Reputation: 1435
I have a terraform project set up an VPC for a region to use for all EKS cluster in that region.
After run terraform apply
successful, I have these output:
Outputs:
all_worker_mgmt_id = "sg-09992bfxxxx13b782"
azs = tolist([
"us-east-2a",
"us-east-2b",
"us-east-2c",
])
public_subnets = [
"subnet-03ac0xxxxe533b510",
"subnet-0f91a04168xxxx9c7",
"subnet-0xxxxcd5cfcaa938c",
]
vpc_cidr_block = "192.168.0.0/16"
vpc_id = "vpc-07e4xxxxxxxx6f616"
In another terraform project set up an EKS cluster, I need to extract the vpc_id
and public_subnets
to use to configure the cluster.
How can I dynamic get above variable 's values without hardcode in configuration?
And does this document (https://registry.terraform.io/providers/hashicorp/aws/latest/docs/data-sources/vpc) use for that?
Upvotes: 4
Views: 3379
Reputation: 434
I usually keep resources separated in terraform and use data
to get the resources that were already created, manually of with other terraform projects.
locals {
environment = "test"
}
data "aws_vpc" "vpc" {
filter {
name = "tag:Name"
values = [local.environment]
}
}
data "aws_subnet_ids" "private_subnets" {
vpc_id = data.aws_vpc.vpc.id
filter {
name = "tag:Name"
values = ["${local.environment}-private-*"]
}
}
data "aws_subnet_ids" "public_subnets" {
vpc_id = data.aws_vpc.vpc.id
filter {
name = "tag:Name"
values = ["${local.environment}-public-*"]
}
}
When you need to get one public
or private
subnet, use sort:
resource "aws_instance" "gitlab" {
...
subnet_id = sort(data.aws_subnet_ids.public_subnets.ids)[0]
...
}
The above code will work perfectly if you use the terraform vpc module
Or, if you want to have a tool that manages all resources at once, you can use Terragrunt
Upvotes: 4