Created
September 5, 2013 15:42
-
-
Save yuta-imai/6451933 to your computer and use it in GitHub Desktop.
botoを使って、EC2が自分でEIPをアロケートして自分にアタッチするサンプルスクリプト
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto.ec2 | |
import boto.sts | |
import commands | |
# fetch credential via sts | |
# stsはus-eastにのみエンドポイントがある | |
# EC2のIAM ROLEに紐付いた期限付きcredentialをSTSを使って取得する | |
sts = boto.sts.connect_to_region("us-east-1") | |
credential = sts.get_session_token() | |
# create EC2 connection | |
# この例ではap-northeast-1(東京)にEC2が起動している | |
conn = boto.ec2.connect_to_region( | |
"us-west-2", | |
aws_access_key_id=credential.access_key, | |
aws_secret_access_key=credential.secret_key, | |
security_token=credential.session_token | |
) | |
# allocate new elastic ip | |
new_ip_address = conn.allocate_address('vpc') | |
# fetch current instance's id | |
# amazon linuxならec2-metadataがプリインストールされている | |
instance_id = commands.getoutput( | |
"ec2-metadata | grep instance-id | awk '{print $2}'" | |
) | |
# EIPを自分に紐付ける | |
print conn.associate_address( | |
instance_id=instance_id, | |
allocation_id=new_ip_address.allocation_id | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment