Leo
Leo

Reputation: 5122

Override part of a variable

I have a base module which contains the following:

locals {
  common_tags = {
    Name          = var.name
    AssetID       = var.AssetID
    AssetName     = var.AssetName
    AssetGroup    = var.AssetGroup
    AssetPurpose  = var.AssetPurpose
    AssetProgram  = var.AssetProgram
    AssetSchedule = var.AssetSchedule
  }
}

output "Tags" {
  value = local.common_tags
}

In my other modules I use these tags by importing the module and referencing to it - ie.

module "base" {
  source = "../base"
}

resource "aws_ecs_cluster" "ecs_cluster" {
  name  = "my_cluster"
  tags = module.base.Tags
}

Now for one of the resources, I need to do the same and use most of the tags apart from one, which will be different ie.

resource "aws_subnet" "private_subnet" {
  count             = length(var.aws_zones)
  vpc_id            = aws_vpc.vpc.id
  availability_zone = element(var.aws_zones, count.index)
  cidr_block        = element(var.private_subnets, count.index)
  tags = {
    Name          = "private-${var.name}-${element(var.aws_zones, count.index)}"  
    AssetID       = var.AssetID
    AssetName     = var.AssetName
    AssetGroup    = var.AssetGroup
    AssetPurpose  = var.AssetPurpose
    AssetProgram  = var.AssetProgram
    AssetSchedule = var.AssetSchedule
  }
}

Is there a way I can do this without having to rebuild the whole object and having to refer to all these variables in the base module?

Upvotes: 0

Views: 499

Answers (1)

Alain O'Dea
Alain O'Dea

Reputation: 21686

This is an ideal case for the merge function:

resource "aws_subnet" "private_subnet" {
  count             = length(var.aws_zones)
  vpc_id            = aws_vpc.vpc.id
  availability_zone = element(var.aws_zones, count.index)
  cidr_block        = element(var.private_subnets, count.index)
  tags = merge(module.base.tags, {
    Name          = "private-${var.name}-${element(var.aws_zones, count.index)}"  
  })
}

merge takes an arbitrary number of maps and returns a single map that contains a merged set of elements from all of the maps.

Upvotes: 1

Related Questions