Python から AWS を操作出来るライブラリには有名な boto3 があります。 boto3 から EIP を扱うサンプルは Using Elastic IP Addresses in Amazon EC2 にまとまっています。 ほぼこの内容そのままですが、簡単なサンプルを書いてみたのでメモしておきます。
全ての EIP を表示する
import boto3
from botocore.exceptions import ClientError
ec2 = boto3.client('ec2')
try:
eips = ec2.describe_addresses()
for eip in eips['Addresses']:
print(eip['PublicIp'])
except ClientError as e:
print(e)
指定数、EIP を取得する
import boto3
import sys
from botocore.exceptions import ClientError
args = sys.argv
if 2 != len(args):
print('Usage: python allocate-eips.py [NUMBER]')
sys.exit(1)
ec2 = boto3.client('ec2')
try:
for i in range(int(args[1])):
eip = ec2.allocate_address(Domain='vpc')
print(eip['PublicIp'])
except ClientError as e:
print(e)
全ての EIP を削除する
import boto3
from botocore.exceptions import ClientError
ec2 = boto3.client('ec2')
try:
eips = ec2.describe_addresses()
for eip in eips['Addresses']:
ec2.release_address(AllocationId=eip['AllocationId'])
print(eip['PublicIp'] + ' released.')
except ClientError as e:
print(e)
コメント