Skip to content

Instantly share code, notes, and snippets.

@fprimex
Last active May 24, 2021 00:39
Show Gist options
  • Save fprimex/4787215b5cda3d6f60ed26a25d8ed7dd to your computer and use it in GitHub Desktop.
Save fprimex/4787215b5cda3d6f60ed26a25d8ed7dd to your computer and use it in GitHub Desktop.
Use Terraform to track a subnet's tags and add your own.
# Put the tags you wish to have added to the subnet in this map variable.
variable "my_tags" {
type = "map"
default = {
my_first_key = "my first value"
my_second_key = "my second value"
}
}
# This reads the subnet and supplies all of the information about it, including
# its tags. You need to know the subnet ID or have some other way of finding it
# using Terraform, such as using data.subnet_ids with a tags filter.
data "aws_subnet" "existing_sn" {
id = "subnet-02ca159710a1a2af2"
}
# These locals do the following:
# 1. Combine the tags from the subnet with the tags variable. The tags variable
# overrides since it comes last.
# 2. Takes each key and value from the map and produces a string Key=<the key>,Value="<the value>".
# 3. Joins each of those with a space, so that there is now
# Key="<the key1>",Value="<the value1>" Key="<the key2>",Value="<the value2>" ...
# This is the argument to --tags
locals {
combined_tags = "${merge(data.aws_subnet.existing_sn.tags, var.my_tags)}"
existing_tags = "${join(" ", formatlist("Key=\"%s\",Value=\"%s\"", keys(local.combined_tags), values(local.combined_tags)))}"
}
resource "null_resource" "tag_updater" {
# This trigger will cause the script to run any time terraform runs and sees
# that the tags on the subnet have changed. Each value in triggers should be
# a string, so existing_tags local is used, which is one big string of all
# of the tags.
# Note that this will fire and run the command if tags are added to the
# subnet by sources outside of this configuration, because it changes the
# string of tags.
triggers {
subnet_tags = "${local.existing_tags}"
}
# When the trigger fires the following command will run. The aws command has
# to be installed. Moving this command to a script will unfortunately result
# in a lot of shell quoting pain, so I don't advise it.
provisioner "local-exec" {
command = "aws ec2 create-tags --resources ${data.aws_subnet.existing_sn.id} --tags ${local.existing_tags}"
}
}
@fprimex
Copy link
Author

fprimex commented Feb 21, 2019

I added quotes around the key ("Key=%s,Value=\"%s\"" to "Key=\"%s\",Value=\"%s\"") without testing FYI.

@fprimex
Copy link
Author

fprimex commented Feb 22, 2019

Updated the comments to correct some things.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment