概要

AWS CloudFormation スタックとスタックセットのテンプレートを一括で取得、保存するスクリプトをAWS CLIを使用して作成しました。

コード

#!/bin/bash

# AWSアカウントIDを取得する
account_id=$(aws sts get-caller-identity --query 'Account' --output text)

# CloudFormationスタックのリストを取得する
stacks=$(aws cloudformation describe-stacks --query 'Stacks[].StackName' --output text)

# CloudFormationスタックセットのリストを取得する
stack_sets=$(aws cloudformation list-stack-sets --status ACTIVE --query 'Summaries[].StackSetName' --output text)

# スタックまたはスタックセットがない場合
if [ -z "$stacks" ] && [ -z "$stack_sets" ]; then
  echo "No CloudFormation stacks and stack sets found in AWS Account ${account_id}."
  exit 0
fi

# stack-templatesディレクトリを作成する
if [ -n "$stacks" ]; then
  mkdir "stack-templates"

  # 各スタックに対してテンプレートを保存する
  for stack in $stacks; do
    aws cloudformation get-template --stack-name "$stack" --query 'TemplateBody' --output text > "stack-templates/${stack}.yml"
  done
fi

# stack-sets-templatesディレクトリを作成する
if [ -n "$stack_sets" ]; then
  mkdir "stack-sets-templates"

  # 各スタックセットに対してテンプレートを保存する
  for stack_set in $stack_sets; do
    aws cloudformation describe-stack-set --stack-set-name "$stack_set" --query 'StackSet.TemplateBody' --output text > "stack-sets-templates/${stack_set}.yml"
  done
fi

# テンプレートディレクトリのZIPアーカイブを作成する
zip -r "${account_id}.zip" stack-templates stack-sets-templates
rm -rf stack-templates stack-sets-templates

全文はこちら

AWS CloudFormation StackとStackSetのテンプレートを一括エクスポートするBashスクリプト
著者:@y-kob