Search code examples
google-cloud-platformgcloudgoogle-groups

How to get all groups from google cloud identity using gcloud command


I am using the gcloud beta command to search the groups in GCP.

The problem is I have 1700 groups, and after x number of groups command generates nextpagetoken and I have to enter it manually to rerun the command. Is there any way I can automate it? i.e, store the next page token in a variable and pass it to the following command.

gcloud beta identity groups search --organization="5487965215"  --labels="cloudidentity.googleapis.com/groups.discussion_forum" --page-size=3

Solution

  • Implementation can be done in different ways, one of them using a while loop that retrieves nextPageToken from response.

    You can run this script on the Cloud Shell and change the Org ID. Group names will be saved on group.txt file

    # setup
    ORGANIZATION_ID="..." 
    
    # get groups list
    echo -n > groups.txt
    GCLOUD_ARG_PAGE_TOKEN=""
    RUN=1
    while [ $RUN == 1 ] ; do
      gcloud beta identity groups search \
        --organization="${ORGANIZATION_ID}" \
        --labels="cloudidentity.googleapis.com/groups.discussion_forum" \
        --format=json \
        --page-size=1000 \
        ${GCLOUD_ARG_PAGE_TOKEN} \
      > response.json   <response.json jq -r ".[0].groups[].groupKey.id" >> groups.txt   NEXT_PAGE_TOKEN="$(<response.json jq -r '.[0].nextPageToken')"
      if [ "$NEXT_PAGE_TOKEN" == "null" ] ; then
        GCLOUD_ARG_PAGE_TOKEN=""
        RUN=0
      else
        GCLOUD_ARG_PAGE_TOKEN="--page-token=$NEXT_PAGE_TOKEN"
      fi
    done