CodexBloom - Programming Q&A Platform

Terraform: scenarios Creating Nested IAM Policies with Dynamic Block for Multiple Actions

👀 Views: 93 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
terraform aws iam hcl

I'm collaborating on a project where I've spent hours debugging this and I'm working on a Terraform configuration to create an AWS IAM role with multiple policies using dynamic blocks... However, I'm working with an behavior when trying to reference dynamic actions from a list. Here's the relevant portion of my Terraform code: ```hcl variable "actions" { type = list(string) default = ["s3:ListBucket", "s3:GetObject"] } resource "aws_iam_role" "my_role" { name = "my_role" assume_role_policy = jsonencode({ Version = "2012-10-17" Statement = [{ Effect = "Allow" Principal = { Service = "ec2.amazonaws.com" } Action = "sts:AssumeRole" }] }) } resource "aws_iam_policy" "my_policy" { name = "my_policy" description = "A policy for S3 actions" policy = jsonencode({ Version = "2012-10-17" Statement = [ for action in var.actions : { Effect = "Allow" Action = action Resource = "*" } ] }) } resource "aws_iam_role_policy_attachment" "attach_policy" { role = aws_iam_role.my_role.name policy_arn = aws_iam_policy.my_policy.arn } ``` When I run `terraform apply`, I'm getting the following behavior message: ``` behavior: Failed to parse JSON: json: want to unmarshal array into Go struct field Policy.Statement of type map[string]interface {} ``` I've tried various configurations, including different ways to structure the dynamic block, but the behavior continues. I'm using Terraform version 1.3.7. I suspect that the scenario lies in how the dynamic block is handling the list of actions, but I'm not sure how to resolve it. Can anyone provide guidance on correcting this behavior while adhering to best practices for IAM policy creation in Terraform? This is part of a larger service I'm building. Cheers for any assistance! I'm using Hcl stable in this project. Has anyone dealt with something similar? My team is using Hcl for this REST API. How would you solve this? For context: I'm using Hcl on Ubuntu 22.04.