CodexBloom - Programming Q&A Platform

Terraform: implementing Using `locals` to Dynamically Generate IAM Policies with Complex Conditions

👀 Views: 54 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-11
terraform aws iam json HCL

I can't seem to get I'm working with difficulties when trying to use `locals` in Terraform to dynamically generate IAM policies with complex conditions. My goal is to create a policy that allows access only if multiple conditions are met, such as the requester's source IP and the presence of a specific tag on the resources. However, the generated policy ends up being malformed, and I'm getting the following behavior during the `terraform plan` phase: `behavior: Invalid JSON: invalid character '}' looking for beginning of object key string`. Here's a simplified version of what I have tried: ```hcl locals { allowed_ips = ["192.168.1.1", "192.168.1.2"] resource_tags = { "Environment" = "Production" "Owner" = "DevTeam" } } resource "aws_iam_policy" "example_policy" { name = "examplePolicy" description = "A policy that allows access based on specific conditions" policy = jsonencode({ Version = "2012-10-17" Statement = [ { Effect = "Allow" Action = "*" Resource = "*" Condition = { StringEquals = { "aws:SourceIp" = join(",", local.allowed_ips) } StringEqualsIfExists = { "aws:ResourceTag/Environment" = local.resource_tags.Environment } } } ] }) } ``` I've tried breaking down the `Condition` into simpler parts, but the behavior continues. Each time I modify the structure, I still end up with either syntax errors or the same malformed JSON scenario. Is there a specific way to format the conditions that I might be missing? Any insights would be greatly appreciated! This issue appeared after updating to Hcl 3.10. What would be the recommended way to handle this? This is my first time working with Hcl latest. Any pointers in the right direction?