Terraform 1.4.3: how to to Configure Custom IAM Policy for Lambda Role with Dynamic Conditions
I'm maintaining legacy code that I'm confused about I'm a bit lost with I've searched everywhere and can't find a clear answer... I'm currently trying to set up a custom IAM policy for an AWS Lambda function using Terraform 1.4.3, but I'm working with issues when adding dynamic conditions based on environment variables. I've defined a role for the Lambda function as follows: ```hcl resource "aws_iam_role" "lambda_role" { name = "my_lambda_role" assume_role_policy = aws_iam_policy_document.lambda_assume_policy.json } resource "aws_iam_policy" "lambda_policy" { name = "my_lambda_policy" description = "A policy for accessing S3 and DynamoDB" policy = jsonencode({ Version = "2012-10-17" Statement = [ { Effect = "Allow" Action = ["s3:ListBucket"], Resource = [var.bucket_arn], Condition = { "StringEquals" = { "s3:prefix" = var.environment == "prod" ? "prod/" : "dev/" } } }, { Effect = "Allow" Action = ["dynamodb:GetItem"], Resource = [var.dynamodb_table_arn] } ] }) } resource "aws_iam_role_policy_attachment" "lambda_role_policy_attachment" { policy_arn = aws_iam_policy.lambda_policy.arn role = aws_iam_role.lambda_role.name } ``` The question arises when I try to apply this configuration. I'm getting the following behavior: ``` behavior: Invalid JSON in IAM policy on main.tf line 14, in resource "aws_iam_policy" "lambda_policy": 14: Condition = { The specified condition key is invalid for the action. ``` I've verified that the variable `environment` is being passed correctly as an input variable. It seems like the condition syntax might not work as expected in the context of the IAM policy. I've also tried simplifying the `Condition` block to just a fixed value, and it works without issues. However, I need dynamic conditions based on the environment because I want to restrict access to specific paths in the S3 bucket depending on the environment. Has anyone faced a similar scenario or can suggest how to properly implement dynamic conditions in IAM policies within Terraform? Any help would be greatly appreciated! This is part of a larger web app I'm building. Is this even possible? I'm developing on Windows 10 with Hcl. I'm working with Hcl in a Docker container on CentOS. What are your experiences with this?