首页 > 解决方案 > 如何列出与我的 Azure 资源关联的策略?

问题描述

对于我的 Azure 帐户中的每个资源,我想列出一些关于它的基本信息,然后找到与之关联的策略。使用 Azure 的 Java SDK,这是我目前所拥有的:

AzureResourceManager azureResourceManager = AzureResourceManager
        .authenticate(credential, profile)
        .withSubscription("<my-subscription-id>");

for(GenericResource resource : azureResourceManager.genericResources().list())
{
    System.out.println("Resource Name: " + resource.name());
    System.out.println("Resource ID: " + resource.id()); 
    PagedIterable<PolicyAssignment> policiesAssignmentsForThisResource = azureResourceManager.policyAssignments().listByResource(resource.id());
    for(PolicyAssignment policyAssignment : policiesAssignmentsForThisResource)
    {
        System.out.println("Policy Assignment Display Name: " + policyAssignment.displayName());
    }
}

这将列出资源名称和 ID,但是当尝试遍历策略分配时,它会引发以下错误:

IllegalArgumentException: Parameter parentResourcePath is required and cannot be null.

有没有办法解决这个错误?有没有更好的方法来查找资源的策略?

listByResource()是我正在使用的方法:

https://docs.microsoft.com/en-us/java/api/com.azure.resourcemanager.resources.models.policyassignments.listbyresource?view=azure-java-stable

标签: javaazureazure-resource-managerazure-policy

解决方案


如果您想检查与一个资源关联的那些策略的状态,请参考以下代码。

注意:这是版本 1 API,而不是当前版本 2 API,并且此代码仍处于测试阶段。

开发工具包

  <dependency>
      <groupId>com.microsoft.azure.policyinsights.v2019_10_01</groupId>
      <artifactId>azure-mgmt-policyinsights</artifactId>
      <version>1.0.0-beta-2</version>
    </dependency>

代码


        ApplicationTokenCredentials credentials = new ApplicationTokenCredentials(clientId,
                tenant,
                clientSecret,
                AzureEnvironment.AZURE);


       RestClient restClient=  new RestClient.Builder()
                .withBaseUrl(credentials.environment(), AzureEnvironment.Endpoint.RESOURCE_MANAGER)
                .withCredentials(credentials)
               .withSerializerAdapter( new AzureJacksonAdapter())
                .withResponseBuilderFactory(new AzureResponseBuilder.Factory())
                .build();

        PolicyInsightsClientImpl policyInsightsClient = new PolicyInsightsClientImpl(restClient);
        PagedList<PolicyStateInner> policys = policyInsightsClient.policyStates().listQueryResultsForResource(
                PolicyStatesResource.DEFAULT,
                "/subscriptions/e5b0fcfa-e859-43f3-8d84-5e5fe29f4c68/resourceGroups/andywin7"
        );
        for(PolicyStateInner policy : policys){
              System.out.println(policy.complianceState());

        }

推荐阅读