22

How can this S3 bucket IAM policy, which has multiple conditions, be re-written as aws_iam_policy_document data block, please?

    "Condition": {
      "StringEquals": {
          "s3:x-amz-acl": "bucket-owner-full-control",
          "aws:SourceAccount": "xxxxxxxxxxxx"
      },
      "ArnLike": {
          "aws:SourceArn": "arn:aws:s3:::my-tf-test-bucket"
      }
    }

With the aws_iam_policy_document condition data block syntax 1:

    condition {
      test = "StringEquals"
      values = []
      variable = ""
    }
UrbanConor
  • 162
  • 1
  • 5
  • 16
Maciej
  • 1,209
  • 4
  • 16
  • 26

1 Answers1

38

The aws_iam_policy_document supports multiple condition directives.

The following Terraform configuration should help:

data "aws_iam_policy_document" "test" {
  statement {
    effect = "Deny"
    actions = ["backup:*"]
    resources = ["*"]

    condition {
      test     = "StringEquals"
      values   = ["bucket-owner-full-control"]
      variable = "s3:x-amz-acl"
    }

    condition {
      test     = "StringEquals"
      values   = ["xxxxxxxxxxxx"]
      variable = "aws:SourceAccount"
    }

    condition {
      test     = "ArnLike"
      values   = ["arn:aws:s3:::my-tf-test-bucket"]
      variable = "aws:SourceArn"
    }
  }
}

output "policy" {
    value = data.aws_iam_policy_document.test.json
}

If we do a terraform plan on that we will get:

terraform plan
data.aws_iam_policy_document.test: Reading...
data.aws_iam_policy_document.test: Read complete after 0s [id=3933526891]

Changes to Outputs:
  + policy = jsonencode(
        {
          + Statement = [
              + {
                  + Action    = "backup:*"
                  + Condition = {
                      + ArnLike      = {
                          + "aws:SourceArn" = "arn:aws:s3:::my-tf-test-bucket"
                        }
                      + StringEquals = {
                          + "aws:SourceAccount" = "xxxxxxxxxxxx"
                          + "s3:x-amz-acl"      = "bucket-owner-full-control"
                        }
                    }
                  + Effect    = "Deny"
                  + Resource  = "*"
                },
            ]
          + Version   = "2012-10-17"
        }
    )
Helder Sepulveda
  • 15,500
  • 4
  • 29
  • 56
jasonwalsh
  • 756
  • 5
  • 9
  • 1
    Is this still the case? When I implement the same configuration as given in this answer, terraform warns, "Attribute redefined The argument "condition" was already set at foo/bar/s3.tf. Each argument may only be set once" on `terraform plan` – UrbanConor Mar 01 '22 at 11:07
  • Past @UrbanConor should have been paying more attention... My problem was with stating `condition`s with an `=` as are how some other attributes are! State `condition` as `condition {}` not `condition = {...}`! – UrbanConor Apr 13 '22 at 15:33