PHP Google Api客户端SQL管理员无法启用Auth IP

时间:2018-01-26 07:28:13

标签: php mysql google-api google-cloud-platform google-api-php-client

我有这个代码更新我的谷歌MySQL实例授权的IP,连接没问题,代码打印我当前的IP但它不能添加新的IP到我试过很多方面的设置,但它仍然不起作用它没有' t对实例配置进行任何更改。

$client = new Google_Client();
    $client->setAuthConfig('../config/service-account.json');
    $client->setApplicationName(env("APP_NAME"));
    $projectName = env("GOOGLE_PROJECT_NAME");
    $instanceName = env("SQL_INSTANCE_NAME");
    $scopes = [
        "https://www.googleapis.com/auth/sqlservice.admin",
        "https://www.googleapis.com/auth/compute",
    ];
    $client->addScope($scopes);
    $sql = new Google_Service_SQLAdmin($client);
    $sqlAdmin = new Google_Service_SQLAdmin_Settings($client);
    $instanceSettings = $sql->instances->get($projectName, $instanceName)->getSettings();
    $authNetworks = $instanceSettings->getIpConfiguration();
    $newAuthNetwork = new Google_Service_SQLAdmin_AclEntry($client);
    $newAuthNetwork->setName("tmp_ip_connection");
    $newAuthNetwork->setKind("sql#aclEntry");
    $authNetworks->setAuthorizedNetworks($newAuthNetwork);
    $ipv4 = file_get_contents('https://api.ipify.org');
    $newAuthNetwork->setValue($ipv4);
    $ipConfiguration = new Google_Service_SQLAdmin_IpConfiguration($client);
    $ipConfiguration->setIpv4Enabled(true);
    $ipConfiguration->setAuthorizedNetworks([$newAuthNetwork]);
    $instanceSettings->setIpConfiguration($ipConfiguration);
    $sql->instances->get($projectName, $instanceName)->setSettings($instanceSettings);
    //TODO why it is not working??
    print_r($sql->instances->get($projectName, $instanceName)->getSettings()->getIpConfiguration()->getAuthorizedNetworks());

1 个答案:

答案 0 :(得分:0)

您所缺少的主要内容是,您从未更改过实例。

工作示例:

$client = new Google_Client();
$client->setAuthConfig('../config/service-account.json');
$client->setApplicationName(env("APP_NAME"));
$projectName = env("GOOGLE_PROJECT_NAME");
$instanceName = env("SQL_INSTANCE_NAME");
$scopes = [
    "https://www.googleapis.com/auth/sqlservice.admin",
    "https://www.googleapis.com/auth/compute",
];
$client->addScope($scopes);
$sql = new Google_Service_SQLAdmin($client);

$instances = $sql->instances;
$instance = $instances->get('projectId', 'instanceId');
$networks = $instance->getSettings()->getIpConfiguration()->getAuthorizedNetworks();

$values = [];
foreach ($networks as $network) {
    $values[$network->getName()] = $network;
}

$values['1.production'] = array_get($values, '1.production', clone head($values));
$external_ip = @file_get_contents('http://ipecho.net/plain');
$values['1.production']->setValue("$external_ip/32");
$values['1.production']->setName('1.production');

$instance->getSettings()->getIpConfiguration()->setAuthorizedNetworks(array_values($values));

$instances->update('projectId', 'instanceId', $instance);