0
0

More than 3 years have passed since last update.

[AWS]boto3でEIPを変更する(取得→関連付け→開放まで)

Posted at

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を変更するなどもできます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0