Lambda layer permission for multiple account

I am working on the lambda layer permission for multiple AWS account.

So i am trying use a variable “list_accounts“ as a list of string and pass to module. I tried different way:

using for_each with for

resource "aws_lambda_layer_version_permission" "account" {
  for_each       = { for id in var.list_accounts: id => id }
  layer_name     = aws_lambda_layer_version.example.layer_name
  version_number = aws_lambda_layer_version.example.version
  principal      = each.value
  action         = "lambda:GetLayerVersion"
  statement_id   = "account-${each.value}"
}

using for_each with toset

resource "aws_lambda_layer_version_permission" "account" {
  for_each       = toset(var.list_accounts)
  layer_name     = aws_lambda_layer_version.example.layer_name
  version_number = aws_lambda_layer_version.example.version
  principal      = each.value
  action         = "lambda:GetLayerVersion"
  statement_id   = "account-${each.value}"
}

so i tried to pass the list_accounts like

list_accounts = ["123","234","345"]

It work first time. But when i add a new account

list_accounts = ["123","234","345","456"]

Terraform plan say it will create 4 permission and destroy 3 (which is not under my expectation by using for_each). Also when i apply, the permssion are not all destroy before create so it provide “ResourceConflictException : The statement id ‘123‘ provided already exists“

So my question are:

  1. is that i use the for_each in the wrong way? (i expected that only change resource will be add/remove but not remove all and create again)
  2. in the worst case, how we may make sure all resource are destory before re-created?

thx

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.