Last active
September 1, 2023 12:23
-
-
Save arehmandev/944facad9159920a64346c3570dcb5d3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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" | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sry small syntax errors, updated