CodexBloom - Programming Q&A Platform

Terraform - scenarios Creating AWS IAM Roles with Assume Role Policy Based on External Input

👀 Views: 0 💬 Answers: 1 📅 Created: 2025-06-14
terraform aws iam HCL

I'm working on a project and hit a roadblock. I'm relatively new to this, so bear with me. After trying multiple solutions online, I still can't figure this out. I'm trying to create AWS IAM roles using Terraform, but I'm running into issues with setting up the assume role policy. Specifically, I'm passing in a JSON string for the policy via a variable, and it seems to not be parsing correctly. My code looks like this: ```hcl variable "assume_role_policy" { type = string } resource "aws_iam_role" "example" { name = "example_role" assume_role_policy = var.assume_role_policy } ``` When I call this module, I pass the policy like this: ```hcl module "iam_roles" { source = "./modules/iam_roles" assume_role_policy = jsonencode({ Version = "2012-10-17", Statement = [{ Effect = "Allow", Principal = { Service = "ec2.amazonaws.com" }, Action = "sts:AssumeRole" }] }) } ``` However, I keep getting the following behavior: ``` behavior: Invalid IAM Policy Document on modules/iam_roles/main.tf line 6, in resource "aws_iam_role" "example": 6: assume_role_policy = var.assume_role_policy Invalid function argument: "jsonencode" expects a value of type "any", got an invalid value of type "string". ``` I've double-checked the JSON structure, and it appears to be valid. I’ve also tried hardcoding the JSON directly in the resource without success. Is there something I'm missing with how Terraform is expecting the assume role policy to be formatted when using external input? Any insights would be greatly appreciated. My development environment is Ubuntu. Any help would be greatly appreciated! My development environment is Windows. How would you solve this?