{CloudFormation}スタックポリシー

https://dev.classmethod.jp/articles/disable-update-stack/


スタックポリシーを使用すると、スタックの更新中にスタックのリソースが意図せずに更新または削除されるのを防止できます。
スタックポリシーは、指定したリソースに対して実行できる更新アクションを定義する JSON ドキュメントです。


-- 1. コマンド等のインストール

-- 1.1 aws cli version 2 インストール

curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
aws --version


-- 2. スタック作成

vim a.yaml

AWSTemplateFormatVersion: "2010-09-09"
Description: Provision EC2
Resources:
  EC2: 
    Type: AWS::EC2::Instance
    Properties: 
      ImageId: ami-0404778e217f54308
      KeyName: key1
      InstanceType: t3.nano
      Tags:
          - Key: Name
            Value: test
Outputs:
  EC2PublicIP:
    Value: !GetAtt EC2.PublicIp
    Description: Public IP of EC2 instance

 

aws cloudformation validate-template \
--template-body file://a.yaml

aws cloudformation create-stack \
--stack-name stack01 \
--template-body file://a.yaml

-- 3. スタック一覧

aws cloudformation describe-stacks \
--stack-name stack01


aws cloudformation describe-stack-resources \
--stack-name stack01

-- 4. スタックポリシー設定
vim policy01.yaml
{
  "Statement" : [
    {
      "Effect" : "Deny",
      "Action" : "Update:*",
      "Principal": "*",
      "Resource" : "*"
    }  
  ]
}

aws cloudformation set-stack-policy \
--stack-name stack01 \
--stack-policy-body file://policy01.yaml

※スタック作成中はスタックポリシーを設定できない


aws cloudformation get-stack-policy \
--stack-name stack01


空のyamlを指定してスタックポリシーを更新。
get-stack-policyでなにも表示されなくなっても、スタックポリシーは残っている模様。
明示的に許可を与えるポリシーに変更する。

 

vim policy01.yaml
{
  "Statement" : [
    {
      "Effect" : "Allow",
      "Action" : "Update:*",
      "Principal": "*",
      "Resource" : "*"
    }  
  ]
}

aws cloudformation set-stack-policy \
--stack-name stack01 \
--stack-policy-body file://policy01.yaml


-- 5. スタック更新
t3.nano → t3.micro

vim a.yaml

AWSTemplateFormatVersion: "2010-09-09"
Description: Provision EC2
Resources:
  EC2: 
    Type: AWS::EC2::Instance
    Properties: 
      ImageId: ami-0404778e217f54308
      KeyName: key1
      InstanceType: t3.micro
      Tags:
          - Key: Name
            Value: test
Outputs:
  EC2PublicIP:
    Value: !GetAtt EC2.PublicIp
    Description: Public IP of EC2 instance

aws cloudformation update-stack \
--stack-name stack01 \
--template-body file://a.yaml


スタックポリシーがある場合下記エラー発生し、updateできない

Action denied by stack policy: Statement [#1] does not allow [Update:*] for resource [*];


aws cloudformation describe-stack-events \
--stack-name stack01

 

 

-- 6. クリーンアップ

-- スタック削除
aws cloudformation delete-stack \
--stack-name stack01