简体   繁体   English

无法在 gcp 中为服务帐号分配角色

[英]Unable to assign role to service account in gcp

I'm able to create a service account but facing issues while assigning a role to the service account.我能够创建服务帐户,但在为服务帐户分配角色时遇到问题。 Here is the approach I'm using这是我正在使用的方法

CloudResourceManager cloudResourceManagerService = createCloudResourceManagerService(clientId,
                clientSecret);

        GetIamPolicy getrequest = cloudResourceManagerService.projects().getIamPolicy(projectId,
                new GetIamPolicyRequest());

        Policy response = getrequest.execute();

//Modification to policy        

        List<String> members = response.getBindings().get(0).getMembers();
        members.add("serviceAccount:name@my-project.iam.gserviceaccount.com");
        response.getBindings().get(0).setMembers(members);

// =================Set policy======================== // ================设置策略========================

         String resource = "projects/" + projectId + "/serviceAccounts/" +
                 "name@my-project.iam.gserviceaccount.com";

        SetIamPolicyRequest requestBody = new SetIamPolicyRequest().setPolicy(response);
        SetIamPolicy setrequest = cloudResourceManagerService.projects().setIamPolicy(resource, requestBody);
        Policy newResponse = setrequest.execute();

This code is not giving any error but also not setting a role for the provided service account.此代码没有给出任何错误,也没有为提供的服务帐户设置角色。

Because you are calling projects.serviceAccounts.setIamPolicy , and because you specifically are passing the serviceAccount, you are only granting the service account editor role on itself .因为您正在调用projects.serviceAccounts.setIamPolicy ,并且因为您专门传递了 serviceAccount,所以您只授予了服务帐户编辑器角色本身

If you want the service account to be an editor on the project you must call projects.setIamPolicy and the resource you want to specify should be the project itself.如果您希望服务帐户成为项目的编辑者,您必须调用projects.setIamPolicy,并且您要指定的资源应该是项目本身。

As John Hanley says, you will also need to do this as a read-modify-write cycle as described here .正如 John Hanley 所说,您还需要按照此处所述的读-修改-写循环来执行此操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM