LoginSignup
0
1

More than 5 years have passed since last update.

稼働しているEC2インスタンスからAMIを作成するshell script

Last updated at Posted at 2017-06-19

久しぶりの投稿です。

最近、稼働しているEC2インスタンスのAMIをリアルタイムで作成する必要が有ったので、shell scriptを使って実装してみました。

  • 前提
    • AWS CLIの設定(インストール~ aws configure での設定)が完了している
    • jqは使用せず、AWS CLIのオプション(filters, query, output等)のみで対応する

処理の流れはこんな感じ↓です

  1. "Instance State"が running で "tag" に Name が設定されているインスタンスのInstanceIdを取得して変数に格納する
  2. 1で取得したInstanceIdをキーにしてインスタンスに設定されている "tag" の Name を取得して変数に格納する
  3. 格納した変数をそれぞれ配列に格納する
  4. InstanceIdをキーにAMIを作成(AMI NameとDescriptionには2で取得した "tag" の Name + "-" + 今日の日付を設定する)
  5. 4で作成したAMIの "tag" の Name に2で取得した "tag" の Name + "-" + 今日の日付を設定する
  6. キーにしたInstanceIdが存在する間、4~5を繰り返す

ソースは以下↓です。

#!/bin/bash

set -eu

TODAY=`date '+%Y%m%d'`
instance_ids=""
instance_names=""
source_ids=""
source_names=""
j=0

## get instance_ids (only status is 'running' and tag-key=Name)
instance_ids=`aws ec2 describe-instances --filters "Name=instance-state-name,Values=running" "Name=tag-key,Values=Name" --query "Reservations[].Instances[].InstanceId" --output text`

## get instance_Name (only status is 'running' and tag-key=Name)
instance_names=`aws ec2 describe-instances --instance-ids ${instance_ids} --filters "Name=tag-key,Values=Name" --query "Reservations[].Instances[].Tags[].Value" --output text`

source_ids=($instance_ids)
source_names=($instance_names)

for i in "${source_ids[@]}"
do
  ami_id=""

  ## create ami
  ami_id=`aws ec2 create-image --instance-id ${i} --name "${source_names[$j]}-${TODAY}" --description "${source_names[$j]}-${TODAY}" --no-reboot --output text`

  ### put tags to ami
  aws ec2 create-tags --resources ${ami_id} --tags Key=Name,Value="${source_names[$j]}-${TODAY}"

  ## count up
  j=$((j+1))
done

exit 0

  • 注意事項
    • AMIを作成するインスタンス情報の取得の際にOWNER ID等での制限をしていないので、クロスアカウントでの使用の際には注意が必要
    • インスタンスの状態が'running'になっているもの全てに対してAMIを作成するようになっているので、台数が多い場合には注意が必要

スクリプトは こちら にもありますので、ご自由に使ってください。
処理自体は非常にシンプルになっています(自分の実力でもありますが...)
基本的な動作確認はしていますが、もし何かありましたらそっと修正して教えていただくと非常にありがたいです!

0
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
0
1