Professional Documents
Culture Documents
pydevops / gcloud-cheat-sheet.md
Last active 1 hour ago
Code
Revisions
174
Stars
662
Forks
300 Embed
<script src="https://gis Download ZIP
gcloud-cheat-sheet.md
0.1. References
0.2. Other cheatsheets
0.3. Manage multiple gcloud config configurations
0.3.1. Switch gcloud context with gcloud config
0.4. Credentials
0.5. info
0.6. projects
0.7. zones & regions
0.8. Organization
0.9. billing
0.10. IAM
0.11. service account
0.11.1. as an identity
0.11.2. service account as a resource
0.11.3. GCS bucket level
0.12. App engine
0.13. Cloud Build
0.13.1. Cloud build trigger GCE rolling replace/start
0.14. KMS
0.15. Secret Manager
0.16. Compute Engine
0.16.1. gcloud command for creating an instance
0.16.2. list compute images
0.16.3. list an instance
0.16.4. move instance
0.16.5. ssh & scp
0.16.6. SSH via IAP
0.16.7. ssh port forwarding for elasticsearch
0.16.8. ssh reverse port forwarding
0.16.9. generate ssh config
0.16.10. Windows RDP reset windows password
0.16.11. debugging
0.16.12. instance level metadata
0.16.13. project level metadata
0.16.14. instances, template, target-pool and instance group
0.16.15. MIG with startup and shutdown scripts
0.16.16. disk snapshot
0.16.17. regional disk
0.17. Networking
0.17.1. network and subnets
0.17.2. route
0.17.3. firewall rules
0.17.4. Network LB
0.17.5. Global LB
0.17.6. forwarding-rules
0.17.7. address
0.17.8. private service access
0.18. interconnect
0.19. GCP managed ssl certificates
0.20. Cloud logging
0.21. Service
0.21.1. list service available
0.21.2. Enable Service
0.22. Client libraries you can use to connect to Google APIs
0.23. chaining gcloud commands
0.24. one liner to purge GCR images given a date
0.25. GKE
0.25.1. create a GKE cluster with label and query it later
0.26. Cloud SQL
0.27. Cloud Run
0.28 Artifact registry
0.29. Machine Learning
0.1. References
have fun with them
projections
filters
resource-keys
scripting-gcloud
gcloud alpha interactive
https://medium.com/@Joachim8675309/getting-started-with-gcloud-sdk-part-1-114924737
https://medium.com/@Joachim8675309/getting-started-with-gcloud-sdk-part-2-4d049a656f1a
https://gist.github.com/bborysenko/97749fe0514b819a5a87611e6aea3db8
https://about.gitlab.com/blog/2020/02/12/plundering-gcp-escalating-privileges-in-google-cloud-platform/
https://www.jhanley.com/google-cloud-understanding-gcloud-configurations/
https://medium.com/infrastructure-adventures/working-with-multiple-environment-in-gcloud-cli-93b2d4e8cf1e
alias demo='gcloud config set account pythonrocks@gmail.com && gcloud config set project mygcp-demo && gcloud config set
echo >&2 "I require gcloud but it's not installed. Aborting."; exit 1; }
echo "replace 'REGION' with the region name like us-west1." 1>&2
exit 1;
fi
0.4. Credentials
https://stackoverflow.com/questions/53306131/difference-between-gcloud-auth-application-default-login-and-gcloud-
auth-logi/53307505
https://medium.com/google-cloud/local-remote-authentication-with-google-cloud-platform-afe3aa017b95
# to authenticate with a user identity (via web flow) which then authorizes gcloud and other SDK tools to access Google C
gcloud auth login
# Service Account: to authenticate with a user identity (via a web flow) but using the credentials as a proxy for a serv
gcloud auth activate-service-account --key-file=sa_key.json
export GCP_REGION="us-east1"
0.5. info
gcloud info --format flattened
0.6. projects
# get project_number
# list regions
0.8. Organization
ORGANIZATION_ADMIN_ADDRESS='user:developer1@example.com'
--member=${ORGANIZATION_ADMIN_ADDRESS} \
--role=roles/resourcemanager.folderAdmin
--member=${ORGANIZATION_ADMIN_ADDRESS} \
--role=roles/storage.admin
--member=${ORGANIZATION_ADMIN_ADDRESS} \
--role=roles/billing.projectManager
0.9. billing
# enable a billing account with a project, assuming the user or service account has "Billing Account User" role.
--billing-account ${ORGANIZATION_BILLING_ACCOUNT}
0.10. IAM
https://github.com/darkbitio/gcp-iam-role-permissions
# list roles
e.g.
# create custom role in the following 2 ways, either on project level (--project [PROJECT_ID]) or org level (--
organization [ORGANIZATION_ID])
2. gcloud iam roles create viewer --project $PROJECT_ID --title "Role Viewer" --description "Custom role
description." --permissions compute.instances.get,compu
0.11.1. as an identity
--filter="displayName:jenkins" --format='value(email)')
--iam-account=connect-sa@${PROJECT_ID}.iam.gserviceaccount.com
# get-iam-policy
--flatten="bindings[].members" \
--member serviceAccount:$SA_EMAIL
--member serviceAccount:$SA_EMAIL
--member serviceAccount:$SA_EMAIL
--member serviceAccount:$SA_EMAIL
--member serviceAccount:$SA_EMAIL
--member="serviceAccount:connect-sa@${PROJECT}.iam.gserviceaccount.com" \
--role="roles/gkehub.connect"
bindings:
- members:
- serviceAccount:<project-id>.svc.id.goog[default/secret-accessor-dev]
role: roles/iam.workloadIdentityUser
etag: BwWhFqqv9aQ=
version: 1
We can impersonate service account from a user or another service account, a short-lived token is used instead of service account
key.
TF_SA_EMAIL=terraform@${SA_PROJECT_ID}.iam.gserviceaccount.com
ANSIBLE_SA_EMAIL="ansible@${SA_PROJECT_ID}.iam.gserviceaccount.com"
--project ${SA_PROJECT_ID} \
--member "serviceAccount:$ANSIBLE_SA_EMAIL" \
--role roles/iam.serviceAccountTokenCreator
TF_SA_EMAIL=terraform@your-service-account-project.iam.gserviceaccount.com
--role roles/iam.serviceAccountTokenCreator
COMPUTE_ENGINE_SA_EMAIL=$(gcloud iam service-accounts list --filter="name:Compute Engine default service account" --form
gsutil iam ch serviceAccount:${COMPUTE_ENGINE_SA_EMAIL}:objectViewer gs://${BUCKET_NAME}
0.12. App engine
https://medium.com/google-cloud/app-engine-project-cleanup-9647296e796a
# user defined
export GCP_REGION="us-east1"
export TEST_IMAGE="us-docker.pkg.dev/google-samples/containers/gke/hello-app:1.0"
export IMAGE_NAME="hello-app"
export REPO_NAME=team1
export TAG_NAME="tag1"
${GCP_REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO_NAME}/${IMAGE_NAME}:${TAG_NAME}
steps:
- name: 'gcr.io/cloud-builders/docker'
- name: 'gcr.io/cloud-builders/gcloud'
- 'gcr.io/$PROJECT_ID/gcp-cloudbuild-gce-angular'
0.14. KMS
cloud-encrypt-with-kms
Integrated with cloud build
--location global \
--member user:$USER_EMAIL \
--role roles/cloudkms.admin
--location global \
--member user:$USER_EMAIL \
--role roles/cloudkms.cryptoKeyEncrypterDecrypter
curl -v "https://cloudkms.googleapis.com/v1/projects/$DEVSHELL_PROJECT_ID/locations/global/keyRings/$KEYRING_NAME/crypto
-d "{\"plaintext\":\"$PLAINTEXT\"}" \
-H "Content-Type:application/json" \
curl -v "https://cloudkms.googleapis.com/v1/projects/$DEVSHELL_PROJECT_ID/locations/global/keyRings/$KEYRING_NAME/crypto
-d "{\"ciphertext\":\"$(cat 1.encrypted)\"}" \
-H "Content-Type:application/json" \
| jq .plaintext -r | base64 -d
# create a secret
# list
# read
--image-family [IMAGE_FAMILY] \
--image-project [IMAGE_PROJECT] \
--create-disk image=[DISK_IMAGE],image-project=[DISK_IMAGE_PROJECT],size=[SIZE_GB],type=[DISK_TYPE]
https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-8-jessie-v20180109
https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/debian-9-stretch-v20180105
# Use the following command to see available non-Shielded VM Windows Server images
# Use the following command to see a list of available Shielded VM images, including Windows images
# the following is a real word example for running a bastion server that talks to a GKE cluster (master authorized netwo
gcloud compute ssh --verbosity=debug <instance_name> --command "kubectl get nodes"
# connect via IAP, assuming the IAP is granted to the account used for login.
gcloud compute --project "foo" ssh --zone "us-central1-c" "elasticsearch-1" --ssh-flag="-L localhost:9200:localhost:9200
gcloud compute --project "${GOOGLE_CLOUD_PROJECT}" ssh --zone "us-west1-c" --ssh-flag="-v -N -R :5000:localhost:5000" "go
ip_address: 104.199.119.166
password: Ks(;_gx7Bf2d.NP
username: jode
0.16.11. debugging
gcloud compute instances list --log-http
#! /bin/bash
apt-get update
EOF
--base-instance-name nginx \
--size 2 \
--template nginx-template \
--target-pool nginx-pool
gsutil cp gs://nat-gw-template/startup.sh .
gcloud compute disks snapshot kafka-data1-1 --async --snapshot-names=kafka-data-1 --project project_a --zone us-west1-a
Use [gcloud compute operations describe URI] command to check the status of the operation(s).
gcloud beta compute instance attach-disk micro1 --disk pd-west1 --disk-scope regional
0.17. Networking
0.17.2. route
tag the instances with no-ip
--network custom-network1 \
--destination-range 0.0.0.0/0 \
--next-hop-instance nat-gateway \
--next-hop-instance-zone us-central1-a \
--tags no-ip --priority 800
--source-ranges 10.128.0.0/9
## DENY
# sort-by
0.17.4. Network LB
--region us-central1 \
--ports=80 \
--target-pool nginx-pool
0.17.5. Global LB
https://cloud.google.com/solutions/scalable-and-resilient-apps
set-named-ports nginx-group \
--named-ports http:80
--instance-group nginx-group \
--instance-group-zone us-central1-a \
--global
--default-service nginx-backend
--url-map web-map
--global \
--target-http-proxy http-lb-proxy \
--ports 80
0.17.6. forwarding-rules
0.17.7. address
--format='value(networkInterfaces.accessConfigs[0].natIP)
gcloud projects list --format='value(project_id)' | xargs -I {} gcloud compute addresses list --format='value(address)'
0.18. interconnect
# It takes 30mins+ to provision the TLS, one of conditions is the target-https-proxies needs to be associated with the c
gcloud beta compute target-https-proxies list
0.20. Cloud logging
0.21. Service
# chain
cloudresourcemanager.googleapis.com && \
compute.googleapis.com
# or not chain
function enable-service() {
SERVICE=$1
--filter="config.name:$SERVICE" 2>&1) != \
else
fi
enable-service container.googleapis.com
| xargs -I {} gcloud compute addresses list --format='value(address)' --project {} 2>/dev/null | sort | uniq -c
DATE=2018-10-01
IMAGE=<project_id>/<image_name>
while read digest;do gcloud container images delete -q --force-delete-tags gcr.io/$IMAGE@$digest ;done
0.25. GKE
--private-cluster \
--master-ipv4-cidr 172.16.0.16/28 \
--enable-ip-alias \
--create-subnetwork ""
--network default \
--range 10.0.4.0/22 \
--enable-private-ip-google-access \
--region us-central1 \
--secondary-range my-svc-range=10.0.32.0/20,my-pod-range=10.4.0.0/14
--private-cluster \
--enable-ip-alias \
--master-ipv4-cidr 172.16.0.32/28 \
--subnetwork my-subnet \
--services-secondary-range-name my-svc-range \
--cluster-secondary-range-name my-pod-range
--enable-master-authorized-networks \
--master-authorized-networks <external_ip_of_kubectl_instance>
--addons HorizontalPodAutoscaling,HttpLoadBalancing,Istio,CloudRun \
--scopes cloud-platform \
--zone us-central1-a \
--machine-type n1-standard-4 \
--enable-stackdriver-kubernetes \
--no-enable-ip-alias
export WORKLOAD_POOL=${PROJECT_ID}.svc.id.goog
export MESH_ID="proj-${PROJECT_NUMBER}"
--machine-type=n1-standard-4 \
--num-nodes=4 \
--workload-pool=${WORKLOAD_POOL} \
--enable-stackdriver-kubernetes \
--subnetwork=default \
--labels mesh_id=${MESH_ID}
--tier=db-n1-standard-1 --activation-policy=ALWAYS
--password Passw0rd
# authorizes the IP
flights --format="value(ipAddresses.ipAddress)")
gcloud run deploy --image gcr.io/${PROJECT-ID}/helloworld --platform managed --region us-central1 --allow-unauthenticate
# list services
export SA_NAME="cloud-scheduler-runner"
export SA_EMAIL="${SA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com"
--display-name "${SA_NAME}"
--platform managed \
--region $GCP_REGION \
--member=serviceAccount:$SA_EMAIL \
--role=roles/run.invoker
export APP="helloworld"
export SVC_URL=$(gcloud run services describe $APP --platform managed --region $GCP_REGION --format="value(status.url)")
--http-method=GET \
--uri=$SVC_URL \
--oidc-service-account-email=$SA_EMAIL \
--oidc-token-audience=$SVC_URL
export GCP_REGION="us-east1"
export SERVICE_NAME="hello-service"
--platform managed \
--region $GCP_REGION \
--allow-unauthenticated \
--image ${GCP_REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO_NAME}/${IMAGE_NAME}:${TAG_NAME}
--platform managed \
--region $GCP_REGION
# test URL
export SVC_URL=$(gcloud run services describe $SERVICE_NAME --platform managed --region $GCP_REGION --format="value(stat
# Hello, world!
# Version: 1.0.0
# Hostname: localhost
export REPO_NAME=team1
export GCP_REGION="us-east1"
--repository-format=docker \
--location=$GCP_REGION \
--description="Docker repository"
# configure auth
gcloud ml language analyze-entities --content="Michelangelo Caravaggio, Italian painter, is known for 'The Calling of Sa
onlinematters
commented
on Apr 8, 2019
EvertonSA
commented
on Sep 4, 2019
utkarshsharma-tudip
commented
on Oct 12, 2019
@onlinematters Here.
WebLeash
commented
on Nov 30, 2019
Nice
csales1987
commented
on Dec 2, 2019
Amazing!
hrishikeshtele
commented
on Jan 2, 2020
goplogic
commented
on Jan 23, 2020
Thanks for the information. I appreciate your effort.
If you have any information regarding Istio, ingress, egress, could you please post here. Thanks
andrewlmarks9
commented
on Jan 30, 2020
This information is helpful, Can someone guide me on how to label a project in gcloud?
pydevops
commented
on Jan 30, 2020 Owner Author
This information is helpful, Can someone guide me on how to label a project in gcloud?
pabloem
commented
on Mar 18, 2020
sethideepak
commented
on Apr 5, 2020
zukko78
commented
on Apr 29, 2020
Excellent list, I have a little bit less as I'm preparing for the GCP exam now. Thank you!
paulstakem
commented
on May 20, 2020
andrewliebowitz1
commented
on Jul 6, 2020
https://gist.github.com/pydevops/cffbd3c694d599c6ca18342d3625af97#0172-route
jayeshlk
commented
on Jul 31, 2020
bpmct
commented
on Apr 1
bpmct
commented
on Apr 1
--filter="serviceConfig.name:$SERVICE" 2>&1) != \
should be
--filter="config.name:$SERVICE" 2>&1) != \
reynoldpj
commented
on May 28
pydevops
commented
19 days ago Owner Author
--filter="serviceConfig.name:$SERVICE" 2>&1) != \
should be
if [[ $(gcloud services list --format="value(config.name)" \
--filter="config.name:$SERVICE" 2>&1) != \
thanks.