※ CloudFormation実行用のシェル
#!/bin/bash

MODE=$1

echo ""

# テンプレートファイル
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 [ "${MODE}" == "events" ]; then
    echo "Display events of Stack: ${STACK_NAME}"
    aws cloudformation describe-stack-events --stack-name $STACK_NAME
    exit 0
fi

# 削除
if [ "${MODE}" == "delete" ]; then
    echo "delete Stack: ${STACK_NAME}"
    aws cloudformation delete-stack --stack-name $STACK_NAME
    aws cloudformation wait stack-delete-complete --stack-name $STACK_NAME
    exit 0
fi

# 登録/更新
if [ "${MODE}" == "deploy" ]; then

    # S3バケットがない場合は作る(バケット名は世界で唯一である必要がある為、末尾にアカウントID等を付与しておく)
    #BUCKET_NAME=stack-${STACK_NAME}-${ACCOUNT_ID}
    BUCKET_NAME=cloudformation-templates-${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 --create-bucket-configuration '{"LocationConstraint": "ap-northeast-1"}' --bucket $BUCKET_NAME
    fi  
    
    # 検証&パッケージング&デプロイ(成功時は作成したAPIのURIを表示する)
    #aws cloudformation validate-template --template-body file://${TEMPLATE} \
    aws cloudformation package --template-file $TEMPLATE --s3-bucket $BUCKET_NAME --output-template-file packaged-template.yml \
      && aws cloudformation deploy --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 --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メモ


トップ   一覧 単語検索 最終更新   ヘルプ   最終更新のRSS