【Azure Developer】使用 Java SDK 调用的VM runCommand 接口示例代码 - LuBu0505/My-Code GitHub Wiki
在2021年4月的一篇博文( 【Azure Developer】调用SDK的runPowerShellScript方法,在Azure VM中执行PowerShell脚本示例 )中,介绍了使用 com.microsoft.azure SDK 来实现了Java 代码调用Run Command接口的代码。但是,在现在的VM Runcomand API接口中,使用的JDK 变为 com.azure.resourcemanager.AzureResourceManager, 所以本文将介绍新的Java SDK 代码来实现RunCommand接口的调用。
package org.example;
import com.azure.core.management.profile.AzureProfile;
import com.azure.core.models.AzureCloud;
import com.azure.identity.AzureAuthorityHosts;
import com.azure.identity.ClientSecretCredential;
import com.azure.identity.ClientSecretCredentialBuilder;
import com.azure.resourcemanager.AzureResourceManager;
import com.azure.resourcemanager.compute.models.RunCommandInput;
public class App {
public static void main(String[] args) {
AzureProfile profile = new AzureProfile(AzureCloud.AZURE_CHINA_CLOUD);
ClientSecretCredential credential;
credential = new ClientSecretCredentialBuilder()
.clientId("<service principle client id>")
.clientSecret("<secret value>")
.tenantId("<tenant id>")
.authorityHost(AzureAuthorityHosts.AZURE_CHINA)
.build();
AzureResourceManager azure = AzureResourceManager
.authenticate(credential, profile)
.withDefaultSubscription();
try {
azure.virtualMachines().manager().serviceClient().getVirtualMachines().runCommand("the resource group name", "vm name",
new RunCommandInput().withCommandId("RunPowerShellScript"), com.azure.core.util.Context.NONE);
} catch (Exception e) {
e.printStackTrace();
}
}
}
pom.xml
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-identity</artifactId>
<version>1.16.1</version>
</dependency>
<dependency>
<groupId>com.azure.resourcemanager</groupId>
<artifactId>azure-resourcemanager</artifactId>
<version>2.51.0</version>
</dependency>
<dependency>
<groupId>com.azure.resourcemanager</groupId>
<artifactId>azure-resourcemanager-compute</artifactId>
<version>2.51.0</version>
</dependency>
注意事项:
1)在 ClientSecretCredentialBuilder 中,指定了中国区Azure 的authorityHost (AzureAuthorityHosts.AZURE_CHINA)
2)在 AzureResourceManager 中,也需要指定中国区Azure环境 AzureProfile profile = new AzureProfile(AzureCloud.AZURE_CHINA_CLOUD)
【Azure Developer】调用SDK的runPowerShellScript方法,在Azure VM中执行PowerShell脚本示例 : https://www.cnblogs.com/lulight/p/14688943.html
Virtual Machines - Run Command : https://learn.microsoft.com/en-us/rest/api/compute/virtual-machines/run-command?view=rest-compute-2025-02-01&tabs=Java
Azure Identity client library for Java : https://github.com/Azure/azure-sdk-for-java/tree/main/sdk/identity/azure-identity
当在复杂的环境中面临问题,格物之道需:浊而静之徐清,安以动之徐生。 云中,恰是如此!