terraform,

Fix Terraform 'Error creating Elastic IP: InvalidInstanceID.Malformed: Invalid id'

Apr 08, 2023 · 1 min read · Post a comment

If you have a Terraform configuration that creates an EC2 instance and an Elastic IP address, you should be aware that the Elastic IP address depends on the instance. If you accidentally remove the depends_on argument for the Elastic IP resource, Terraform will attempt to create the Elastic IP before the EC2 instance and you will get the following error:

Error: Error creating Elastic IP: InvalidInstanceID.Malformed: Invalid id: "": must be a valid EC2 instance id
        status code: 400, request id: abcd1234-5678-efgh-ijkl-1234567890ab

Let’s see how to resolve it.

Prerequisites

  • Terraform

Solution

  • If your Terraform configuration is something like this:
resource "aws_instance" "my_instance" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  # ...
}

resource "aws_eip" "my_eip" {
  vpc = true
  # ...
}

you will get the dependency error

Error: Error creating Elastic IP: InvalidInstanceID.Malformed: Invalid id: "": must be a valid EC2 instance id
        status code: 400, request id: abcd1234-5678-efgh-ijkl-1234567890ab

  on main.tf line 15, in resource "aws_eip" "my_eip":
  15: resource "aws_eip" "my_eip" {
  • To resolve the issue you need to add the depends_on argument to the Elastic IP resource and specify the EC2 instance resource as a dependency. This ensures that Terraform will create the EC2 instance first before attempting to create the Elastic IP address.
resource "aws_instance" "my_instance" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t2.micro"
  # ...
}

resource "aws_eip" "my_eip" {
  vpc = true
  depends_on = [
    aws_instance.my_instance
  ]
  # ...
}

Conclusion

Feel free to leave a comment below and if you find this tutorial useful, follow our official channel on Telegram.