Reputation: 216
Is it possible to get a list of the public IPs of the NAT gateways in a VPC, using a Terraform data source?
An example of getting a list of subnet ids is shown here, but it is predicated on the aws_subnet_ids data source, which returns a list to start with.
We've got NAT gateways per private subnet. I'm not finding a way to get the list of NAT gateways in a vpc and then get the public IPs from that list.
Has anyone needed and/or solved this issue?
Upvotes: 3
Views: 1585
Reputation: 54
Try this code.
terraform {
required_providers {
shell = {
source = "scottwinkler/shell"
version = "1.7.10"
}
}
}
provider "shell" {
# Configuration options
}
data "shell_script" "nat_gateways" {
lifecycle_commands {
read = <<-EOF
aws ec2 describe-nat-gateways --region ${var.region}
EOF
}
}
locals {
nat_gw_ips = flatten([
for elem in jsondecode(data.shell_script.nat_gateways.output.NatGateways):
format("${elem.NatGatewayAddresses[0].PublicIp}%s", "/32")
])
}
output "natgwips" {
value = local.nat_gw_ips
}
Upvotes: 0
Reputation: 31
This workaround worked for me https://github.com/hashicorp/terraform-provider-aws/issues/7575
My code sample
data "aws_nat_gateway" "nat_gw" {
for_each = toset(module.vpc.public_subnets)
subnet_id = each.value
}
Get public IP of NAT to add as source for an Security group
resource "aws_security_group_rule" "allow_https"{
type = "ingress"
security_group_id = module.sg.id
from_port = "443"
to_port = "443"
protocol = "tcp"
cidr_blocks = [ for v in data.aws_nat_gateway.nat_gw : format("${v.public_ip}%s", "/32") ]
}
Upvotes: 2