boto3を使用してEIPを変更する(取得→関連付け→開放まで)方法です。
インスタンスIDで指定
import boto3
from botocore.exceptions import ClientError
ec2 = boto3.client('ec2')
try:
filters = [
{'Name': 'instance-id', 'Values': ['i-xxxxxxxxxxxxxx']}
] #EC2のインスタンスIDでフィルターする
addresses = ec2.describe_addresses(Filters=filters)
address_list = addresses["Addresses"]
address = address_list[0] if len(address_list) else ''
old_allocationid = address["AllocationId"]
allocation = ec2.allocate_address(Domain='vpc') #EIP取得
associate = ec2.associate_address(AllocationId=allocation['AllocationId'],InstanceId='i-xxxxxxxxxxxxxx') #EIP関連付け
release = ec2.release_address(AllocationId=old_allocationid) #古いEIPを開放
print('Address released')
except ClientError as e:
print(e)
ENIで指定
import boto3
from botocore.exceptions import ClientError
ec2 = boto3.client('ec2')
try:
filters = [
{'Name': 'network-interface-id', 'Values': ['eni-xxxxxxxxxxxxxx']}
]#ネットワークインターフェースIDでフィルターする
addresses = ec2.describe_addresses(Filters=filters)
address_list = addresses["Addresses"]
address = address_list[0] if len(address_list) else ''
old_allocationid = address["AllocationId"]
allocation = ec2.allocate_address(Domain='vpc') #EIP取得
associate = ec2.associate_address(AllocationId=allocation['AllocationId'],NetworkInterfaceId='eni-xxxxxxxxxxxxxx') #EIP関連付け
release = ec2.release_address(AllocationId=old_allocationid) #古いEIPを開放
print('Address released')
except ClientError as e:
print(e)
他にも、特定のプライベートIPを持つENIに関連づいているEIPを変更するなどもできます。