0

Is there a special variable that references the assigned ephemeral external IP address so I can define it in the startup script?

Martin Zeitler
  • 1
  • 19
  • 155
  • 216
zimmerdimmer
  • 39
  • 1
  • 5

2 Answers2

0

Assuming that the NAT IP had already been assigned with --address, as described here:

Assigns the given external address to the instance that is created. The address might be an IP address or the name or URI of an address resource. This option can only be used when creating a single instance.

gcloud compute instances create $INSTANCE_NAME \
    --startup-script $BUCKET/startup.sh \
    --address $EXTERNAL_IP \
    ...

It should be possible to retrieve it again in eg. $BUCKET/startup.sh:

INSTANCE_NAME=$(hostname)

INTERNAL_IP=$(gcloud compute instances describe $INSTANCE_NAME \
    --format='get(networkInterfaces[0].networkIP))

EXTERNAL_IP=$(gcloud compute instances describe $INSTANCE_NAME \
    --format='get(networkInterfaces[0].accessConfigs[0].natIP)')

Source: Locating IP addresses for an instance .


Without --address, you might be getting the INTERNAL_IP, but no EXTERNAL_IP...

gcloud compute addresses can as well list all IP in a project, which are unassigned and then attach one of them. Or create a new one, in case there are no spare IP addresses left. I've already wrote about this once: How to get the current Zone & Project ID in a GCE startup script? Knowing the zone and project ID is the least to start automating anything beside an OS install, because the gcloud command most often depends on these two arguments.


The least effort may be to first create the IP address (outside the container) and then the GCE instance (also outside the container). Even if one can create and assign an IP address later on, it would not be readily available in the startup script, unless providing further script to assign one. One could as well create a whole IP range and then attach a GCE instance to each of the given IP addresses (the other way around as usual).

Martin Zeitler
  • 1
  • 19
  • 155
  • 216
0

If your VM start with an ephemeral IP, you can get it directly from the metadata server at this path /instance/network-interfaces/0/access-configs/0/external-ip

In your startup script, you can include that line if you want to get it

curl -H "Metadata-Flavor: Google" http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/0/access-configs/0/external-ip
guillaume blaquiere
  • 66,369
  • 2
  • 47
  • 76
  • I've managed to find another way using `dig TXT +short o-o.myaddr.l.google.com @ns1.google.com` but yours is also a valid way to get the ephemeral IP. – zimmerdimmer Jul 10 '22 at 14:18