Search code examples
amazon-web-servicesterraformterraform-provider-aws

Terraform skip null for_each


I am setting tags to AMI. I have ubuntu and EKS AMI, where EKS AMI needs to be set with k8s version, containerd etc which are not required for other OS. I have declared all variables that are EKS specific to default to null in an assumption that they will skipped while I run for_each but it errors out. Here is the code and error.

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
}

Error when values are null:

Error: Missing required argument
  on main.tf line 41, in resource "aws_ec2_tag" "ami-tagging":
  41:   value       = each.value

Is there a way to skip or gracefully move to next record if the value is null.


Solution

  • Assuming that default_tags (not shown in your question) is similar to your local.tag, you could do the following:

    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
    }
    

    The solution uses for expression. Basically, it takes your original local.tags and creates new temporary map that will be used in the for_each. The new map will have same keys and values (k=>v) except those that don't meet the if condition.