Skip to content

Instantly share code, notes, and snippets.

@bluPhy
Last active April 1, 2023 17:06
Show Gist options
  • Select an option

  • Save bluPhy/94388b80ab061c70013f59de2f98c014 to your computer and use it in GitHub Desktop.

Select an option

Save bluPhy/94388b80ab061c70013f59de2f98c014 to your computer and use it in GitHub Desktop.
Script to retrieve GCP IAM roles, users and serviceaccounts and export it to yaml files
#!/bin/bash
# Script to retrieve GCP IAM roles, users and serviceaccounts
# and export it to yaml files that can be used to import back
# with gcloud projects set-iam-policy <project> <policy.yaml>
#
# You can manually remove the etag and version lines in the resulting yaml file
# but do so at your own risk.
#
# Author - Alejandro Leal [email protected]
prjs=($(gcloud projects list --filter='lifecycleState: ACTIVE' --format='value(projectId)'))
for i in "${prjs[@]}"; do
YAML_EXPORT_FILE="$i"_policies.yaml
echo "------------------------------------------------------------------"
echo "Collecting IAM roles & users for Project: $i"
echo "#" >"$YAML_EXPORT_FILE"
tee -a "$YAML_EXPORT_FILE" <<EOT >/dev/null
# Project $i IAM export, result of
# running: gcloud projects get-iam-policy $i"
#
# Critical note: Resulting file will not work if the IAM policy
# has changed, read the note on https://cloud.google.com/iam/docs/reference/rest/v1/Policy
# etag is used for optimistic concurrency control as a way to help prevent
# simultaneous updates of a policy from overwriting each other. It is strongly
# suggested that systems make use of the etag in the read-modify-write cycle
# to perform policy updates in order to avoid race conditions: An etag is
# returned in the response to getIamPolicy, and systems are expected to put
# that etag in the request to setIamPolicy to ensure that their change will
# be applied to the same version of the policy.
# Important: If you use IAM Conditions, you must include the etag field whenever
# you call setIamPolicy. If you omit this field, then IAM allows you to overwrite
# a version 3 policy with a version 1 policy, and all of the conditions in the
# version 3 policy are lost.
#
# You can manually remove the etag and version lines in the resulting yaml file
# but do so at your own risk.
#
EOT
# Only run if the project exists. If it has been deleted, gcloud will fail.
gcloud projects get-iam-policy "$i" >>"$YAML_EXPORT_FILE" || continue
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment