Home > Software design >  Terraform resource based on condition stage variable string
Terraform resource based on condition stage variable string

Time:10-28

I am trying to attach a different type of policy to a user in each of my three environments: dev, staging and production.

The environment information is stored as a terraform variable in string format, e.g. 'dev'.

resource "aws_iam_policy" "s3-dev-policy" {
  count       = var.stage != "dev" ? 1 : 0
  name        = "s3-bucket-policy-${var.stage}"
  description = "Access rights for cicd-user to Bucket on Dev"

  policy = <<EOF
{
    "Version": "2012-10-17",
    "Statement": [{
            "Action": [
                "s3:GetObject",
                "s3:ListBucket",
                "s3:PutObject",
                "s3:DeleteObject"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3::: dev-bucket-pushed",
                "arn:aws:s3::: dev-bucket-pushed/*"
            ]
        }
}
EOF
}

resource "aws_iam_group_policy_attachment" "attach_cicd-users_s3_dev_group_policy" {
  count      = var.stage != "dev" ? 1 : 0
  group      = aws_iam_group.cicd-users.name
  policy_arn = aws_iam_policy.s3-dev-policy[count.index]
}

Terraform apply does not complain about the syntax but it does not apply this resource either even though the stage is set to 'dev'. Does the conditional only work with boolean as a data type?

CodePudding user response:

Your condition is incorrect, policy has syntax errors, arn is incorrect, among other problems. It all should be:


resource "aws_iam_policy" "s3-dev-policy" {
  count       = var.stage == "dev" ? 1 : 0
  name        = "s3-bucket-policy111-${var.stage}"
  description = "Access rights for cicd-user to Bucket on Dev"

  policy = <<EOF
{
    "Version": "2012-10-17",
    "Statement": [{
            "Action": [
                "s3:GetObject",
                "s3:ListBucket",
                "s3:PutObject",
                "s3:DeleteObject"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:s3:::dev-bucket-pushed",
                "arn:aws:s3:::dev-bucket-pushed/*"
            ]
        }
       ] 
}
EOF
}


resource "aws_iam_group_policy_attachment" "attach_cicd-users_s3_dev_group_policy" {
  count      = var.stage == "dev" ? 1 : 0
  group      = aws_iam_group.cicd-users.name
  policy_arn = aws_iam_policy.s3-dev-policy[count.index].arn
}
  • Related