azure使用java sdk向vm分配角色

ruoxqz4g  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(471)

我正在编写一个java程序,它创建一个vm并从一个存储器访问文件。但是,我很难将该vm分配为“storagecontributor/owner”角色,以便它可以。
我目前有这个代码,但我不确定它是否是我需要的,而且我也不知道在某些地方写什么:

rbacManager = GraphRbacManager.authenticate( credentials );
rbacManager.roleAssignments()
           .define("roletest")
           // which object? and where to find the ID? 
           .forObjectId("/subscription/" + subscription + "?")
           .withBuiltInRole(com.microsoft.azure.management.graphrbac.BuiltInRole.STORAGE_ACCOUNT_CONTRIBUTOR)
           // what should go as resource scope?
           .withResourceScope(?)
           .createAsync();

本质上,我想在java代码中执行以下步骤:

提前谢谢!

w6lpcovy

w6lpcovy1#

关于这个问题,请参考以下步骤
创建服务主体并分配 Owner sp的角色

az login
az ad sp create-for-rbac -n "MyApp" --role "Owner"\
    --scopes /subscriptions/{SubID} \
    --sdk-auth

项目
答。软件开发包

<dependency>
      <groupId>com.azure.resourcemanager</groupId>
      <artifactId>azure-resourcemanager</artifactId>
      <version>2.0.0</version>
    </dependency>
    <dependency>
      <groupId>com.azure</groupId>
      <artifactId>azure-identity</artifactId>
      <version>1.2.0</version>
    </dependency>

b。代码

AzureProfile profile = new AzureProfile(AzureEnvironment.AZURE);
        String clientId="<sp appid>";
        String clientSecret="<sp password>";
        String tenant="";
        String subscriptionId=""
        TokenCredential credential = new ClientSecretCredentialBuilder()
                .clientId(clientId)
                .clientSecret(clientSecret)
                .authorityHost(profile.getEnvironment().getActiveDirectoryEndpoint())
                .tenantId(tenant)
                .build();
        AzureResourceManager azureResourceManager = AzureResourceManager
                .configure()
                .withLogLevel(HttpLogDetailLevel.BASIC)
                .authenticate(credential, profile)
                .withSubscription(subscriptionId);
        // get storage account
        String accountGroup="";
        String accountName="";
        StorageAccount account = azureResourceManager.storageAccounts().getByResourceGroup(accountGroup,accountName);
        // get vm
        String vmGroup="";
        String vmName="test";
        VirtualMachine virtualMachine = azureResourceManager.virtualMachines().getByResourceGroup(vmGroup,vmName);
        virtualMachine.update()
                .withSystemAssignedManagedServiceIdentity()
                .withSystemAssignedIdentityBasedAccessTo(account.id(), BuiltInRole.fromString("Storage Blob Data Owner"))
                .apply();

    }

相关问题