CodexBloom - Programming Q&A Platform

Problems with IAM Role Policy Attachment in Terraform for AWS Lambda Function

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

I'm confused about Does anyone know how to I'm refactoring my project and I'm sure I'm missing something obvious here, but I'm sure I'm missing something obvious here, but I've been banging my head against this for hours... I'm trying to create an AWS Lambda function with an associated IAM role using Terraform, but I'm running into issues when attaching the policy to the role. My current setup looks like this: ```hcl resource "aws_iam_role" "lambda_role" { name = "lambda_execution_role" assume_role_policy = jsonencode({ Version = "2012-10-17" Statement = [ { Action = "sts:AssumeRole" Principal = { Service = "lambda.amazonaws.com" } Effect = "Allow" Sid = "" } ] }) } resource "aws_iam_policy" "lambda_policy" { name = "lambda_basic_execution" description = "IAM policy for Lambda function to write logs" policy = jsonencode({ Version = "2012-10-17" Statement = [ { Action = ["logs:CreateLogGroup", "logs:CreateLogStream", "logs:PutLogEvents"], Resource = "*", Effect = "Allow" } ] }) } resource "aws_iam_role_policy_attachment" "lambda_policy_attachment" { policy_arn = aws_iam_policy.lambda_policy.arn role = aws_iam_role.lambda_role.name } resource "aws_lambda_function" "my_lambda" { function_name = "MyLambdaFunction" role = aws_iam_role.lambda_role.arn handler = "index.handler" runtime = "nodejs14.x" source_code_hash = filebase64sha256("path/to/your/code.zip") } ``` When I apply this configuration, I encounter the following behavior: ``` behavior: creating IAM Role Policy Attachment: InvalidParameterValue: Role 'lambda_execution_role' is not found. ``` I double-checked the role name, and it's correctly defined in the `aws_iam_role` resource. I also ensured that the IAM role is successfully created before the policy attachment is attempted. I've tried running `terraform apply` again, but I keep getting the same behavior. I suspect it might be related to the order of resource creation or a missing dependency, but I'm not sure how to resolve this. Can anyone guide to figure out what's going wrong? My development environment is Linux. Thanks in advance! Thanks in advance! This is my first time working with Hcl latest. This is for a REST API running on Windows 10. Any pointers in the right direction?