LoginSignup
1
1

More than 3 years have passed since last update.

AWS CLIでオートスケーリンググループの更新・デプロイ

Posted at

TL;DL

bash deploy.sh v1.1.1
deploy.sh
#!/bin/bash
echo ""
echo "### Start Deploy $1 ###"
echo ""

echo ""
echo "### SSH Server ###"
echo ""
ssh -A YourSSHTarget bash deploy.sh

echo ""
echo "### Creating New AMI ###"
echo ""
created_ami_id=$(aws ec2 create-image --instance-id YourInstanceId --name "InstanceName-$1" | jq -r .ImageId)
echo "AMI_ID: $created_ami_id created"

echo ""
echo "### Update Launch Template ###"
echo ""

# update launch template
prev_template_ver=$( aws ec2 describe-launch-templates \
    --launch-template-ids YourTemplateId | \
    jq -r '.LaunchTemplates[].DefaultVersionNumber')

new_template_json=$(aws ec2 create-launch-template-version \
    --launch-template-id YourTemplateId \
    --version-description $1 \
    --source-version $prev_template_ver \
    --launch-template-data "ImageId=$created_ami_id")
echo $new_template_json| jq .

echo ""
echo "### Restart Autoscaling Group ###"
echo ""
# restart servers
aws autoscaling start-instance-refresh --auto-scaling-group-name YourAutoscalingGroupName

概要

パイプラインとかコードデプロイとかを使うのがモダンだが、まずはシェルでも良いかということで、書いてみた。

sshで対象のインスタンスに接続、今回はprivate subnetにあるインスタンスだったので、ssh configのプロキシ使用し、踏み台経由でアクセス。リモートサーバーで実行したい処理を実行(ソースコードもってくるなど) githubの認証情報をssh-agentに持たせたため、-Aオプション使用。

echo ""
echo "### SSH Server ###"
echo ""
ssh -A your-ssh-target bash deploy.sh

対象のインスタンス、でアップデート等が済み新しいバージョンが動き始めるようになったら、対象インスタンスからAMI作成。

echo ""
echo "### Creating New AMI ###"
echo ""
created_ami_id=$(aws ec2 create-image --instance-id YourInstanceId --name "InstanceName-$1" | jq -r .ImageId)
echo "AMI_ID: $created_ami_id created"

更新したAMIを元に起動テンプレートの新しいバージョン作成
--source-versionを指定したかったので、対象起動テンプレートのデフォを取得した。

echo ""
echo "### Update Launch Template ###"
echo ""

# update launch template
prev_template_ver=$( aws ec2 describe-launch-templates \
    --launch-template-ids YourTemplateId | \
    jq -r '.LaunchTemplates[].DefaultVersionNumber')

new_template_json=$(aws ec2 create-launch-template-version \
    --launch-template-id YourTemplateId \
    --version-description $1 \
    --source-version $prev_template_ver \
    --launch-template-data "ImageId=$created_ami_id")
echo $new_template_json| jq .

今回はオートスケーリング グループの設定として常に起動テンプレートの最新バージョンを参照するように設定しているため、あとはインスタンス更新をトリガーする。


echo ""
echo "### Restart Autoscaling Group ###"
echo ""
# restart servers
aws autoscaling start-instance-refresh --auto-scaling-group-name YourAutoscalingGroupName

注意

AWS CLI v2.0.54
バージョンが違うと一部コマンドが実行できない。またpipだと最新版まで上げられなかったため公式ドキュメントの方法で最新版をインストールした。

試しに動かす際は、--dray-runをつけた方がいい。実際に変更は加えられないがエラーが起きるかどうか確認できる

ちゃんと使うなら、各種IDは別ファイルを参照させたりする、インスタンスが起動状態を確認する、例外処理を加えるなどの追記が必要。現状とりあえずお手軽版

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1