javagoogle-cloud-platformvirtual-machinegoogle-cloud-compute-engine

How to programmatically set external ip for Google Cloud virtual machine in Java?


I am trying to programmatically start Google Cloud virtual machine instances. It occurred to me that in order to have internet access, have to set an external IP address.

        // Access Config
        AccessConfig accessConfig = AccessConfig.newBuilder()
                    .setNatIP("foo")
                    .setType("ONE_TO_ONE_NAT")
                    .setName("External NAT")
                    .setExternalIpv6("bar")
                    .build();
        
        // Use the network interface provided in the networkName argument.
        NetworkInterface networkInterface = NetworkInterface.newBuilder()
                .setName(networkName)
                .setAccessConfigs(0, accessConfig)
                .build();

That is my status quo. It is inspired by this article post. I hoped that would work in Java, too, but currently, I am stuck.

All I get is:

com.google.api.gax.rpc.InvalidArgumentException: Bad Request

Unfortunately, Google Cloud Compute Engine Docs doesn't really provide any further information, on how to set the external IP properly.

Thanks in advance.


Solution

  • I have encountered the answer. In the Google Cloud Compute Engine Docs it is explained for Windows Instances. It took me a while to recognize it because I've focused only Linux Instances' related questions.

    The solution:

    instanceResource = Instance.newBuilder()
                    .setName(instanceName)
                    .setMachineType(machineType)
                    .addDisks(disk)
                    // Add external internet to instance
                    .addNetworkInterfaces(NetworkInterface.newBuilder()
                            .addAccessConfigs(AccessConfig.newBuilder()
                                    .setType("ONE_TO_ONE_NAT")
                                    .setName("External NAT")
                                    .build())
                            .setName("global/networks/default")
                            .build())
                    .setMetadata(buildMetadata())
                    .build();