Home > front end >  For loop in terraform
For loop in terraform

Time:12-17

I am trying to get the value of function name from local.tf but I am not able to get it. I have terraform,tfvars in which I am giving the fucntion name then it is passed to variable.tf. From varibale.tf I pass it to local.tf then to main.tf. I am not able to get the fucntion name in main.tf. Any help would be appreciated. terraform.tfvars

config = {
  s3= {
//s3 configurations
}
  s3_notifications = {
      function_name         = "test-lambda-mary"
    }
}

variable.tf

variable "config" {
  type        = any
  description = "S3 configuration block"
}

local.tf

  function_name = {
    for k, v in var.config :
    k => lookup(v, "function_name", "")
  }
module "all_notifications" {
  source   = "terraform-aws-modules/s3-bucket/aws//modules/notification"
  for_each = var.config
  bucket   = module.s3_bucket[each.key].this_s3_bucket_id

  lambda_notifications = {
    lambda = {
      function_name = local.function_name[each.key]
      function_arn  = "arn:aws:lambda:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:function:${local.function_name[each.key]}"
      events        = ["s3:ObjectCreated:*"]

    }
  }
}

error

"function_name" doesn't comply with restrictions ("^(arn:[\\w-] :lambda:)?([a-z]{2}-(?:[a-z] -){1,2}\\d{1}:)?(\\d{12}:)?(function:)?([a-zA-Z0-9-_] )(:(\\$LATEST|[a-zA-Z0-9-_] ))?$"): ""
│ 
│   with module.all_notifications["s3"].aws_lambda_permission.allow["lambda"],
│   on .terraform/modules/all_notifications/modules/notification/main.tf line 63, in resource "aws_lambda_permission" "allow":
│   63:   function_name       = each.value.function_name

CodePudding user response:

A stab in the dark as I haven't used that module before.

But by looking at your error message:

"function_name" doesn't comply with restrictions ("^(arn:[\\w-] :lambda:)?

it looks like for function_name you should pass Lambda's ARN, not name (contrary to what the variable name says).

BTW, is function_arn even a parameter here?

CodePudding user response:

If I put the function_name inside s3 braces it works absolutely fine but I need to have the fucntion name in s3_notification

That looks like a great hint. You're iterating over var.config which has 2 keys and only 1 of them has function_name defined. So when module is requested with s3 as a key, the function_value for that key will be empty string and AWS will fail the request as expected.

You can filter for_each = var.config to exclude such case, something like:

for_each = { for k, v in var.config: k => v if local.function_name[each.key] != ""}

Little nitpick: seems like the source of the module could be incorrectly written. Instead of terraform-aws-modules/s3-bucket/aws//modules/notification potentially it should be terraform-aws-modules/terraform-aws-s3-bucket//modules/notification. See https://github.com/terraform-aws-modules/terraform-aws-s3-bucket

  • Related