Skip to content

Instantly share code, notes, and snippets.

@arehmandev
Last active September 1, 2023 12:23
Show Gist options
  • Save arehmandev/944facad9159920a64346c3570dcb5d3 to your computer and use it in GitHub Desktop.
Save arehmandev/944facad9159920a64346c3570dcb5d3 to your computer and use it in GitHub Desktop.
# Pull in existing VPC
data "aws_vpc" "selected" {
id = var.vpc_id
}
# Subnet ids data source lookup allows multiple subnets to be provided
data "aws_subnet_ids" "private" {
vpc_id = data.aws_vpc.selected.id
filter {
name = "tag:Name"
values = ["*private*"]
}
}
# Pull in all private subnet CIDR Blocks for a for_each as this data source allows only 1 subnet
data "aws_subnet" "private_subnet_cidr" {
for_each = data.aws_subnet_ids.*.id
id = each.value
}
# Try to attach tags to all those subnet ID's.
resource "aws_subnet" "private_subnet_tags" {
for_each = values(data.aws_subnet.private_subnet_cidr).*.cidr_block
vpc_id = data.aws_vpc.selected.id
cidr_block = each.value
tags = {
"PRIVATETAGONE" = "HELLOWORLD"
"PRIVATETAGTWO" = "HELLOWORLD"
}
}
variable "tag_map" {
default = {
"PRIVATETAGONE" = "HELLOWORLD"
"PRIVATETAGTWO" = "HELLOWORLD"
}
}
locals {
formatted_tags = join(" ", formatlist("Key='%s',Value='%s'", keys(var.tag_map), values(var.tag_map)))
}
# Pull in existing VPC
data "aws_vpc" "selected" {
id = var.vpc_id
}
# Subnet ids data source lookup allows multiple subnets to be provided
data "aws_subnet_ids" "private" {
vpc_id = data.aws_vpc.selected.id
filter {
name = "tag:Name"
values = ["*private*"]
}
}
# Use this option if you dont want to import state
resource "null_resource" "tagger" {
for_each = data.aws_subnet_ids.private.*.id
triggers = {
tags = local.formatted_tags
}
provisioner "local-exec" {
command = "aws ec2 create-tags --resources ${each.value} --tags ${local.formatted_tags}"
}
provisioner "local-exec" {
when = "destroy"
command = "aws ec2 delete-tags --resources ${each.value} --tags ${local.formatted_tags}"
}
}
@arehmandev
Copy link
Author

Coming across 2 reference issues, but I'm digging into to see what I can find:

Error: Invalid reference

  on main.tf line 69, in resource "null_resource" "tagger":
  69:   for_each = data.aws_subnet_ids.*.id

The "data" object must be followed by two attribute names: the data source
type and the resource name.


Error: Incorrect attribute value type

  on main.tf line 70, in resource "null_resource" "tagger":
  70:   triggers = local.formatted_tags

Sry small syntax errors, updated

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