Terraform 跳过 null for_each

Raj*_*Raj 1 amazon-web-services terraform terraform-provider-aws

我正在为 AMI 设置标签。我有 ubuntu 和 EKS AMI,其中 EKS AMI 需要设置 k8s 版本、containerd 等,其他操作系统不需要这些。我已将 EKS 特定的所有变量声明为默认为 null,假设在运行 for_each 时它们会跳过,但会出错。这是代码和错误。

locals {

  tags = {
    docker_version = var.docker_version
    kubernetes = var.k8s_version
    cni_plugin_version = var.cni_plugin_version
    containerd_version = var.containerd_version
    target = var.target
    source_ami_id = var.source_ami_id
    Release = var.ami_release-version
    Description = var.ami_description
    Name = var.ami_name
    Creator = var.creator
  }

data "aws_ami" "ami_image" {
  most_recent      = true
  owners           = ["xxxxxxxx"]
  name_regex = var.ami_regex
}

output "ami_id" {
  value = data.aws_ami.ami_image.id
}
output "ami_arn" {
  value = data.aws_ami.ami_image.arn
}
output "ami_name" {
  value = data.aws_ami.ami_image.name
}

resource "aws_ec2_tag" "ami-taggging" {
  resource_id = data.aws_ami.ami_image.id
  for_each    = local.tags
  key         = each.key
  value       = each.value
}

Run Code Online (Sandbox Code Playgroud)

当值为空时出错:

Error: Missing required argument
  on main.tf line 41, in resource "aws_ec2_tag" "ami-tagging":
  41:   value       = each.value
Run Code Online (Sandbox Code Playgroud)

如果值为空,是否有办法跳过或优雅地移动到下一条记录。

Mar*_*cin 5

假设default_tags(您的问题中未显示)与您的类似local.tag,您可以执行以下操作:

resource "aws_ec2_tag" "ami-taggging" {
  resource_id = data.aws_ami.ami_image.id
  for_each    = {for k,v in local.tags: k => v if v != null}
  key         = each.key
  value       = each.value
}
Run Code Online (Sandbox Code Playgroud)

该解决方案用于表达。基本上,它会获取您的原始local.tags地图并创建将在for_each. 新映射将具有相同的键和值 (k=>v),除了那些不满足条件的键和值if