Home  >  Article  >  Operation and Maintenance  >  How to perform renewal query and renewal management directly through API

How to perform renewal query and renewal management directly through API

坏嘻嘻
坏嘻嘻Original
2018-09-28 17:11:563734browse

The content of this article is about how to perform renewal query and renewal management directly through API. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

ECS instance renewal

This article mainly involves the following key functions:

Query the cloud server according to the expiration time

Renew the instance

Query the cloud server automatic renewal time

Set the cloud server automatic renewal time

For yearly and monthly cloud servers, the life cycle Very important. If cloud server resources cannot be renewed on time, the server may be locked or even released, thus affecting business continuity. The API helps you understand and check the expiration time of resources in a timely manner and complete the renewal and recharge function.

This article requires attention to the following API:

Query instance list

Renew instance

Query the expired cloud servers within the specified range

Query the API for the instance list. By filtering parameters, you can query the information of the instances that have expired within a certain time range. By setting the filtering parameters ExpiredStartTime and ExpiredEndTime (the time parameter is expressed in accordance with the ISO8601 standard and needs to use UTC time. The format is: yyyy-MM-ddTHH:mmZ.), you can easily query the list of instances that expire within this time range. If you need to filter by security group, just add the security group ID.

INSTANCE_EXPIRED_START_TIME_IN_UTC_STRING = '2017-01-22T00:00Z'
INSTANCE_EXPIRE_END_TIME_IN_UTC_STRING = '2017-01-28T00:00Z'
def describe_need_renew_instance(page_size=100, page_number=1, instance_id=None,
                                 check_need_renew=True, security_group_id=None):
    request = DescribeInstancesRequest()
    if check_need_renew is True:
        request.set_Filter3Key("ExpiredStartTime")
        request.set_Filter3Value(INSTANCE_EXPIRED_START_TIME_IN_UTC_STRING)
        request.set_Filter4Key("ExpiredEndTime")
        request.set_Filter4Value(INSTANCE_EXPIRE_END_TIME_IN_UTC_STRING)
    if instance_id is not None:
        request.set_InstanceIds(json.dumps([instance_id]))
    if security_group_id:
        request.set_SecurityGroupId(security_group_id)
    request.set_PageNumber(page_number)
    request.set_PageSize(page_size)
    return _send_request(request)

Renew cloud server

Renewal instances only support annual and monthly server types, and do not support pay-as-you-go servers. Users are also required to Must support account balance payment or credit payment. Synchronous deductions and order generation will be performed when executing the API. Therefore, when executing the API, you must ensure that your account has sufficient funds to support automatic deductions.

def _renew_instance_action(instance_id, period='1'):
    request = RenewInstanceRequest()
    request.set_Period(period)
    request.set_InstanceId(instance_id)
    response = _send_request(request)
    logging.info('renew %s ready, output is %s ', instance_id, response)

The renewal instance will be deducted automatically. After the renewal is completed, you can query the resource expiration time of the instance based on the InstanceId. Since the API is an asynchronous task, the query resource expiration time may take 10 seconds to change.

Enable automatic cloud server renewal

#In order to reduce your resource expiration maintenance costs, Alibaba Cloud also provides The automatic renewal function has been launched. The automatic renewal and deduction date is 08:00:00 on the 9th day before the server expires. If the automatic deduction fails on the previous day, it will continue to be executed regularly on the next day until the deduction is completed or the resource lock expires in 9 days. You only need to ensure that your account balance or credit limit is sufficient.

Query automatic renewal settings

You can query and set automatic renewal through OpenAPI. This API only supports annual and monthly subscription instances, and an error will be reported when executing pay-as-you-go instances. Querying the automatic renewal status of an instance supports querying up to 100 annual and monthly subscription instances at a time. Multiple instance IDs are connected with commas.

The input parameter of DescribeInstanceAutoRenewAttribut is the instance ID.

InstanceId: supports querying up to 100 annual and monthly subscription instances. Multiple instance IDs are connected with commas.

python # check the instances is renew or not def describe_auto_renew(instance_ids, expected_auto_renew=True): describe_request = DescribeInstanceAutoRenewAttributeRequest() describe_request.set_InstanceId(instance_ids) response_detail = _send_request(request=describe_request) failed_instance_ids = '' if response_detail is not None: attributes = response_detail.get('InstanceRenewAttributes').get('InstanceRenewAttribute') if attributes: for item in attributes: auto_renew_status = item.get('AutoRenewEnabled') if auto_renew_status != expected_auto_renew: failed_instance_ids = item.get ('InstanceId') ',' describe_auto_renew('i-1111,i-2222')

The returned content is as follows:

{"InstanceRenewAttributes":{"InstanceRenewAttribute":
[{"Duration":0,"InstanceId":"i-1111","AutoRenewEnabled":false},
{"Duration":0,"InstanceId":"i-2222","AutoRenewEnabled":false}]},
"RequestId":"71FBB7A5-C793-4A0D-B17E-D6B426EA746A"}

If automatic renewal is set, the returned attribute AutoRenewEnabled is true, Otherwise return false.

Set and cancel the automatic renewal of the cloud server

There are three input parameters for setting automatic renewal:

InstanceId: supports the most To query 100 annual and monthly subscription instances, multiple instance IDs are connected with commas.

Duration: supports 1, 2, 3, 6, 12, the unit is months.

AutoRenew: true/false, true means enabling automatic renewal, false means canceling automatic renewal.

python def setting_instance_auto_renew(instance_ids, auto_renew = True): logging.info('execute enable auto renew ' + instance_ids) request = ModifyInstanceAutoRenewAttributeRequest(); request.set_Duration(1); request.set_AutoRenew(auto_renew); request.set_InstanceId(instance_ids) _send_request(request)

执行成功返回 Response 如下:

python {"RequestId":"7DAC9984-AAB4-43EF-8FC7-7D74C57BE46D"}

续费成功后,您可以再执行一次查询。如果续费成功将返回续费时长以及是否开启自动续费。

python {"InstanceRenewAttributes":{"InstanceRenewAttribute":[{"Duration":1,"InstanceId":"i-1111","AutoRenewEnabled":true},{"Duration":1,"InstanceId":"i-2222","AutoRenewEnabled":true}]},"RequestId":"7F4D14B0-D0D2-48C7-B310-B1DF713D4331"}

完整的代码如下:

#  coding=utf-8
# if the python sdk is not install using 'sudo pip install aliyun-python-sdk-ecs'
# if the python sdk is install using 'sudo pip install --upgrade aliyun-python-sdk-ecs'
# make sure the sdk version is 2.1.2, you can use command 'pip show aliyun-python-sdk-ecs' to check
import json
import logging
from aliyunsdkcore import client
from aliyunsdkecs.request.v20140526.DescribeInstanceAutoRenewAttributeRequest import \
    DescribeInstanceAutoRenewAttributeRequest
from aliyunsdkecs.request.v20140526.DescribeInstancesRequest import DescribeInstancesRequest
from aliyunsdkecs.request.v20140526.ModifyInstanceAutoRenewAttributeRequest import \
    ModifyInstanceAutoRenewAttributeRequest
from aliyunsdkecs.request.v20140526.RenewInstanceRequest import RenewInstanceRequest
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                    datefmt='%a, %d %b %Y %H:%M:%S')
clt = client.AcsClient('Your Access Key Id', 'Your Access Key Secrect', 'cn-beijing')
# data format in UTC, only support passed the value for minute, seconds is not support.
INSTANCE_EXPIRED_START_TIME_IN_UTC_STRING = '2017-01-22T00:00Z'
INSTANCE_EXPIRE_END_TIME_IN_UTC_STRING = '2017-01-28T00:00Z'
def renew_job(page_size=100, page_number=1, check_need_renew=True, security_group_id=None):
    response = describe_need_renew_instance(page_size=page_size, page_number=page_number,
                                            check_need_renew=check_need_renew,
                                            security_group_id=security_group_id)
    response_list = response.get('Instances').get('Instance')
    logging.info("%s instances need to renew", str(response.get('TotalCount')))
    if response_list > 0:
        instance_ids = ''
        for item in response_list:
            instance_id = item.get('InstanceId')
            instance_ids += instance_id + ','
            renew_instance(instance_id=instance_id)
        logging.info("%s execute renew action ready", instance_ids)
def describe_need_renew_instance(page_size=100, page_number=1, instance_id=None,
                                 check_need_renew=True, security_group_id=None):
    request = DescribeInstancesRequest()
    if check_need_renew is True:
        request.set_Filter3Key("ExpiredStartTime")
        request.set_Filter3Value(INSTANCE_EXPIRED_START_TIME_IN_UTC_STRING)
        request.set_Filter4Key("ExpiredEndTime")
        request.set_Filter4Value(INSTANCE_EXPIRE_END_TIME_IN_UTC_STRING)
    if instance_id is not None:
        request.set_InstanceIds(json.dumps([instance_id]))
    if security_group_id:
        request.set_SecurityGroupId(security_group_id)
    request.set_PageNumber(page_number)
    request.set_PageSize(page_size)
    return _send_request(request)
# check the instances is renew or not
def describe_instance_auto_renew_setting(instance_ids, expected_auto_renew=True):
    describe_request = DescribeInstanceAutoRenewAttributeRequest()
    describe_request.set_InstanceId(instance_ids)
    response_detail = _send_request(request=describe_request)
    failed_instance_ids = ''
    if response_detail is not None:
        attributes = response_detail.get('InstanceRenewAttributes').get('InstanceRenewAttribute')
        if attributes:
            for item in attributes:
                auto_renew_status = item.get('AutoRenewEnabled')
                if auto_renew_status != expected_auto_renew:
                    failed_instance_ids += item.get('InstanceId') + ','
    if len(failed_instance_ids) > 0:
        logging.error("instance %s auto renew not match expect %s.", failed_instance_ids,
                      expected_auto_renew)
def setting_instance_auto_renew(instance_ids, auto_renew=True):
    logging.info('execute enable auto renew ' + instance_ids)
    request = ModifyInstanceAutoRenewAttributeRequest();
    request.set_Duration(1);
    request.set_AutoRenew(auto_renew);
    request.set_InstanceId(instance_ids)
    _send_request(request)
    describe_instance_auto_renew_setting(instance_ids, auto_renew)
# if using the instance id can be found means the instance is not renew successfully.
def check_instance_need_renew(instance_id):
    response = describe_need_renew_instance(instance_id=instance_id)
    if response is not None:
        return response.get('TotalCount') == 1
    return False
# 续费一个实例一个月
def renew_instance(instance_id, period='1'):
    need_renew = check_instance_need_renew(instance_id)
    if need_renew:
        _renew_instance_action(instance_id=instance_id, period=period)
        # describe_need_renew_instance(instance_id=instance_id, check_need_renew=False)
def _renew_instance_action(instance_id, period='1'):
    request = RenewInstanceRequest()
    request.set_Period(period)
    request.set_InstanceId(instance_id)
    response = _send_request(request)
    logging.info('renew %s ready, output is %s ', instance_id, response)
def _send_request(request):
    request.set_accept_format('json')
    try:
        response_str = clt.do_action(request)
        logging.info(response_str)
        response_detail = json.loads(response_str)
        return response_detail
    except Exception as e:
        logging.error(e)
if __name__ == '__main__':
    logging.info("Renew ECS Instance by OpenApi!")
    # 查询在指定的时间范围内是否有需要续费的实例。
    describe_need_renew_instance()
    # 续费一个实例, 直接执行扣费
    renew_instance('i-1111')
    # 查询实例自动续费的状态
    # describe_instance_auto_renew_setting('i-1111,i-2222')
    # 设置实例自动续费
    # setting_instance_auto_renew('i-1111,i-2222')

The above is the detailed content of How to perform renewal query and renewal management directly through API. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn