具有多个主题的Terraform s3存储桶通知

时间:2017-07-08 23:32:20

标签: amazon-s3 terraform

我正在尝试为aws_s3_bucket_notification编写灵活/动态资源,该资源可能包含指定s3存储桶的可变主题。对于一个桶,我可能只有2个前缀和2个主题,而其他4或5等等...我正在考虑使用map函数,它将为每个前缀类型存储“前缀”和“SNS ARN”事件将是相同的。我需要创建一个s3_bucket_notification,其中包含所有主题,而无需手动编写每个主题。有什么建议吗?

实施例

resource "aws_s3_bucket_notification" "bucket_notification" {
  bucket = "${aws_s3_bucket.bucket.id}"

  topic {
    topic_arn     = "$map.value" ###prototype
    events        = ["s3:ObjectCreated:*"]
    filter_suffix = "$map.key" ###prototype
  }
}

1 个答案:

答案 0 :(得分:2)

如果我的理解是正确的,代码应该是这样的:

variable "sns_top" {
  type = "map"

  default = {
    dev  = "topic1"
    uat  = "topic2"
    prod = "topic3"
  }
}

variable "bucket_name" {
  default = "my-tf-test-bucket-dfsfddsf"
}

data "aws_caller_identity" "current" {}

resource "aws_sns_topic" "sns_topic" {
  count = "${length(keys(var.sns_top))}"
  name  = "sns-topic-${element(values(var.sns_top),count.index)}"
}

resource "aws_sns_topic_policy" "custom" {
  count = "${length(keys(var.sns_top))}"
  arn   = "${element(aws_sns_topic.sns_topic.*.arn, count.index)}"

  policy = <<POLICY
{
  "Version": "2012-10-17",
  "Id": "default",
  "Statement":[{
    "Sid": "default",
    "Effect": "Allow",
    "Principal": {"AWS":"*"},
    "Action": [
      "SNS:GetTopicAttributes",
      "SNS:SetTopicAttributes",
      "SNS:AddPermission",
      "SNS:RemovePermission",
      "SNS:DeleteTopic"
    ],
    "Resource": "${element(aws_sns_topic.sns_topic.*.arn, count.index)}"
  }]
}
POLICY

  depends_on = ["aws_sns_topic.sns_topic"]
}

resource "aws_s3_bucket" "bucket" {
  bucket = "${var.bucket_name}"
}

data "aws_iam_policy_document" "default" {
  statement {
    effect = "Allow"

    actions = [
      "s3:PutObject",
    ]

    resources = [
      "${aws_s3_bucket.bucket.arn}/*",
    ]

    principals {
      type        = "AWS"
      identifiers = ["arn:aws:iam::${data.aws_caller_identity.current.account_id}:root"]
    }
  }
}

resource "aws_s3_bucket_policy" "default" {
  bucket = "${aws_s3_bucket.bucket.id}"
  policy = "${data.aws_iam_policy_document.default.json}"
}

resource "aws_s3_bucket_notification" "bucket_notification" {
  count  = "${length(keys(var.sns_top))}"
  bucket = "${aws_s3_bucket.bucket.id}"

  topic {
    topic_arn     = "${element(aws_sns_topic.sns_topic.*.arn, count.index)}"
    events        = ["s3:ObjectCreated:*"]
    filter_suffix = "${element(keys(var.sns_top),count.index)}"
  }
}

代码遇到了以下链接中解释的错误,但您可以将其用于进一步编码,例如如何将count.index用于地图。

* aws_s3_bucket_notification.bucket_notification.0: Error putting S3 notification configuration: InvalidArgument: Unable to validate the following destination configurations

参见:

How do I avoid the error "Unable to validate the following destination configurations" when using S3 event notifications in CloudFormation?