Python implementation of Aliyun ECS host public network IP switching function program

Source: Internet
Author: User
Tags json sleep aliyun in python

For acquisition, registration or agent, if the server public network IP can automatically switch, then there may be a lot less trouble. Recently, bloggers have implemented this small function using the Aliyun API. The implementation of the steps are relatively simple, first need to apply for Aliyun API key. Then apply for VPC proprietary network, ordinary classic ECS host can not mount elastic IP, in the newly applied proprietary network to open an ECS server. Then apply for elastic public network IP. Finally, this public network IP mount to the exclusive network of ECS. After the completion of the payment consists of two parts, one is ECS costs (package year or monthly, prepaid), in addition to the flexible public network EIP costs (by volume, after pay).

The next step is to implement it in Python. Aliyun provides the Python SDK, where the blogger uses the SDK directly.

First step: Create VPC and ECS

This can be created directly on the Aliyun page.

Step Two: Install the SDK

Pip Install Aliyun-python-sdk-ecs
Not clear can refer to the Ali Cloud: Https://develop.aliyun.com/sdk/python

The third step: Elastic public Network IP method

The code resembles the following:

Application

def create_eip_address (regionid= ' Cn-hongkong ', chargetype= ' paybybandwidth ', bandwidth=1,fmt= ' json '):
Request=allocateeipaddressrequest.allocateeipaddressrequest ()
Request.set_accept_format (FMT)
Request.set_bandwidth (bandwidth)
Request.add_query_param (' RegionID ', RegionID)
Request.add_query_param (' Internetchargetype ', Chargetype)

Try
Result=clt.do_action (Request)
R_dict=json.loads (Result)
Except
Print ("Create EIP address Failed.")
Sys.exit ()

If R_dict.has_key (' eipaddress '):
res={}
res[' IP ']=r_dict[' eipaddress ']
res[' id ']=r_dict[' allocationid ']
return res
Else
Print (r_dict[' message ')
Sys.exit ()
Delete

def delete_eip_address (eipid,fmt= ' json '):
Request=releaseeipaddressrequest.releaseeipaddressrequest ()
Request.set_accept_format (FMT)
Request.set_allocationid (Eipid)
Try
Result=clt.do_action (Request)
R_dict=json.loads (Result)
Except
Print ("Delete EIP address Failed.")
Sys.exit ()

If R_dict.has_key (' Code '):
Print (r_dict[' message ')
Sys.exit ()
Else
Return r_dict
Binding

def associate_eip_address (allocationid,instanceid,instancetype= ' ecsinstance ', fmt= ' json '):
Request=associateeipaddressrequest.associateeipaddressrequest ()
Request.set_accept_format (FMT)
Request.set_allocationid (Allocationid)
Request.add_query_param (' Instancetype ', instancetype)
Request.set_instanceid (Instanceid)
Try
Result=clt.do_action (Request)
R_dict=json.loads (Result)
Except
Print ("Associate EIP Address Failed.")
Sys.exit ()

If R_dict.has_key (' Code '):
Print (r_dict[' message ')
Sys.exit ()
Else
Return r_dict
Untied

def unassociate_eip_address (allocationid,instanceid,instancetype= ' ecsinstance ', fmt= ' json '):
Request=unassociateeipaddressrequest.unassociateeipaddressrequest ()
Request.set_accept_format (FMT)
Request.set_allocationid (Allocationid)
Request.add_query_param (' Instancetype ', instancetype)
Request.set_instanceid (Instanceid)
Try
Result=clt.do_action (Request)
R_dict=json.loads (Result)
Except
Print ("Unassociate EIP address Failed.")
Sys.exit ()

If R_dict.has_key (' Code '):
Print (r_dict[' message ')
Sys.exit ()
Else
Return r_dict
The above is a number of flexible public network IP 4 methods, respectively, the implementation of IP applications, delete, binding and bind the function.

Fourth step: Replace the IP

To replace the IP step:

Obtain ECS information--There are eip--> the EIP-> delete the old EIP--> apply for new EIP--> bind the new EIP to ECS
| ^
| |
-------------------No EIP------------------------
In the deletion of the old public IP before the need to determine whether the real solution, or the binding request to Aliyun immediately after the removal of the old EIP may be due to the EIP has not yet been untied and error.

The code resembles the following:

def main ():
#获取当前vpc下ecs主机的eip
Instance=instance_info (ecs_vpc_id)
eip_id=instance[' eipaddress ' [' Allocationid ']
eip_ip=instance[' eipaddress ' [' IPAddress ']
If not instance:
Print ("Get instance info error.")
Sys.exit ()
Else
If not eip_id:
Print ("Instance%s has not associate an EIP address.")% ecs_vpc_id
Else
Print ("Instance:%s, Eip ID:%s.")% (ecs_vpc_id,eip_id)

#解绑eip
Result_unassociate=unassociate_eip_address (eip_id, ecs_vpc_id)
If not result_unassociate:
Print ("Unassociate EIP address from%s error.") ecs_vpc_id
Sys.exit ()

#判断真正解绑后开始删除老的eip
While True:
Eip_id_tmp=instance_info (ecs_vpc_id) [' eipaddress '] [' Allocationid ']
If not eip_id_tmp:
#删除老的eip
Result_release=delete_eip_address (eip_id)
If not result_release:
Print ("Release EIP%s error.")% eip_id
Sys.exit ()
Break
Else
Continue
Time.sleep (1)

#申请新eip
Result_allocate=create_eip_address (Bandwidth=eip_bandwidth)
If not result_allocate:
Print ("Allocate new EIP address error.")
Sys.exit ()

#time. Sleep (10)

#绑定eip
Result_associate=associate_eip_address (result_allocate[' id '), instanceid=ecs_vpc_id)
If not result_associate:
Print ("Associate Eip%s to instance%s error.")% (result_allocate,ecs_vpc_id)
Sys.exit ()
Else
Print ("Associate Eip%s to instance%s successfully.")% (result_allocate[' IP '],ecs_vpc_id)
ip_dict={
' Oip ': eip_ip,
' Nip ': result_allocate[' IP ']
}
Return ip_dict

The above code I put on the GitHub, address: Https://github.com/zhangnq/scripts/tree/master/python/aliyun, interested friends can also see

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.