How to Create Elastic IP with Terraform: Simple Guide
To create an Elastic IP in Terraform, use the
aws_eip resource with required arguments like vpc set to true if using VPC. This resource allocates a static public IP address that you can associate with your AWS instances.Syntax
The aws_eip resource creates an Elastic IP address in AWS. Key parts include:
- resource "aws_eip" "name": Defines the Elastic IP resource.
vpc = true: Specifies the Elastic IP is for a VPC (Virtual Private Cloud).instance = aws_instance.example.id: (Optional) Associates the Elastic IP with an EC2 instance.
terraform
resource "aws_eip" "example" { vpc = true instance = aws_instance.example.id }
Example
This example shows how to create an Elastic IP and associate it with an EC2 instance in a VPC.
terraform
provider "aws" { region = "us-east-1" } resource "aws_instance" "example" { ami = "ami-0c55b159cbfafe1f0" instance_type = "t2.micro" } resource "aws_eip" "example" { vpc = true instance = aws_instance.example.id }
Output
Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
Outputs:
aws_eip.example.public_ip = "54.210.123.45"
Common Pitfalls
Common mistakes when creating Elastic IPs with Terraform include:
- Not setting
vpc = truewhen using a VPC, causing allocation failure. - Trying to associate an Elastic IP with an instance that does not exist or is in a different region.
- Forgetting to specify the
instanceargument if you want automatic association.
terraform
resource "aws_eip" "wrong" { # Missing vpc = true causes error in VPC instance = aws_instance.example.id } # Correct way resource "aws_eip" "right" { vpc = true instance = aws_instance.example.id }
Quick Reference
Remember these tips when creating Elastic IPs with Terraform:
- Always set
vpc = trueif your instance is in a VPC. - Use
instanceto associate the IP automatically. - Elastic IPs are regional; ensure your provider region matches your resources.
Key Takeaways
Use the aws_eip resource with vpc = true to create Elastic IPs in a VPC.
Associate Elastic IPs with instances using the instance argument for automatic binding.
Ensure your AWS provider region matches your resources to avoid allocation errors.
Common errors come from missing vpc flag or wrong instance references.
Terraform applies will show the allocated Elastic IP address in the output.