亚马逊 AWS EC2 弹性ip绑定与释放

#!/usr/bin/env python3

import boto3
import os
import time
from botocore.exceptions import ClientError

def get_ip():
    out = os.popen("/sbin/ifconfig | grep 'inet addr:' | grep -v '127.0.0.1' | cut -d: -f2 | awk '{print $1}' | head -1").read()
    ip=out.split('\n')[0]
    return ip
res = get_ip()
print(res)


ec2 = boto3.client('ec2', region_name='us-west-1')
filters = [
    {'Name': 'private-ip-address', 'Values': [res]}
]
instances = ec2.describe_instances(Filters=filters)
INSTANCE_ID=instances['Reservations'][0]['Instances'][0]['InstanceId']
print(INSTANCE_ID)

AssociationIds = ec2.describe_addresses(Filters=filters)
Addresses=AssociationIds['Addresses']
print(Addresses)
if Addresses:
    ALLOCATION_ID = AssociationIds['Addresses'][0]['AllocationId']
    print(ALLOCATION_ID)
    try:
        response1 = ec2.release_address(AllocationId=ALLOCATION_ID)
        allocation = ec2.allocate_address(Domain='vpc')
        print(allocation)
        filename= '/home/ubuntu/ip.txt'
        with open(filename,'a+') as file_object:
            file_object.write('\n'+allocation['PublicIp'])
        response2 = ec2.associate_address(AllocationId=allocation['AllocationId'],
                                     InstanceId=INSTANCE_ID)
    except ClientError as e:
        print(e)
else:
    try:
        allocation = ec2.allocate_address(Domain='vpc')
        print(allocation)
        response2 = ec2.associate_address(AllocationId=allocation['AllocationId'],
                                     InstanceId=INSTANCE_ID)
    except ClientError as e:
        print(e)
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import boto3
import os
import time
from botocore.exceptions import ClientError


for regionname in ['us-east-1','us-east-2','us-west-1','us-west-2','af-south-1','ap-east-1','ap-south-1','ap-northeast-2','ap-southeast-1','ap-southeast-2','ap-northeast-1','ca-central-1','eu-central-1','eu-west-1','eu-west-2','eu-south-1','eu-west-3','eu-north-1']:
    try:
        ec2 = boto3.client('ec2', region_name=regionname)
        AssociationIds = ec2.describe_addresses()
        Addresses=AssociationIds['Addresses']
    except:
        print('regionname:error')
        print(regionname)

    print(Addresses)
    if Addresses :
        for Address in Addresses:
            print(Address)
            if 'InstanceId' in Address.keys():
                 print(Address['InstanceId'])
            else:
                 print('销毁')
                 ALLOCATION_ID=Address['AllocationId']
                 response1 = ec2.release_address(AllocationId=ALLOCATION_ID)