Dimitri Bret
Dimitri Bret

Reputation: 33

How to set IAM policy for a project using Google Cloud Resource Manager package

Problem

I'm using the google-cloud-resource-manager to create projects. I would like to update the IAM policy of the project to ad a new user to the owner roole.

Here's how I do:

async def set_iam_policy(project_id, user_id):
    client = ProjectsAsyncClient()
    project_ressource = 'projects/{}'.format(project_id)
    iam_policy : Policy = await client.get_iam_policy(resource=project_ressource)
    owner : Binding = iam_policy.bindings[0]
    owner.members.append('user:{}'.format(user_id))
    updated_policy =await client.set_iam_policy(resource=project_ressource)

Explanations

  1. I get thee project iam policy
  2. I edit the policy given to add the specified user as an owner
  3. I try to update the IAM poolicy for the given project, it breaks here

The set_iam_policy takes as argument a ressource string (exemple projects/myprojectid but I can't pass the policy to this object, there is not fields for that. Am I missing something?

Documentation

You can find the documentation and the source code associated with the set_iam_policy function.

Upvotes: 3

Views: 1308

Answers (1)

DazWilkin
DazWilkin

Reputation: 40081

I think you want something like:

request = SetIamPolicyRequest(
    resource=project_ressource,
    policy=iam_policy,
)

updated_policy = await client.set_iam_policy(
   resource=project_ressource,
   request=request,
)

NOTE retained typo in project_ressource

NOTE You should not assume that bindings[0] corresponds to roles/owners.

Upvotes: 2

Related Questions