How to receive public ipv4 from AWS ECS via Terraform
Hello everyone! I want to share with you my Terraform solution which allows to receive public IP address from Elastic Container Service Tasks.
You have simple service like that:
resource "aws_ecs_service" "test" {
name = "test"
cluster = data.aws_ecs_cluster.test.id
task_definition = aws_ecs_task_definition.test.id
launch_type = "FARGATE"
desired_count = 1
network_configuration {
subnets = ["test"]
security_groups = ["test"]
assign_public_ip = true
}
}
Let`s add "enable_ecs_managed_tags = true" , it allows you to see services what connected with Elastic Network Interface (ENI IP), we enabled it by "assign_public_ip = true" line
resource "aws_ecs_service" "test" {
name = "test"
cluster = data.aws_ecs_cluster.test.id
task_definition = aws_ecs_task_definition.test.id
launch_type = "FARGATE"
desired_count = 1
enable_ecs_managed_tags = true
network_configuration {
subnets = ["test"]
security_groups = ["test"]
assign_public_ip = true
}
}
Now we can find the ENI with "aws:ecs:serviceName" tag using this data source:
data "aws_network_interfaces" "test" {
tags = {
"aws:ecs:serviceName" = aws_ecs_service.test.name
}
}
We receive the ID with this data source , next step to find our public Ipv4 from this interface:
data "aws_network_interface" "eni-ip" {
depends_on = [ aws_ecs_service.test ]
id = data.aws_network_interfaces.test.ids[0]
}
It`s done. You can receive your IP and get via output:
output "eni_ip" {
value = data.aws_network_interface.eni-ip.association[0].public_ip
}
Expertise Back (Java Spring/NodeJS) Architecture distribuée (Cloud AWS/Google Cloud Platform | Terraform) Fullstack (compétences Angular & React)
11 个月What do you do if your IP changes, do you re-apply your Terraform?
IT Infrastructure as a service || DevOps || as a lifestyle
11 个月Maybe it is now better to share how to not receive public IP from AWS, since now they are all paid :)