Search code examples
python-3.xgcloudgoogle-cloud-iam

How can I call add-iam-policy-binding with Python?


I am struggling to follow the docs (https://googleapis.dev/python/iam/latest/index.html) for the GCP Python IAM Client.

How can I invoke gcloud iam service-accounts add-iam-policy-binding with this library (i.e. without shell'ing out)?


Solution

  • APIs Explorer is very useful for this type of problem because, not only does it allow you to lookup any Google service method to determine the request and response types but, it often includes sample code.

    In this case gcloud's add-iam-policy-binding maps to 2 underlying calls. GET'ting the policy, revising it and then POST'ing it back using the same eTag.

    Your code should change the Policy in the response from getIamPolicy to create the Policy in the request for setIamPolicy.

    The eTag is a hash of the existing policy and it's used in the POST to confirm to the platform, that the value you're POSTting is intended to replace what you received. If the value is changed before your POST, then the service will reject your POST.

    Here's setIamPolicy:

    https://cloud.google.com/iam/docs/reference/rest/v1/projects.serviceAccounts/setIamPolicy

    And the examples (click Python):

    https://cloud.google.com/iam/docs/reference/rest/v1/projects.serviceAccounts/setIamPolicy#examples

    Another trick is to use append --log-http to the gcloud command to see what underlying REST calls are made.