I am trying to add service accounts to a certain role in a project in GCP. In order to do so, I get the IAM policy and then add the accounts desired, but am unable to get set_iam_policy to work correctly. I add the projects_to_add to the member list for the role I want to add service accounts to, but the GCP Docs are confusing and I'm not able to add the roles_dict I updated to set_iam_policy. Does anyone know how I should do this?
client = resourcemanager_v3.ProjectsClient(credentials=credentials)
req = iam_policy_pb2.GetIamPolicyRequest(
resource="projects/mse-sandbox-registry-anushka"
)
response = client.get_iam_policy(request=req)
roles_dict = MessageToDict(response)
projects_to_add = []
projects_to_remove = []
for proj in proj_numbers:
account = (
"serviceAccount:service-"
+ proj
+ "@serverless-robot-prod.iam.gserviceaccount.com"
)
if proj not in storage_obj_viewer_list:
projects_to_add.append(account)
for dict in roles_dict["bindings"]:
if (
dict["role"] == "roles/storage.objectViewer"
): # add the projects into the dictionary
members_list = dict["members"]
members_list.append(projects_to_add)
dict["members"] = members_list
req = iam_policy_pb2.SetIamPolicyRequest(
resource="mse-sandbox-registry-anushka", Policy=roles_dict
)
response = client.set_iam_policy(
request=req,
)```
I tried various forms, including passing in resource="projects/<my-project-name>", policy=roles_dict, but nothing seems to work.