使用PHP动态调整腾讯云CVM的外网IP

PHP-SDK: https://github.com/QcloudApi/qcloudapi-sdk-php
云服务器 API 文档:https://cloud.tencent.com/document/api/213/9388
 
<?php
namespace QCloud;
use QCloud\QcloudApi\QcloudApi;
/**
* 腾讯云弹性IP操作类
*
* @author phpbin
*
*/
class MyQcApi
{
/**
* EIP实例
*
* @var Model
*/
private $EIP;
/**
* 服务器实例ID
*
* @var string
*/
private $InstanceId;
/**
* 初始化
*
* @param array $config
*/
public function __construct($config)
{
$this->InstanceId = $config[‘InstanceId’];
$this->EIP = QcloudApi::load(QcloudApi::MODULE_EIP, $config);
}
/**
* 换IP操作
*
* @return string
*/
public function changeAddresses()
{
// 1.获取弹性IP列表
$ips = $this->describeAddresses();
$addressId = $ips[‘AddressSet’][0][‘AddressId’];
if ( !$addressId) return ‘错误:获取弹性IP失败!’;
echo “获取:$addressId \n”;
// 2.解绑弹性IP
$res = $this->disassociateAddress($addressId);
if (!is_array($res)) return ‘错误:解绑弹性IP失败!’;
echo “解绑:$addressId \n”;
// 3.释放弹性IP
$res = $this->releaseAddresses($addressId);
if (!is_array($res)) return ‘错误:释放弹性IP失败!’;
echo “释放:$addressId \n”;
// 4.创建弹性IP
$ips = $this->allocateAddresses();
$newAddressId = $ips[‘AddressSet’][0];
if ( !$newAddressId) return ‘错误:创建弹性IP失败!’;
echo “创建:$addressId \n”;
// 5.绑定弹性IP
$res = $this->associateAddress($newAddressId, $this->InstanceId);
echo “绑定:$newAddressId, $this->InstanceId \n”;
return $res;
}
/**
* 获取弹性IP
*
* @return array
*/
public function describeAddresses()
{
$data = $this->EIP->DescribeAddresses(array(‘Version’=>’2017-03-12’));
return $this->scopeData($data);
}
/**
* 创建弹性IP
*
* @param number $num
* @return array
*/
public function allocateAddresses($num = 1)
{
$data = $this->EIP->AllocateAddresses(array(‘Version’=>’2017-03-12’, ‘AddressCount’=>$num));
return $this->scopeData($data);
}
/**
* 绑定弹性IP
*
* @param string $addressId
* @param string $instanceId
* @return array
*/
public function associateAddress($addressId, $instanceId)
{
$data = $this->EIP->AssociateAddress(
array(
‘Version’ => ‘2017-03-12’,
‘AddressId’ => $addressId,
‘InstanceId’ => $instanceId,
)
);
return $this->scopeData($data);
}
/**
* 解绑弹性IP
*
* @param string $addressId
* @return array
*/
public function disassociateAddress($addressId)
{
$data = $this->EIP->DisassociateAddress(array(‘Version’=>’2017-03-12’, ‘AddressId’=>$addressId));
return $this->scopeData($data);
}
/**
* 释放弹性IP
*
* @param string $addressId
* @param number $num
* @return array
*/
public function releaseAddresses($addressId, $num = 1)
{
$data = $this->EIP->ReleaseAddresses(array(‘Version’=>’2017-03-12’, ‘AddressIds.’.$num=>$addressId));
return $this->scopeData($data);
}
/**
* 数据处理
*
* @param array $data
* @return array
*/
private function scopeData($data)
{
if ($data === false) {
$error = $this->E->getError();
return $error->getMessage();
} else {
sleep(1);
return $data[‘Response’];
}
}
}

发表评论

邮箱地址不会被公开。 必填项已用*标注