sylzys
sylzys

Reputation: 167

Google Compute API: new instance with external IP

I'm trying to dynamically create Compute instances on Google Cloud via PHP using API.

Using csmartinez Cloud API sample, I managed to create my instance and can see it running on Google Console.

I need to assign an external IP address to this newly created instance. Based on the API and Google PHP library, I then added:

$ipName = "foo";
$addr = new Google_Service_Compute_Address();
$addr->setName($ipName);
$response = $service->addresses->insert($project, $ipZone, $addr);

Since this call has a "pending" status at first, I added a sleep(5) so I can then get the newly created static IP:

$response = $service->addresses->get($project, $ipZone, $ipName);
$ip = $response->address;

which runs well and gives me the correct IP address. I then continue and try to create my instance while assigning the new IP:

$networkConfig = new Google_Service_Compute_AccessConfig();
$networkConfig->setNatIP($ip);
$networkConfig->setType("ONE_TO_ONE_NAT");
$networkConfig->setName("External NAT");
$googleNetworkInterfaceObj->setAccessConfigs($networkConfig);

The static IP is created, the instance is created, but IP is not assigned to the instance. To remove my doubt about the pending status, I also tried to assign an already created static IP to my instance, thus using:

$networkConfig->setNatIP("xxx.xxx.xxx.xxx");

With no more success... What am I missing here ?

Upvotes: 0

Views: 270

Answers (2)

Martin Zeitler
Martin Zeitler

Reputation: 76669

this would be the whole procedure, which assigns a network:

$instance = new Google_Instance();
$instance->setKind("compute#instance");

$accessConfig = new Google_AccessConfig();
$accessConfig->setName("External NAT");
$accessConfig->setType("ONE_TO_ONE_NAT");

$network = new Google_NetworkInterface();
$network->setNetwork($this->getObjectUrl($networkName, 'networks', $environment->getPlatformConfigValue(self::PROJECT_ID)));
$network->setAccessConfigs(array($accessConfig));

$instance->setNetworkInterfaces(array($network));

$addr->setName() is barely cosmetic; try $addr->setAddress($ipAddress).

guess the Google_NetworkInterface would need the $addr assigned.

sorry, currently have no spare IP and do not want to pay only to provide code.

Upvotes: 0

Caner
Caner

Reputation: 59168

I think this line:

$googleNetworkInterfaceObj->setAccessConfigs($networkConfig);

should be:

$googleNetworkInterfaceObj->setAccessConfigs(array($networkConfig));

If this doesn't work, there might be another error somewhere else.

Upvotes: 2

Related Questions