Java 如何列出与Azure资源关联的策略?

Java 如何列出与Azure资源关联的策略?,java,azure,azure-resource-manager,azure-policy,Java,Azure,Azure Resource Manager,Azure Policy,对于我Azure帐户中的每个资源,我想列出一些关于它的基本信息,然后查找与之相关的策略。使用Azure的Java SDK,到目前为止,我拥有以下内容: AzureResourceManager azureResourceManager = AzureResourceManager .authenticate(credential, profile) .withSubscription("<my-subscription-id>");

对于我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());
    }
}
有没有办法解决这个错误?是否有更好的方法找到资源的策略

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


如果要检查与一个资源关联的策略的状态,请参阅以下代码

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

Sdk


com.microsoft.azure.policyinsights.v2019_10_01
azure管理策略洞察
1.0.0-beta-2
代码


ApplicationTokenCredentials credentials=新的ApplicationTokenCredentials(clientId,
房客
客户机密,
AzureEnvironment.AZURE);
RestClient RestClient=new RestClient.Builder()
.withBaseUrl(credentials.environment(),AzureEnvironment.Endpoint.RESOURCE\u管理器)
.具有凭证(凭证)
.带有SerializeRadapter(新AzureJacksonAdapter())
.withResponseBuilderFactory(新AzureResponseBuilder.Factory())
.build();
PolicyInsightsClientImpl policyInsightsClient=新的PolicyInsightsClientImpl(restClient);
PagedList policys=policyInsightsClient.PolicyState().listQueryResultsForResource(
PolicyStatesResource.DEFAULT,
“/subscriptions/e5b0fcfa-e859-43f3-8d84-5e5fe29f4c68/resourceGroups/andywin7”
);
for(PolicyState内部策略:策略){
System.out.println(policy.complianceState());
}

由于我不想使用v1 API,它仍处于测试阶段,而且v2 API还没有此功能,所以我选择使用REST API。我过去常搬运重物。这是我的解决方案,其中我使用资源ID获取资源的策略状态:

OkHttpClient policyStateHttpClient = new OkHttpClient();
String policyStateUrl = "https://management.azure.com" 
        + resource.getString("id") // This is the resource ID that I have...
        + "/providers/Microsoft.PolicyInsights/policyStates/latest/queryResults?api-version=2019-10-01";

// It's empty b/c it's a POST without a body.  Yes, it's dumb.
RequestBody policyStateRequestBody = RequestBody.create("", null); 
Request policyStateRequest = new Request.Builder()
        .url(policyStateUrl)
        .addHeader("Authorization", "Bearer " + token)
        .post(policyStateRequestBody)
        .build();

String policyStateJson = "";
try
{
    Response policyStateResponse = policyStateHttpClient.newCall(policyStateRequest).execute();
    policyStateJson = policyStateResponse.body().string();
    if (!policyStateResponse.isSuccessful())
    {
        System.out.println("ERROR: Unable to get the policy states for this resource (" + resource.getString("name") + ").");
        System.out.println(" Reason for error: ");
        System.out.println("  " + policyStateJson);
        return;
    }
}
catch (SocketTimeoutException ste)
{
    System.out.println("ERROR: Unable to get the policy states for this resource (" + resource.getString("name") + ").");
    System.out.println(" The reason is that it timed out.  Azure does this a lot.  If you re-run the app, it will likely fix itself.");
    return;
}
catch (IOException ioe)
{
    ioe.printStackTrace();   // TODO Handle this...
}
JSONObject policyStateRootObject = new JSONObject(policyStateJson);
JSONArray policyStates = policyStateRootObject.getJSONArray("value");
for (int j = 0; j < policyStates.length(); j++) 
{
    JSONObject policyState = policyStates.getJSONObject(j);
    // Do something with the JSON
    System.out.println(policyState.getString("policyDefinitionName"));
    System.out.println(policyState.getString("policyDefinitionId"));
    System.out.println(policyState.getString("complianceState"));
}
OkHttpClient policyStateHttpClient=new OkHttpClient();
字符串policyStateUrl=”https://management.azure.com" 
+resource.getString(“id”)//这是我拥有的资源id。。。
+“/providers/Microsoft.PolicyInsights/PolicyState/latest/queryResults?api版本=2019-10-01”;
//这是空的b/c这是一个没有主体的帖子。是的,这是愚蠢的。
RequestBody policyStateRequestBody=RequestBody.create(“,null);
Request policyStateRequest=new Request.Builder()
.url(policyStateUrl)
.addHeader(“授权”、“持有人”+令牌)
.post(policyStateRequestBody)
.build();
字符串policyStateJson=“”;
尝试
{
Response policyStateResponse=policyStateHttpClient.newCall(policyStateRequest.execute();
policyStateJson=policyStateResponse.body().string();
如果(!policyStateResponse.isSuccessful())
{
System.out.println(“错误:无法获取此资源的策略状态(“+resource.getString”(“name”)+”);
System.out.println(“错误原因:”);
System.out.println(“+policyStateJson”);
返回;
}
}
捕捉(SocketTimeoutException ste)
{
System.out.println(“错误:无法获取此资源的策略状态(“+resource.getString”(“name”)+”);
System.out.println(“原因是它超时了。Azure经常这样做。如果你重新运行应用程序,它可能会自行修复。”);
返回;
}
捕获(ioe异常ioe)
{
ioe.printStackTrace();//要处理此问题。。。
}
JSONObject policyStateRootObject=新的JSONObject(policyStateJson);
JSONArray PolicyState=policyStateRootObject.getJSONArray(“值”);
对于(int j=0;j
谢谢您的回答。我同意这段代码应该可以工作,但当我测试它时,我发现它返回每个资源的每个策略分配,无论它是否适用。控制台和Azure CLI表现出正确的行为,但Java SDK没有。@james.garriss您能详细描述一下您的问题吗?我有。对于通过
genericResources().list()
在我的帐户中找到的每个资源,
listForResource()
方法返回每个启用的策略,无论它们是否分配给该资源。我可以在门户中看到正确的作业。我可以使用
az策略状态列表--resource$id
通过CLI检索正确的分配。但是Java对我来说是坏的。我不知道为什么。@james.garriss comamnd
az policy state list
不用于列出分配,您应该使用
az policy assignment list
来列出分配。不,CLI命令正是我想要的。也许我应该问这样一个问题:什么Java方法与@Jim Xu
az策略状态列表
  <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());

        }
OkHttpClient policyStateHttpClient = new OkHttpClient();
String policyStateUrl = "https://management.azure.com" 
        + resource.getString("id") // This is the resource ID that I have...
        + "/providers/Microsoft.PolicyInsights/policyStates/latest/queryResults?api-version=2019-10-01";

// It's empty b/c it's a POST without a body.  Yes, it's dumb.
RequestBody policyStateRequestBody = RequestBody.create("", null); 
Request policyStateRequest = new Request.Builder()
        .url(policyStateUrl)
        .addHeader("Authorization", "Bearer " + token)
        .post(policyStateRequestBody)
        .build();

String policyStateJson = "";
try
{
    Response policyStateResponse = policyStateHttpClient.newCall(policyStateRequest).execute();
    policyStateJson = policyStateResponse.body().string();
    if (!policyStateResponse.isSuccessful())
    {
        System.out.println("ERROR: Unable to get the policy states for this resource (" + resource.getString("name") + ").");
        System.out.println(" Reason for error: ");
        System.out.println("  " + policyStateJson);
        return;
    }
}
catch (SocketTimeoutException ste)
{
    System.out.println("ERROR: Unable to get the policy states for this resource (" + resource.getString("name") + ").");
    System.out.println(" The reason is that it timed out.  Azure does this a lot.  If you re-run the app, it will likely fix itself.");
    return;
}
catch (IOException ioe)
{
    ioe.printStackTrace();   // TODO Handle this...
}
JSONObject policyStateRootObject = new JSONObject(policyStateJson);
JSONArray policyStates = policyStateRootObject.getJSONArray("value");
for (int j = 0; j < policyStates.length(); j++) 
{
    JSONObject policyState = policyStates.getJSONObject(j);
    // Do something with the JSON
    System.out.println(policyState.getString("policyDefinitionName"));
    System.out.println(policyState.getString("policyDefinitionId"));
    System.out.println(policyState.getString("complianceState"));
}