GCP: retrieving the full subnet qualification from a shared VPC network

If you are working in a gcp project where the VPC networks are homed within the project itself, then specifying a subnet in gcloud calls is simple, just use the name of the subnet (e.g. ‘default’).

However, if you are working in a gcp project where the VPC networks are shared (not owned) with the project, then you need to specify the fully qualified path to the subnet.   This can be specified via convention:

projects/<sharedProjectId>/regions/<regionId>/subnetworks/<subnetName>

Or by looking up the fully qualified subnet in the project sharing it as shown below.

# name of project sharing the vpc subnet, and subnet name
gcp_shared_project="sharedproj"
gcp_subnet_name="sharednetwork"

# get shared project id, where vpc network is located
gcp_shared_project_id=$(gcloud projects list --filter="name ~ ^$gcp_shared_project" --format="csv(projectId)" | tail -n+2)

# switch to shared project
echo "shared project id: $gcp_shared_project_id"
gcloud config set project $gcp_shared_project_id

# human readable view of networks in shared project
gcloud compute networks list

# retrieve full subnet path from vpc shared project
gcp_subnet_full=$(gcloud compute networks subnets list --filter="name ~ ^$gcp_subnet_name" --format="csv(selfLink)" | grep -Po "/compute/v1/\K(.*)")

# show the full path to the subnet, use for --subnet flag
echo "full subnet path: $gcp_subnet_full"

REFERENCES

google, compute instances create using –subnet flag

google, gcloud install