処理の実行
VPC IDを取得します。
コマンド:
EC2_VPC_ID=$( \
aws ec2 describe-vpcs \
--filters Name=tag:Name,Values=${EC2_VPC_TAG_NAME} \
--query 'Vpcs[].VpcId' \
--output text \
) \
&& echo ${EC2_VPC_ID}
結果(例):
セキュリティグループIDを取得します。
コマンド:
EC2_SECURITY_GROUP_ID=$( \
aws ec2 describe-security-groups \
--filter Name=vpc-id,Values=${EC2_VPC_ID} \
Name=group-name,Values=${EC2_SECURITY_GROUP_NAME} \
--query "SecurityGroups[].GroupId" \
--output text \
) \
&& echo ${EC2_SECURITY_GROUP_ID}
結果(例):
IAMポリシードキュメントを作成します。
変数の確認:
cat << EOF
# FILE_IAM_POLICY_DOC:"${HOME}/environment/conf-handson-cli-lambda/EC2SecurityGroupIngressAuthorize-lambda-handson-cli-lambda-boto3-ec2-authorize-function-policy.json"
FILE_IAM_POLICY_DOC="${FILE_IAM_POLICY_DOC}"
# AWS_DEFAULT_REGION:"ap-northeast-1"
AWS_DEFAULT_REGION="${AWS_DEFAULT_REGION}"
# EC2_VPC_ID:"vpc-xxxxxxxxxxxxxxxxx"
EC2_VPC_ID="${EC2_VPC_ID}"
# EC2_SECURITY_GROUP_ID:"sg-xxxxxxxxxxxxxxxxx"
EC2_SECURITY_GROUP_ID="${EC2_SECURITY_GROUP_ID}"
EOF
コマンド:
cat << EOF > ${FILE_IAM_POLICY_DOC}
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:AuthorizeSecurityGroupIngress"
],
"Resource": "arn:aws:ec2:${AWS_DEFAULT_REGION}:*:security-group/${EC2_SECURITY_GROUP_ID}",
"Condition": {
"ArnEquals": {
"ec2:Vpc": "arn:aws:ec2:${AWS_DEFAULT_REGION}:*:vpc/${EC2_VPC_ID}"
}
}
},
{
"Effect": "Allow",
"Action": "ec2:DescribeSecurityGroups",
"Resource": "*"
}
]
}
EOF
cat ${FILE_IAM_POLICY_DOC}
結果(例):
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:AuthorizeSecurityGroupIngress"
],
"Resource": "arn:aws:ec2:ap-northeast-1::security-group/|EC2_SECURITY_GROUP_ID|",
"Condition": {
"ArnEquals": {
"ec2:Vpc": "arn:aws:ec2:|AWS_DEFAULT_REGION|::vpc/vpc-xxxxxxxxxxxxxxxxx"
}
}
},
{
"Effect": "Allow",
"Action": "ec2:DescribeSecurityGroups",
"Resource": "*"
}
]
}
JSONファイルを作成したら、フォーマットが壊れてないか必ず確認します。
コマンド:
cat ${FILE_IAM_POLICY_DOC} \
| python3 -m json.tool \
> /dev/null
結果(例):
完了確認
「IAMポリシードキュメント"${HOME}/environment/conf-handson-cli-lambda/EC2SecurityGroupIngressAuthorize-lambda-handson-cli-lambda-boto3-ec2-authorize-function-policy.json"が存在する。」ことを確認します。
コマンド:
ls ${FILE_IAM_POLICY_DOC}
結果(例):
${HOME}/environment/conf-handson-cli-lambda/EC2SecurityGroupIngressAuthorize-lambda-handson-cli-lambda-boto3-ec2-authorize-function-policy.json