I would like to source existing aws security group information allowing for them to be referenced by name rather than id.
I can reference a single existing instance using:
data "aws_security_groups" "single" {
filter {
name = "group-name"
values = ["Foo-all"]
}
}
output "singlename" {
value = "${data.aws_security_groups.single.ids[0]}"
}
This isn't ideal, as I would need to enter all the security group ids as their own block.
I can get all of the attributes for all of the security groups printed using:
data "aws_security_groups" "sgroups" {
filter {
name = "vpc-id"
values = ["${data.aws_vpc.vpc.id}"]
}
}
data "aws_security_group" "instances" {
count = length(data.aws_security_groups.sgroups.ids)
id = data.aws_security_groups.test.ids[count.index]
}
output "groupinfo" {
value = "${data.aws_security_group.instances}"
}
This isn't useful, to me, as I want a Name = id mapping.
What I'm hoping to do is define all of the existing security groups as a map so I could do something like the following:
resource "aws_instance" "fooTest" {
ami = "${var.ami}"
instance_type = "t2.nano"
subnet_id = "${var.subnets["Foo-net"]}"
key_name = "Fookey"
vpc_security_group_ids = [
"${var.existingsgs["Foo-all"]}",
]
}
Can this be done? Or is there a better way of achieving name based security group references?
I dont think you can output a map, you should be able to output a list of sec group id's using a data source like you've done with your example code. Take that a step further by filtering the data source to grab resources that are tagged with specific labels. Then just reference the data resource inside your aws_instance resource block.
Example by request:
To read existing vpc and security groups use a data source. Select the desired target by filtering on specific tags that are applied to the vpc and security groups.
data "aws_vpc" "my_vpc" {
tags = {
Project = "my_vpc"
Environment = "qa"
}
}
data "aws_security_group" "my_sg" {
vpc_id = "${data.aws_vpc.my_vpc.id}"
tags = {
Name = "my_sg"
Environment = "qa"
}
}
When you create your resource you can reference the data sources you have grabbed. Remember data sources are read first to make them available to use when creating additional resources.
resource "aws_instance" "fooTest" {
ami = "${var.ami}"
instance_type = "t2.nano"
subnet_id = "${var.subnets["Foo-net"]}"
key_name = "Fookey"
vpc_security_group_ids = ["${data.aws_security_group.my_sg.ids}"]
}
You can also do the same thing with subnets, nearly anything that exists in AWS can be read into a data source block for referencing when creating additional resources.
https://www.terraform.io/docs/configuration/data-sources.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With