Use file("${path.module}/iam.json") } but still able to use variables?

Is is possible to use variables in json files direct?

See variable ${var.AWS_AccountID}:

resource "aws_iam_policy" "ebs" {
  name        = "test_policy"
  path        = "/"
  description = "EBS Access for eks"

  policy = file("${path.module}/iam.json")
}

iam.json

{
    "Version": "2012-10-17",
    "Statement": [
      {
        "Sid": "VisualEditor1",
        "Effect": "Allow",
        "Action": ["ec2:CreateVolume", "ec2:CreateTags"],
        "Resource": "arn:aws:ec2:eu-central-1:${var.AWS_AccountID}:volume/*"
      }
    ]
  }

Currently it dont get parsed. A working alternative is to use jsonencode() instead. But an own json file has the advantage to use the autoformatting, syntax check and features like editorconfig in Vscode.

You can use templatefile instead of file

1 Like

@stuart-c yes that worked, thanks. :slight_smile:

resource "aws_iam_policy" "ebs" {
  name        = "test_policy"
  path        = "/"
  description = "EBS Access for eks"

  policy = templatefile("${path.module}/IAM EBS.json",
    {
      AWS_AccountID = var.AWS_AccountID
    }
  )
}
{
    "Version": "2012-10-17",
    "Statement": [
      {
        "Sid": "VisualEditor1",
        "Effect": "Allow",
        "Action": ["ec2:CreateVolume", "ec2:CreateTags"],
        "Resource": "arn:aws:ec2:eu-central-1:${var.AWS_AccountID}:volume/*"
      }
    ]
  }