#!/bin/bash MODE=$1 REGION=$2 # テンプレートファイル TEMPLATE=template.yml # スタック名 ( gitプロジェクトの場合はgitリポジトリ名、それ以外の場合はフォルダ名をスタック名とする ) cd `dirname $0` STACK_NAME=`basename \`pwd\`` if [ -e ".git" ]; then STACK_NAME=`cat .git/config | grep url | head -1 | awk -F"/" '{print $NF}'` fi STACK_NAME=`echo $STACK_NAME | sed 's/_/-/g' | sed 's/Repo$/Stack/'` # アカウントIDの取得 ACCOUNT_ID=`aws sts get-caller-identity | grep Account | awk '{print $2}' | sed -e "s/[^0-9]//g"` # リージョンの設定 if [ "${REGION}" == "" ]; then # 未指定時はデフォルトリージョン REGION=`aws configure list | grep "region" | awk '{print $2}'` fi REGION_PARAM="--region ${REGION}" # スタック作成時のイベント確認 if [ "${MODE}" == "events" ]; then echo "Display events of Stack: ${STACK_NAME}" aws cloudformation describe-stack-events --region $REGION --stack-name $STACK_NAME exit 0 fi # 削除 if [ "${MODE}" == "delete" ]; then echo "Delete Stack: ${STACK_NAME}" aws cloudformation delete-stack --region $REGION --stack-name $STACK_NAME aws cloudformation wait stack-delete-complete --region $REGION --stack-name $STACK_NAME exit 0 fi # 登録/更新 if [ "${MODE}" == "deploy" ]; then echo "Create/Update Stack: ${STACK_NAME}" # S3バケットがない場合は作る(バケット名は世界で唯一である必要がある為、末尾にアカウントID等を付与しておく) #BUCKET_NAME=stack-${STACK_NAME}-${ACCOUNT_ID} BUCKET_NAME=cloudformation-templates-${REGION}-${ACCOUNT_ID} BUCKET_COUNT=`aws s3api list-buckets | grep -e "\"${BUCKET_NAME}\"" | wc -l | awk '{print $1}'` if [ "${BUCKET_COUNT}" == "0" ]; then echo create bucket: ${BUCKET_NAME} aws s3api create-bucket --region $REGION --create-bucket-configuration '{"LocationConstraint": "ap-northeast-1"}' --bucket $BUCKET_NAME fi # 検証&パッケージング&デプロイ(成功時は作成したAPIのURIを表示する) #aws cloudformation validate-template --template-body file://${TEMPLATE} \ aws cloudformation package --region $REGION --template-file $TEMPLATE --s3-bucket $BUCKET_NAME --output-template-file packaged-template.yml \ && aws cloudformation deploy --region $REGION --template-file packaged-template.yml --stack-name $STACK_NAME --capabilities CAPABILITY_IAM CAPABILITY_NAMED_IAM CAPABILITY_AUTO_EXPAND \ && echo "" \ && echo "### Exported Value ###" \ && aws cloudformation describe-stacks --region $REGION --stack-name $STACK_NAME \ | awk 'BEGIN{key=""}{ if ($1 == "\"OutputKey\":") key=$2; if ($1 == "\"OutputValue\":") print key" : "$2 }' \ | sed 's/[",]//g' \ && echo "######################/" \ && echo "" exit 0 fi echo "Usage)" echo "" echo " ${0} (deploy|delete|events)" echo "" echo "Example)" echo "" echo " # create or update stack named '${STACK_NAME}'" echo " ${0} deploy" echo "" echo " # delete stack '${STACK_NAME}' named" echo " ${0} delete" echo "" echo " # display events details of create or update or delete stack named '${STACK_NAME}'" echo " ${0} events" echo "" echo "Details)" echo "" echo " StackName ... The stack name will be the git repository name or folder name" echo ""
※ 関連 AWS CloudFormationメモ