22
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CloudFormationの分割とチェーン実行を試してみる

Posted at

JAWS-UG 島根支部 第0回勉強会に参加してCloudFormationのTipsとしてTemplateは分割してチェーン実行すると良いというのを知ったので試してみた。

今までどーんと1つのTemplate作ってしまってたけど、これだと実用的に利用出来そう。

呼び出すTemplate

  • 以下のTemplate作成してs3-ap-northeast-1のhogemoge-publicバケットにs3_bucket_policy.templateの名前で配置しアクセスできるようにしておく
  • Parametersで指定されたS3バケットに適当なバケットポリシーを設定してポリシー名を出力する簡単なTemplate
{
  "AWSTemplateFormatVersion" : "2010-09-09",

  "Description" : "test",

  "Parameters" : {
    "BucketName" : {
      "Type" : "String",
      "Default" : "",
      "Description" : ""
    }
  },
  
  "Resources" : {
    "S3BucketPolicy" : {
      "Type" : "AWS::S3::BucketPolicy",
      "Properties" : {
        "PolicyDocument" : {
          "Statement": [{
            "Effect": "Allow",
            "Principal": { "AWS": "*" },
            "Action": "s3:GetObject",
            "Resource": { 
              "Fn::Join" : [ 
                "", 
                ["arn:aws:s3:::", { "Ref" : "BucketName" }, "/*" ]
              ]
            }, 
            "Condition": {
		      "StringLike": {
			     "aws:UserAgent": [ "hoge*" ]
			  }
		    }
          }]
        },
        
        "Bucket" : { "Ref" : "BucketName" }
      }
    }
  },
  
  "Outputs" : {
    "S3BucketPolicy" : {
      "Value" : { "Ref" : "S3BucketPolicy" }
    }
  }
}

大元のTemplate

  • 他のTemplateを呼び出す際のResourceは以下のようにする
  • TypeはAWS::CloudFormation::Stack
  • TemplateURLで呼び出すTemplateを指定
  • TemplateのParametersがある場合はそれも指定
  • 呼び出したTemplateのOutputsを以下のように参照可能
  • { "Fn::GetAtt" : ["[Template呼び出したResource名]", "Outputs.[TemplateのOutputsのキー指定]"]}
{
  "AWSTemplateFormatVersion" : "2010-09-09",

  "Description" : "test",

  "Resources" : {
    "Bucket" : {
      "Type" : "AWS::S3::Bucket"
    },
    
    "BucketPolicy" : {
      "Type" : "AWS::CloudFormation::Stack",
      "Properties" : {
        "TemplateURL" : "https://s3-ap-northeast-1.amazonaws.com/hogemoge-public/s3_bucket_policy.template",
        "Parameters" : {
          "BucketName" : { "Ref" : "Bucket" }
        }
      }
    }
  },

  "Outputs" : {
    "S3BucketPolicy" : {
      "Value" : { "Fn::GetAtt" : ["BucketPolicy", "Outputs.S3BucketPolicy"]}
    }
  }
}

Templateのチェーン実行

  • 大元のTemplate(hoge)を実行
  • 呼び出すTemplate(hoge-bucketpolicy-8tffgtdxlxim)も実行され結果が表示された

cloudformation_run.jpg

22
19
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
22
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?