11. AWS CLIはオープンソース
#!/usr/bin/python
# Copyright 2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the License). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
# http://aws.amazon.com/apache2.0/
# or in the license file accompanying this file. This file is
# distributed on an AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.
import sys
import awscli.clidriver
def main():
return awscli.clidriver.main()
if __name__ == '__main__':
sys.exit(main())
39. bashなどのシェル – コマンド結果を活⽤用
awsコマンドの出⼒力力はフォーマットを text にすると、bashなどのシェル
で扱いやすいです。出⼒力力を1項⽬目に抑えると、複数の値が⾃自動的に配列列のよ
うに扱えます。複数項⽬目を扱う場合は、環境変数IFSで区切切り⽂文字を⼀一時的
に変更更することで、⾏行行ごとと列列ごとに分けて扱うことも可能です。
例例)全リージョンの起動中のEC2インスタンスを停⽌止する
IFS=$'n' output=$(aws --output text ec2 describe-regions)
for line in $output;
do
IFS=$'t' region_info=($line)
instances=$(aws --region ${region_info[2]} --output text ec2 describe-instances
--query 'Reservations[].Instances[?State.Name==`running`].InstanceId[]')
if [ $instances ]; then
aws --region ${region_info[2]} ec2 stop-instances --instance-ids $instances
fi
done
REGIONS ec2.eu-west-1.amazonaws.com eu-west-1
REGIONS ec2.sa-east-1.amazonaws.com sa-east-1
...
i-xxxxxxx i-xxxxxxx i-xxxxxxx
51. bashサンプル: 踏み台サーバからEC2インスタンスを⼿手動作成 (4/4)
$ aws ec2 create-security-group --vpc-id vpc-8c007ae4 --group-name 'Mgmt_FromMe' --description 'ssh from my'
{
return: true,
GroupId: sg-36ca0253
}
$ aws ec2 authorize-security-group-ingress --group-name 'Mgmt_FromMe' --cidr `curl -s ifconfig.me`/32 --
protocol tcp --port 22
$ instances=($instances)
$ aws ec2 modify-instance-attribute --instance-id ${instances[0]} --groups sg-36ca0253
$ aws ec2 modify-instance-attribute --instance-id ${instances[1]} --groups sg-36ca0253
$ aws ec2 describe-instances --instance-ids ${instances[@]} --query 'Reservations[].Instances[].
[PublicIpAddress][]' --output text
54.65.0.36 54.65.0.72
$ ssh -l ec2-user 54.65.0.36
The authenticity of host '54.65.0.36 (54.65.0.36)' can't be established.
RSA key fingerprint is 0d:bd:f5:b2:aa:71:d6:72:fb:23:47:c1:8a:c0:f2:d2.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '54.65.0.36' (RSA) to the list of known hosts.
__| __|_ )
_| ( / Amazon Linux AMI
___|___|___|
...
52. PowerShellサンプル: 実⾏行行中のインスタンスで⾃自動バックアップ (1/4)
事前確認
PS C:UsersAdministrator aws configure
AWS Access Key ID [None]:
AWS Secret Access Key [None]:
Default region name [None]:
Default output format [None]:
PS C:Scripts aws configure list
Name Value Type Location
---- ----- ---- --------
profile not set None None
access_key ****************YBMQ iam-role
secret_key ****************oScl iam-role
region not set None None