Cannot get public IP address of spot instance created

Hello,

I’m spinning up a spot instance as you can see in below config and then trying to get the IP address from the spot. It seems to work fine with a regular ec2 instance (ie. that is not spot instance).

The error that I get is:

aws_route53_record.staging: Resource ‘aws_spot_instance_request.app-ec2’ does not have attribute ‘public_ip’ for variable ‘aws_spot_instance_request.app-ec2.public_ip’

Here is the config that I’m using:

    resource "aws_spot_instance_request" "app-ec2" {
    ami = "ami-1c999999"
    spot_price    = "0.0075"
    instance_type = "t2.small"
    tags {
        Name = "${var.app_name}"
    }
    key_name = "mykeypair"
    associate_public_ip_address = true
    vpc_security_group_ids = ["sg-99999999"]
    subnet_id = "subnet-99999999"
    iam_instance_profile = "myInstanceRole"
    user_data = <<-EOF
#!/bin/bash
echo ECS_CLUSTER=APP-STAGING >> /etc/ecs/ecs.config
    EOF
}

resource "aws_route53_record" "staging" {
   zone_id = "XXXXXXXX"
   name = "staging.myapp.com"
   type = "A"
   ttl = "300"
   records = ["${aws_spot_instance_request.app-ec2.public_ip}"]

Any help will be greatly appreciated!

So I’ve been trying to figure this out since last night and kept seeing the spot instance request being fulfilled via the AWS Console. Likewise, I could see the public IP for the spot and this was misleading me.

It turns out I was missing 1 line (argument) in my script:

wait_for_fulfillment = true

By default, it is set to false, and therefore when I tried to set the public_ip address it simply did not exist at that time.

Now Terraform will wait for the Spot Request to be fulfilled. According to the documentation, it will throw an error if the timeout of 10m is reached.