GCP: assign/remove ephemeral IP to an existing instance

With Google Cloud SDK you could use a workflow like the following:

Set up some variables;

instance=instance-1
zone=asia-northeast2-a

Set an external ephemeral ipv4 address for the instance, issue the maintainance commands to it, and unset its external ephemeral ipv4 address;

gcloud compute instances add-access-config $instance --zone=$zone

gcloud compute ssh $instance --zone=$zone --command="maintenance #..."

gcloud compute instances delete-access-config $instance --zone=$zone

Correspondent Cloud SDK documentation links are instances/describe, instances/add-access-config, ssh and instances/delete-access-config.


Found it after some (too long) time exploring the deep part of gcloud documentation.

In the section dedicated to assign static external IP address to an instance (yes in the static part) it says in a small note:

"If you intend to use an ephemeral external IP address, you can skip this step, and Compute Engine will randomly assign an ephemeral external IP address."

https://cloud.google.com/compute/docs/ip-addresses/reserve-static-external-ip-address#ipassign

So the "key" word is to add an accessConfig to your instance like:

gcloud compute instances add-access-config [INSTANCE_NAME] \
--access-config-name "[ACCESS_CONFIG_NAME]" 

In the example, there is a --address [IP_ADDRESS] option to assign the static external IP but, as the note said, it is optional. Frankly, not easy to find!