1

一部の VM インスタンスを管理するためにGcloud-javaを使用しています。新しいインスタンスを作成するコードは明確で、次のとおりです。

Address externalIp = compute.getAddress(addressId);

InstanceId instanceId = InstanceId.of("us-central1-a", "test-instance");

NetworkId networkId = NetworkId.of("default");

PersistentDiskConfiguration attachConfiguration =
        PersistentDiskConfiguration.builder(diskId).boot(true).build();

AttachedDisk attachedDisk = AttachedDisk.of("dev0", attachConfiguration);

NetworkInterface networkInterface = NetworkInterface.builder(networkId)
    .accessConfigurations(AccessConfig.of(externalIp.address()))
    .build();

MachineTypeId machineTypeId = MachineTypeId.of("us-central1-a", "n1-standard-1");

InstanceInfo instance =
    InstanceInfo.of(instanceId, machineTypeId, attachedDisk, networkInterface);

Operation operation = compute.create(instance);
// Wait for operation to complete
operation = operation.waitFor();

if (operation.errors() == null) {
   System.out.println("Instance " + instanceId + " was successfully created");
} else {
     // inspect operation.errors()
     throw new RuntimeException("Instance creation failed");
}

しかし、開始したい既存のインスタンスがあり、外部 IP をアタッチしたい場合はどうすればよいですか?

私はこの方法で試しました: まず、RegionAddressId を作成し、networkInterface を作成するための Address を取得します。

RegionAddressId addressId = RegionAddressId.of("europe-west1", "test-address");
    Operation operationAdd = compute.create(AddressInfo.of(addressId));
    operationAdd = operationAdd.waitFor();

Address externalIp = compute.getAddress(addressId);
NetworkId networkId = NetworkId.of("default");
NetworkInterface networkInterface = NetworkInterface.builder(networkId)
            .accessConfigurations(NetworkInterface.AccessConfig.of(externalIp.address()))
            .build();

インスタンスを取得し、accessConfig を追加します

InstanceId instanceId = InstanceId.of("my-server", "europe-west1-b","my-instance");
    Instance instance = compute.getInstance(instanceId);
    instance.addAccessConfig("default", NetworkInterface.AccessConfig.of(externalIp.address()));
    Operation operation = instance.start();

その結果、取得方法がわからない別の外部 IP でインスタンスが起動されます。正しい手順は何ですか?ありがとう

4

1 に答える 1

1

私は自分で解決策を見つけました。

Compute compute = ComputeOptions.defaultInstance().service();

InstanceId instanceId = InstanceId.of("my-server", "europe-west1-b","my-instance");

Operation operation = compute.start(instanceId);

Operation completedOperation = operation.waitFor();
if (completedOperation == null) {
    // operation no longer exists
} else if (completedOperation.errors() != null) {
    // operation failed, handle error
}

Instance instance = compute.getInstance(instanceId);
String publicIp = 
    instance.networkInterfaces().get(0).accessConfigurations().get(0).natIp();

Compute の start メソッドを使用してインスタンスを開始し、(操作が完了した後) インスタンスを取得します。

于 2016-07-04T15:57:11.470 に答える