aliyun_autosnapshot/index.php

90 lines
3.7 KiB
PHP
Raw Permalink Normal View History

2024-09-23 19:28:42 +08:00
<?php
$config=[
'access_key_id'=>'',
'access_key_secret'=>'',
'disk_id'=>'',
'region_id'=>'cn-hangzhou',
];
if ($_SERVER['REMOTE_ADDR']!='127.0.0.1')
die();
require 'vendor/autoload.php';
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
// Downloadhttps://github.com/aliyun/openapi-sdk-php
// Usagehttps://github.com/aliyun/openapi-sdk-php/blob/master/README.md
AlibabaCloud::accessKeyClient($config['access_key_id'], $config['access_key_secret'])
// use STS Token
// AlibabaCloud::stsClient('<your-access-key-id>', '<your-access-key-secret>', '<your-sts-token>')
->regionId($config['region_id'])
->asDefaultClient();
try {
//查询快照
$result = AlibabaCloud::rpc()
->product('SWAS-OPEN')
// ->scheme('https') // https | http
->version('2020-06-01')
->action('ListSnapshots')
->method('POST')
->host("swas.{$config['region_id']}.aliyuncs.com")
->options([
'query' => [
'RegionId' => $config['region_id'],
],
])
->request();
//echo json_encode($result->toArray());
$name=(date("w")==1?'week-':'day-');
//删除多余快照
foreach($result['Snapshots'] as $i=>$snapshot){
if ($snapshot['SourceDiskId']==$config['disk_id'] && stripos($snapshot['SnapshotName'],$name)===0){
$result = AlibabaCloud::rpc()
->product('SWAS-OPEN')
// ->scheme('https') // https | http
->version('2020-06-01')
->action('DeleteSnapshot')
->method('POST')
->host("swas.{$config['region_id']}.aliyuncs.com")
->options([
'query' => [
'RegionId' => $config['region_id'],
'SnapshotId' => $snapshot['SnapshotId'],
],
])
->request();
}
}
//新建快照
$result = AlibabaCloud::rpc()
->product('SWAS-OPEN')
// ->scheme('https') // https | http
->version('2020-06-01')
->action('CreateSnapshot')
->method('POST')
->host("swas.{$config['region_id']}.aliyuncs.com")
->options([
'query' => [
'RegionId' => $config['region_id'],
'DiskId' => $config['disk_id'],
'SnapshotName' => $name.date("Y-m-d-H-i-s"),
],
])
->request();
//echo json_encode($result->toArray());
} catch (ClientException $e) {
echo $e->getErrorMessage() . PHP_EOL;
} catch (ServerException $e) {
echo $e->getErrorMessage() . PHP_EOL;
}