Skip to main content
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
AWS 公式 Webinar
https://amzn.to/JPWebinar
過去資料
https://amzn.to/JPArchive
Solutions Architect 内田 大樹
2020/8/26
AWS CloudFormation
サービスカットシリーズ
[AWS Black Belt Online Seminar]
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
自己紹介
内田 大樹 (うちだ ひろき)
インダストリソリューション部
ソリューションアーキテクト
前職までの経験
通信会社でアプリケーション開発、監視、インフラ構
築する部署に所属。
好きなAWSのサービス
AWS Command Line Interface (CLI)
AWS Cloud Development Kit (CDK)
@nikuyoshi
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
AWS Black Belt Online Seminar とは
「サービス別」「ソリューション別」「業種別」のそれぞれのテーマに分かれて、アマゾ
ン ウェブ サービス ジャパン株式会社が主催するオンラインセミナーシリーズです。
質問を投げることができます!
• 書き込んだ質問は、主催者にしか見えません
• 今後のロードマップに関するご質問は
お答えできませんのでご了承下さい
Twitter ハッシュタグは以下をご利用ください
#awsblackbelt
① 吹き出しをクリック
② 質問を入力
③ Sendをクリック
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
内容についての注意点
• 本資料では2020年8月26日時点のサービス内容および価格についてご説明しています。最新の
情報はAWS公式ウェブサイト(http://aws.amazon.com)にてご確認ください。
• 資料作成には十分注意しておりますが、資料内の価格とAWS公式ウェブサイト記載の価格に相
違があった場合、AWS公式ウェブサイトの価格を優先とさせていただきます。
• 価格は税抜表記となっています。日本居住者のお客様には別途消費税をご請求させていただきま
す。
• AWS does not offer binding price quotes. AWS pricing is publicly available and is
subject to change in accordance with the AWS Customer Agreement available at
http://aws.amazon.com/agreement/. Any pricing information included in this
document is provided only as an estimate of usage charges for AWS services based on
certain information that you have provided. Monthly charges will be based on your
actual use of AWS services, and may vary from the estimates provided.
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
アジェンダと想定聴講者
アジェンダ
• CloudFormationの概要、始め方
• 開発
• テスト
• デプロイ
• 運用
• まとめ、Next Action
想定聴講者
• CloudFormationをこれから利用される方
• CloudFormationを既に使っている方
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
本資料の前提知識、ゴール
前提知識
AWSの概要を理解していること
YAML、JSONといったファイル形式の知識があること
ITインフラ自動化の概要を理解しているとより望ましい(必須ではない)
ゴール
2020年におけるCloudFormationの便利な機能、使い方を紹介し、
効率的な自動化の方法についてご理解いただくこと
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
本日お伝えしたいこと
• CloudFormationの概要
• CloudFormationの便利なツール
• CloudFormationの開発、テスト、デプロイ、運用の方法
本日お伝えしないこと
• CloudFormation以外のサービス(例: AWS Cloud Development Kit、AWS Serverless
Application Model)に関する概要、詳細
公開されているBlack Beltの資料、動画をご覧ください
• CloudFormationのテンプレートの作成方法 (例: !Ref、!Sub等)
公開後の本資料、またはHands-on for Beginnersの動画をご活用ください
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
全体の流れ
CloudFormationの
概要、始め方
開発 テスト
デプロイ運用
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.© 2020, Amazon Web Services, Inc. or its Affiliates.
概要、始め方
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
概要、始め方
1. CloudFormationの概要
2. 始め方
3. テンプレート、スタック
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
AWS環境における構成管理方法
AWS Command
Line Interface
AWS
ミドルウェア
Amazon EC2
Amazon Simple Storage
Service (S3)
Amazon RDS
Amazon VPC
手段 管理対象
アプリケーション
自作スクリプト、AWS OpsWorks、
Chef、Ansible …
AWS
CloudFormation
自作スクリプト、AWS CodeBuild、
Elastic Beanstalk…
ミドルウェア、
ミドルウェア設定…
アプリケーション、
アプリケーション設定…
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
AWS CloudFormation
EC2 や ELB といった AWS リソースの環境構築を、設定ファイル (テンプ
レート) を元に自動化できるサービス。テンプレートを自由に作成できるため、
自分好みのシステム構成を自動的に構築できる。テンプレートには起動すべき
リソースの情報を JSON や YAML フォーマットのテキスト形式で記述する。
追加料金はない。(プロビジョニングされたAWSリソース分の料金のみ発生)
作成/変更/削除
作成するリソースの定義 リソースの集合
リソースの
作成/変更/削除
Template Stack
Amazon
RDS
Amazon
EC2
VPC
CloudFormation
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
CloudFormation 基本機能
作成
テンプレートに定義された構成でスタックを自動作成
並列でリソースを作成し依存関係がある場合は自動的に解決
変更
スタックに前回のテンプレートとの差分を適用(冪等性)
リソース変更時は 無停止変更 / 再起動 / 再作成 のいずれかが発生
Change Set を作ることで差分の内容を事前に確認可能
削除
依存関係を解決しつつリソースを全て削除
データストアはスナップショット取得 / 保持が可能
注意: 手動で行った変更はCloudFormation管理外
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
始め方
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
YAML/JSONで
記述
アップロード リソースの
作成と管理
CloudFormation を使った構成管理の流れ
スタックの作成
ローカルファイルを
マネジメントコンソールや
S3バケット、パイプ
ライン経由でアップロード
マネジメントコンソール、
AWS CLI、AWS SDK、
スタックセットを利用して
スタックを作成する
AWS SAMやAWS CDK、
サンプルテンプレートの
利用も可。
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
YAML/JSONで記述
リファレンスを参考に、エディタにて以下のようなテンプレートを記述。
AWSTemplateFormatVersion: 2010-09-09
Description: Hands-on template for EC2
Parameters:
VPCStack:
Type: String
Default: handson-cfn
〜省略〜
Resources:
EC2WebServer01:
Type: AWS::EC2::Instance
Properties:
ImageId: !Ref EC2AMI
〜省略〜
Outputs:
EC2WebServer01:
Value: !Ref EC2WebServer01
Export:
Name: !Sub ${AWS::StackName}-
EC2WebServer01
• Parameters
スタック構築時にユーザーに
指定させる値を指定
• Resources
必須項目であり、起動するリ
ソースのタイプやプロパティ
を指定
• Outputs
スタック構築後に表示・取得
した値や他スタックとの連携
のための出力を指定
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
アップロード
AWSのマネジメントコンソールにて、前述のテンプレートをアップロード。
ファイルを選択してアップロードも可能。
既にS3にアップロードされている場合はそちらを選択することも可能。
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
スタックの作成
必要に応じてIAMリソースが作成されることを承認して、スタックを作成。
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
リソースの作成と管理
実際にCloudFormationスタックができると、以下のスクリーンショットの通
りリソースタブで確認できる。テンプレートを更新する際は、再度ファイルを
アップロードして更新する流れとなる。
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
(参考) 既存リソースをインポートして始める方法
AWS公式のツールではないが、Former2を利用することで、既存のAWSリソースを
CloudFormationテンプレート化できる。そのテンプレートを活かし、リソースをインポー
トすることでCloudFormationで扱えるようになる。
https://github.com/iann0036/former2
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
YAML/JSONで
記述
アップロード リソースの
作成と管理
CloudFormation を使った構成管理の流れ
スタックの作成
ローカルファイルをブラウ
ザのコンソールやS3バ
ケット、パイプライン経由
でアップロード
コンソール、CLI、
AWS SDK、ス
タックセットを利
用してスタックを
作成する
SAMやCDK、サンプルテ
ンプレートの利用も可。
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
テンプレート、スタック
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
テンプレートとスタックの概要
作成/変更/削除
リソースの
作成/変更/削除
Template Stack
Amazon
RDS
Amazon
EC2
VPC
CloudFormation
JSON/YAML形式のテキスト
リソースの定義 AWSリソースの集合
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
テンプレート
作成/変更/削除
作成するリソースの定義 リソースの集合
リソースの
作成/変更/削除
Template Stack
Amazon
RDS
Amazon
EC2
VPC
CloudFormation
まずはテンプレートから
説明していきます
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
テンプレート
• AWS CloudFormationの心臓部
• スタックの設計図
• どのリソースを構築するか(状態)を記述
• リソースの依存関係は
AWS Cloudformationが自動判別
• JSON/YAMLフォーマットで記述
AWSTemplateFormatVersion: 2010-09-09
Description: Sample
Parameters:
KeyName:
Description: "Sample key"
Type: String
Mappings:
RegionMap:
ap-northeast-1:
"AMI": "ami-xxxxxxxxxx"
Resources:
Ec2Instance:
Type: "AWS::EC2::Instance"
Properties:
SubnetId: "subnet-xxxxxxxxxx"
SecurityGroupIds:
- "sg-xxxxxxxxxx"
KeyName: !Ref KeyName
ImageId: !FindInMap [
RegionMap,
!Ref "AWS::Region", AMI ]
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/template-guide.html
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
テンプレートの要素
AWSTemplateFormatVersion: "version date"
Description:
String
Metadata:
template metadata
Parameters:
set of parameters
Mappings:
set of mappings
Conditions:
set of conditions
Transform:
set of transforms
Resources:
set of resources
Outputs:
set of outputs
AWS CloudFormationテンプレートバージョン
テンプレートの説明文
実行時(スタック作成/更新)にユーザ入力を求めるパ
ラメータ(KeyPairの名前や、DBのユーザ名など)
キーと値のマッピング
条件パラメータ値の指定に使用
(必須パラメータ)Amazon EC2やAmazon RDSなど、
スタックを構成するリソースとプロパティ
スタック構築後にAWS CloudFormationから出力させ
る値(DNS名やEIPの値など)
条件名と条件判断内容
Resourcesセクションなどでリソース作成時に利用
サーバーレスアプリケーションや定型コンテンツ
挿入等のための、マクロを指定
テンプレートに関する追加情報
利用頻度の高い要素
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Format version and Description
AWSTemplateFormatVersion
現状「2010-09-09」が唯一有効な値
Description
テンプレートに関する説明文
AWSTemplateFormatVersion: 2010-09-09
Description: some details about the template.
AWS Serverless Application Model(SAM)を利用する
際は、別の定義が必要です(後述)
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/format-version-structure.html
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/template-description-structure.html
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Metadata
• テンプレートに関する追加情報を提供するオブジェクト
• 例: Instancesリソースの説明文をMetadataに記述
Resources:
MyInstance:
Type: "AWS::EC2::Instance”
Metadata:
MyInstance:
Description: "Information about the
instance"
Database:
Description: "Information about the
database"
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/metadata-section-structure.html
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Metadata Key
• 一部の機能では、Metadataセクションで定義した設定または設定情報を取得可能
• 例)AWS::CloudFormation::Interface → パラメーターをグループ化およびソート
する方法を定義するMetadata Key
• マネジメントコンソールの画面上でパラメータをわかりやすく表示するための機能
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
- Label:
default: "Network
Configuration"
Parameters:
- VPCID
- ApplicationSubnetId
- Label:
default: "EC2
Configuration"
Parameters:
- KeyNamehttps://docs.aws.amazon.com/ja_jp/A
WSCloudFormation/latest/UserGuide/
metadata-section-structure.html
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Parameters
• スタック構築時にユーザに指定させる値を定義
• データ型、デフォルト値、最大最小値などのプロパティを設定可能
Parameters:
VPCStack:
Type: String
Default: handson-cfn
DBUser:
Type: String
Default: dbmaster
DBPassword:
Type: String
Default: H&ppyHands0n
MinLength: 8
NoEcho: true
パラメータごとのプロパティ
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Parametersの主なプロパティ
プロパティ 内容
Type
データ型
String,Number,List<Number>,CommaDelimitedList,AWS固有のパラメータ,SSMパラメー
タタイプ
Default デフォルト値
NoEcho 入力時に*****となる(パスワードなどに使用)
AllowedValues 入力可能値の一覧指定 (例:[“true”,”false”] )
AllowedPattern 正規表現で入力可能パターンを指定(例:[a-zA-Z]*)
MaxLength 最大文字数
MinLength 最小文字数
MaxValue 最大値
MinValue 最小値
Description プロパティの詳細説明
ConstraintDescription
入力した値がAllowedPatternやMaxLengthなどの制約に引っかかった時に表示する説明
(どのような制約があるかの説明を記述)
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/parameters-section-structure.html
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Mappings
• キーと値のマッピングテーブルを管理できる
• リージョンやユーザ入力パラメータによって、値が変わるものに利
用
• Mappingsを利用することでテンプレートの再利用性が向上
Mappings:
RegionMap:
us-east-1:
"AMI": "ami-xxxxxxxxxx"
"KEYPAIR": "myKey-east"
us-west-1:
"AMI": "ami-yyyyyyyyyy"
"KEYPAIR": "myKey-west”
ap-northeast-1:
"AMI": "ami-zzzzzzzzzz"
"KEYPAIR": "myKey-
tokyo"
Mappingsにテーブルの定義を行う
(この例の場合、”RegionMap”という
名称でMappingを定義)
Regionが”ap-northeast-1”であれば、
AMI IDは”ami-zzzzzzzzzz”、キーペア
名は”myKey-tokyo”とする
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/mappings-section-structure.html
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Mappingsの使い方
• Functionの”Find::InMap”を使って値を取得
例)"Fn::FindInMap" : [ "MapName", "Key", "Value"]
• 引数のMapName,Key,Valueには”!Ref”が利用可能
Mappings:
RegionMap:
us-east-1:
"AMI": "ami-xxxxxxxxxx"
us-west-1:
"AMI": "ami-yyyyyyyyyy"
ap-northeast-1:
"AMI": "ami-zzzzzzzzzz"
Resources:
Ec2Instance:
Type: "AWS::EC2::Instance"
Properties:
ImageId: !FindInMap [ RegionMap, !Ref "AWS::Region", AMI ]
リージョンに合致するAMIの値を取得する
リージョンが”ap-northeast-1”の場合、最終
的な戻り値は”ami-zzzzzzzzzz”となる
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/mappings-section-structure.html
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Conditions
• 条件名と成立条件を列挙
• Resourcesセクションなどで、『ある条件が成立しているときのみリソースを起動』といった条
件ベースの制御が可能
• 本番環境と検証環境で構成が異なる場合に便利
• Conditionsを多く使用すると、テンプレートの可読性が下がるため注意
Parameters:
EnvType:
Description: "Environment type."
Default: "development"
Type: String
AllowedValues: ["production", "staging", "development"]
ConstraintDescription: "must specify."
Conditions:
CreateProdResources: {"Fn::Equals" : [{"Ref" : "EnvType"}, “production"]}
Resources:
Ec2Instance:
Type: "AWS::EC2::Instance"
Condition: "CreateProdResources"
EnvTypeパラメータ値
が”production”であれば、
CreateProdResources条件が成立
CreateProdResources条件が成立した
場合、EC2リソースを作成
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/conditions-section-structure.html
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Transform
テンプレートの処理に使用する一つ以上のマクロを指定
AWS::Serverless
サーバーレスアプリケーションの場合に、使用するAWS SAMのバージョンを指定
AWS::Include
メインのテンプレートとは別に保存されたテンプレートスニペットを使用
Macros
作成したMacros ※1を使用
Transform: AWS::Serverless-2016-10-31
Resources:
MyServerlessFunctionLogicalID:
Transform:
Name: 'AWS::Include'
Parameters:
Location:
's3://MyAmazonS3BucketName/MyFileName.yaml'
Transform: [EchoMacro]
Resources:
FancyTable:
※1 https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/template-macros.html
Transform https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/transform-section-structure.html
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Resources (必須)
• EC2やELB、 RDSなど、作成するリソースを指定
• リソースごとに決められたプロパティを設定
• 利用可能なリソースタイプはリファレンスを参照
Resources:
EC2WebServer01:
Type: AWS::EC2::Instance
Properties:
ImageId: !Ref EC2AMI
InstanceType: t2.micro
SubnetId:
Fn::ImportValue: !Sub ${VPCStack}-
PublicSubnet1
リソースタイプ
リソースごとの
プロパティ
(参考)公式ドキュメントのテンプレートリファレンスとリリース履歴
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/aws-template-resource-type-ref.html
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/ReleaseHistory.html
論理ID
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Outputs
• スタック構築後に取得・表示したい情報の定義
• アクセスURLや、DBの通信先情報、作成したIAMユーザー名など、あとで
使用したい情報がある場合に便利
Resources:
EC2WebServer01:
Type: AWS::EC2::Instance
Properties:
ImageId: !Ref EC2AMI
InstanceType: t2.micro
Outputs:
EC2WebServer01:
Value: !Ref EC2WebServer01
Export:
Name: !Sub ${AWS::StackName}-EC2WebServer01
出力データの名称
出力する値
組み込み関数を
使って文字列を加工
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/outputs-section-structure.html
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
論理IDと物理ID
論理ID
テンプレート内で一意
テンプレートの他の部分のリソースを参照するために使用
!Refや!GetAttで使用
物理ID
リソースに実際に割り当てられている名前(EC2のインスタンスID、S3バケット名など)
AWS CloudFormationテンプレート外のリソースを識別する場合に使用
Resources:
MyEC2Instance:
Type: "AWS::EC2::Instance”
Properties:
SubnetId: "subnet-xxxxxxxxxxxxxxxx"
Outputs:
MyEC2PhysicalID:
Value: !Ref MyEC2Instance
論理ID
物理ID
“!Ref 論理ID”で、
物理IDを取得
物理ID
(EC2のインスタンスID)
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/resources-section-structure.html
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Ref
Fn::Sub
Fn::GetAtt
Fn::Base64
Fn::Cidr
Fn::FindInMap
Fn::GetAZs
Fn::ImportValue
Fn::Join
Fn::Select
Fn::Split
Fn::Transform
Fn::And
Fn::Equals
Fn::If
Fn::Not
Fn::Or
AWS::AccountId
AWS::NotificationARNs
AWS::NoValue
AWS::Partition
AWS::Region
AWS::StackId
AWS::StackName
AWS::URLSuffix
組み込み関数 疑似パラメータ
Function、疑似パラメータ
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
組み込み関数
• パラメータの参照や値の加工などに利用する関数
• 記法は完全名の「Fn::xxx」と短縮形の「!xxx」の2つ
• 主な組み込み関数
• 値を参照する !Ref, !GetAtt
• 文字列を結合する !Join
• AZを取得する !GetAZs
• エクスポート値取得 Fn::ImportValue
• Base64エンコード Fn::Base64
• 条件関数 Fn::If, Fn::Equals, Fn::Not
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference.html
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
!Ref, !Sub, !GetAttの使い分け
!Ref
テンプレート内の論理名から物理名(ID)を参照する
!Sub
本来は文字列内の変数を指定した値で置き換える関数。
${xxx}で指定した変数(パラメータ、論理名、属性)の展開を行う用途でもよく使われる
!GetAtt
リソースが持つ属性値を取得する
Resources:
Ec2Instance:
Type: "AWS::EC2::Instance"
Properties:
ImageId: !FindInMap [ RegionMap, !Ref
"AWS::Region", AMI ]
Tags:
- Key: Name
Value: !Sub ${AWS::StackName}-WebServer01
…
Outputs:
EC2WebServer01DNS:
Value: !GetAtt EC2WebServer01.PublicDnsName
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-ref.html
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-sub.html
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-getatt.html
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
擬似パラメータ(Pseudo Parameters)
• あらかじめ定義された擬似パラメータ群で“!Ref”により参照可能
• 利用可能な主なパラメータ
• AWS::Region → リージョン名を取得
• AWS::StackId → スタックIDを取得
• AWS::StackName → スタック名を取得
• AWS::AccountId → AWSアカウントIDを取得
• AWS::NoValue → 指定されたプロパティを無視するようAWS
CloudFormationに伝える
Resources:
Ec2Instance:
Type: "AWS::EC2::Instance"
Properties:
KeyName: !Ref "AWS::StackName"
Tags:
-
Key: region
Value: !Ref “AWS::Region”
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/pseudo-parameter-reference.html
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
テンプレートの要素を手を動かしながら学びたい方はこちら
本日ご紹介しないテンプレートの書き方を紹介しております。
10分動画 × 8本のハンズオンコンテンツとなっています。是非ご活用ください。
https://pages.awscloud.com/JAPAN-event-OE-Hands-on-for-Beginners-cfn-2020-reg-event-LP.html
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
スタック
作成/変更/削除
作成するリソースの定義 リソースの集合
リソースの
作成/変更/削除
Template Stack
Amazon
RDS
Amazon
EC2
VPC
CloudFormation
次にスタックを
説明していきます
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
スタック
単一のユニットとして管理できる AWS リソースのコレクション
スタック単位でリソースの管理が可能
スタックの削除を実行すると、スタックにひもづくリソースが削除される
使用するリソースおよびリソースの構築順は、テンプレートの依存関係から
CloudFormationが自動的に決定
Stack これらを一度に作成/変更/削除が可能
S3 DB Web App Hosted Zone
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
テンプレート、スタックのまとめ
以下のことをお伝えしました
作成/変更/削除
リソースの
作成/変更/削除
Template Stack
Amazon
RDS
Amazon
EC2
VPC
CloudFormation
• JSON/YAML形式のテキスト
• リソースの定義
• テンプレートの要素として、
Resources、Outputs等の定義を
していく必要がある
AWSリソースの集合
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
全体の流れ
CloudFormationの
概要、始め方
開発 テスト
デプロイ運用
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.© 2020, Amazon Web Services, Inc. or its Affiliates.
開発
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
開発
エディタ Lintツール 自動補完
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
エディタ
自動補完が効くツールを使うと効率が良くなります
• Visual Studio Code
• Sublime Text
• Atom
• Cloud9
• IntelliJ
• PyCharm
• Others
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
cfn-lint
入力した値の整合性チェックをできるコマンドラインツール。以下の画像は、
エディタにプラグインを適用して利用した例。
• Atom, Visual Studio Code, Sublime,
Vim用のプラグインあり
• 複数ファイルの一括処理
• conditions/Fn::If の対応
• SAMとのインテグレーション
• GitHubからすぐに利用可能
https://github.com/aws-cloudformation/cfn-python-lint
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
自動補完
CloudFormation template schemaを利用することで、開発効率を向上できる
https://github.com/aws-cloudformation/aws-cloudformation-template-schema
• Visual Studio Code/PyCharm
で利用可能
• リソースタイプと必須プロパ
ティのリストの自動補完
• YAMLとJSONテンプレートの
両方をサポート
• 必須でないプロパティも必要
に応じて自動補完
• リソースタイプドキュメント
へのリンク
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
開発のまとめ
エディタ Lintツール 自動補完
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
全体の流れ
CloudFormationの
概要、始め方
開発 テスト
デプロイ運用
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.© 2020, Amazon Web Services, Inc. or its Affiliates.
テスト
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
テスト
型定義等の厳密なチェック
独自に定義したポリシーへの
適合性をチェック
セキュリティチェック
マルチリージョン/
アカウントのテスト
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
cfn-lintによる厳密なチェック
定義が書いてあるものの使われていないもの、型の違いに対して警告を出す。
パイプラインで実行し、チェックで引っかかったら次のタスクを実行しない。
Pull Request やオープンソース開発スタイルで効果的。
https://github.com/awslabs/cfn-python-lint
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
TaskCatによるマルチリージョン/アカウントテスト
AWS QuickStart チームが開発したオープンソースプロジェクトで、複数の AWS リー
ジョンで並列にテンプレートからスタックを作成してテスト可能。1つのテンプレート
やスタックをテストしたのではわからない問題を検知できる。各リージョンでの 成功/
失敗 のレポートを生成でき、AWS CloudFormation StackSetsを利用する際に効果的。
https://github.com/aws-quickstart/taskcat
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
cfn-nagによるセキュリティチェック
サードパーティのOSS。潜在的なセキュリティの問題を開発プロセスの初期段
階で気づくことができる。
https://github.com/stelligent/cfn_nag
$ cfn_nag_scan --input-path ./security-
groups.yaml
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
CloudFormation Guard (2020/08現在 Preview)
CloudFormationテンプレート検証を行うためのツールセット
https://github.com/aws-cloudformation/cloudformation-guard
• ルールを記述して対象リソースが満たすべき条件
を指定
• cfn-guard-rulegenコマンドで既存テンプレート
からルールのひな形生成
• cfn-guardコマンドでチェック
• Lambdaで実行できるライブラリも提供
(パイプラインに組込みやすい)
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
テストのまとめ
型定義等の厳密なチェック
独自に定義したポリシーへの
適合性をチェック
セキュリティチェック
マルチリージョン/
アカウントのテスト
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
全体の流れ
CloudFormationの
概要、始め方
開発 テスト
デプロイ運用
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.© 2020, Amazon Web Services, Inc. or its Affiliates.
デプロイ
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
デプロイ
アカウント 1
Stack
アカウント 2
Stack
管理者アカウント
AWS Region - A AWS Region - B
Template
アカウント 1
Stack
アカウント 2
Stack
3. StackSets (マルチリージョン/マルチアカウント)
1. AWS CodePipeline を利用したデプロイ
2. Change Setで 変更内容を事前確認した上でのデプロイ
StackSets
Change setStack Change set Stack
実行確認変更
AWS
CodePipeline
CloudFormation
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
CodePipeline でデプロイ
• 自動化
• 安全
• 繰り返し可能
• デプロイリソースへの手動アクセス阻止
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Change Set で変更内容を事前確認
変更を要求した箇所とその変更により影響を受ける箇所を事前に確認可能。変更によっ
てリソースが中断されたり置き換え (再作成) されたりすることがあることに注意。リ
ソースの更新動作の詳細は、スライド下のURLを参照すること。
変更セットを利用したスタックの更新: https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-changesets.html
スタックのリソースの更新動作: https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/using-cfn-updating-stacks-update-behaviors.html
影響するリソース
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
一回の操作で複数のアカウントやリージョンへスタックを作成、更新、削除
できるCloudFormationの機能。
StackSets
アカウント 1
Stack
管理者アカウント AWS Region - A
Template StackSet
• スタックインスタンスの細かな
アクセス制御
• 多数のリソースを管理可能
(標準で2000スタックインスタ
ンス/1スタックセット)
• Organization Unit(OU) に
作成した新規アカウントへ
自動的にデプロイ
• OUとの信頼関係を自動的に管理
アカウント 2
Stack
アカウント 3
Stack
アカウント 1
Stack
AWS Region - B
アカウント 2
Stack
アカウント 3
Stack
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/what-is-cfnstacksets.html
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/cloudformation-limits.html
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
デプロイのまとめ
アカウント 1
Stack
アカウント 2
Stack
管理者アカウント
AWS Region - A AWS Region - B
Template
アカウント 1
Stack
アカウント 2
Stack
3. StackSets (マルチリージョン/マルチアカウント)
1. AWS CodePipeline を利用したデプロイ
2. Change Setで 変更内容を事前確認した上でのデプロイ
StackSets
Change setStack Change set Stack
実行確認変更
AWS
CodePipeline
CloudFormation
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
全体の流れ
CloudFormationの
概要、始め方
開発 テスト
デプロイ運用
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.© 2020, Amazon Web Services, Inc. or its Affiliates.
運用
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
運用
• スタックの更新
• スタックとリソースの保護
• ライフサイクル別のテンプレート管理
• 既存スタックのリファクタリング
• ヘルパースクリプト
• Dynamic Reference
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
運用
• スタックの更新
• スタックとリソースの保護
• ライフサイクル別のテンプレート管理
• 既存スタックのリファクタリング
• ヘルパースクリプト
• Dynamic Reference
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
スタックの更新
ドリフト検出 即時実行
現行スタック
ドリフトの確認
差分を
テンプレートに反映
テンプレート更新
直接更新 変更セット
スタック更新
ドリフトなし
変更点を
確認後実行
イテレーション
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
ドリフトの確認
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
直接更新と変更セット(Change Set)
現状のスタックとの変更点を
確認して更新する場合(変更セット)
現状のスタックを直接更新する場合
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
運用
• スタックの更新
• スタックとリソースの保護
• ライフサイクル別のテンプレート管理
• 既存スタックのリファクタリング
• ヘルパースクリプト
• Dynamic Reference
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
スタックやリソースが誤って変更/削除されないように保護するための機
能。複数のレイヤで保護機能を提供。
スタックとリソースの保護
作成/変更/削除
作成するリソースの定義 リソースの集合
リソースの
作成/変更/削
除
Template Stack
Amazon
RDS
Amazon
EC2
VPC
CloudFormation
リソースの
DeletionPolicy属性
ユーザーの
IAMポリシー
スタックの削除保護、
スタックポリシー
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• スタックが誤って削除されるのを防ぐ
• スタックの削除保護を有効または無効にすると、そのスタックに属するネストされ
たすべてのスタックにも設定される
スタックの削除保護
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• スタックの更新中にスタックのリソースが意図せずに変更/削除されるのを防ぐ
• 指定したリソースに対して実行できるアクションを定義するJSONドキュメント
スタックポリシー
テンプレート
stack-policy.json
ポリシーファイル
リソース
保護リソース
非保護リソース
Template
DB Instance
Instance Instance
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• 例)RDSリソースに対する変更を禁止するポリシー
スタックポリシー
{
"Statement" : [
{
"Effect" : "Deny",
"Action" : "Update:*",
"Principal": "*",
"Resource" : "*",
"Condition" : {
"StringEquals" : {
"ResourceType" : ["AWS::RDS::DBInstance"]
}
}
},
{
"Effect" : "Allow",
"Action" : "Update:*",
"Principal": "*",
"Resource" : "*"
}
]
}
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
リソースのDeletionPolicy属性
• スタックが削除された際にリソースを保持またはバックアップ
• 例: スタックが削除されてもS3バケットを保持
AWSTemplateFormatVersion: '2010-09-09'
Resources:
myS3Bucket:
Type: AWS::S3::Bucket
DeletionPolicy: Retain
DeletionPolicyオプション スタック削除時のリソースの挙動
Delete 削除
Retain 保持
Snapshot
スナップショットを取得
対応リソース
AWS::EC2::Volume
AWS::ElastiCache::CacheCluster
AWS::ElastiCache::ReplicationGroup
AWS::RDS::DBInstance
AWS::RDS::DBCluster
AWS::Redshift::Cluster
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
運用
• スタックの更新
• スタックとリソースの保護
• ライフサイクル別のテンプレート管理
• 既存スタックのリファクタリング
• ヘルパースクリプト
• Dynamic Reference
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
ライフサイクル別のスタック
インスタンス、Auto Scalingグループ
API エンドポイント, Lambda関数
アラーム、ダッシュボード
VPC, NATゲートウェイ, VPN, サブネット
IAM ユーザー、グループ、ルール、ポリシー
フロントエンド
のリソース
バックエンド
サービス
ステートフルな
リソース
ネットワーク
セキュリティ
開発 テスト ステージング 商用
1
2
スタックを
レイヤとライフサイクルで
分割する
スタックを環境ごとに
再利用する監視
リソース
データベース、クラスター、キュー
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
規模が大きくなると単一のテンプレートでの管理は手間と時間がかかり、変更時の影響範
囲も大きくなるため、スタックを分割
スタック分割
観点 意味
依存関係
VPC→セキュリティグループ+IAM→アプ
リケーションが基本
ライフサイクル
更新頻度と寿命
通常VPCやIAMなど依存される側のリ
ソースは更新頻度が少なく寿命が長い一
方、アプリケーションは高頻度更新で短
命であることが多い
ステートレス/ステートフル
ステートレスなリソースとステートフル
なリソースを分割
所有権 更新に責任を持てるチーム毎に分割
設計観点 実装
Cross Stack Reference
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
スタック分割 - インフラ全体
ネットワーク
IAM
Network Layer
Security Layer
Application Layer
アプリケーションリソース
セキュリティグループ
依存される側
依存する側
依
存
関
係
解説 含まれるリソース
• システムが直接利用するリソー
スを配置
• アプリケーションだけではなく、
共有サービス(例えばDirectory
等)も依存関係上このレイヤー
に含まれる
• EC2
• RDS
• ELB
• SQSキュー
• Active Directory
• CI/CDサーバ
• ネットワークリソースのうちセ
キュリティグループはネット
ワークの存在を前提とするため
このレイヤーに所属
• IAMは事実上依存性のないリ
ソースだが、分類上このレイ
ヤーに所属
• セキュリティグループ
• IAMロール
• IAMグループ
• IAMポリシー
• ネットワークリソースは最も依
存性が低いリソースであり、い
わば環境の「地面」に相当する
ため、外部のリソースの存在を
前提としない
・VPC
・サブネット
・エンドポイント
・ルートテーブル
・内部DNS(Route53)
・IGW, NAT GW, VGW
ラ
イ
フ
サ
イ
ク
ル
短命・高頻度
長寿・低頻度
アプリケーション
チーム
セキュリティ
チーム
ネット
チーム
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Shared Service
Data
Application
アプリケーションリソース
依存される側
依存する側
依
存
関
係
解説 含まれるリソース
• アプリケーションコードを直接
実行、またはリクエストをルー
ティングするものを配置
• このレイヤのリソースは内部に
状態、データを持たないリソー
スとして考える(ステートレ
ス)
• EC2
• ECS
• ELB
• AutoScaling
• API Gateway
• データベース、キャッシュ、
キューなどアプリケーションの
リソースのうちデータを内部に
持つリソースを配置(ステート
フル)
• S3
• RDS
• Redshift
• ElastiCache
• SQS
• EC2(データを保持す
るもの)
• アプリケーションから共通で利
用されるサービスを配置
• Active Directoryのような認証
サーバ、プロキシサーバー、
メールリレーサーバー、CI/CD
サーバなど
・Directory Service
・EC2(共通サービス)
・CodeX
・SES
・Route53
ラ
イ
フ
サ
イ
ク
ル
短命・高頻度
長寿・低頻度
アプリケーション
チーム
スタック分割 - アプリケーションレイヤ内部
データベース
チーム
共有サービス
チーム
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
スタック分割の例 – サンプルシステム
Security Group
IAM Role & Policy
Security Group
AP AP
Role
Bastion
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
スタック分割の例 – スタック構成
注:スタックの作成順はユーザによる管理が必要
CrossStack Reference
ALB
Public Subnet 1 Public Subnet 2
Private Subnet 1 Private Subnet 2
LB用
SG
AP用
SG
Basion用
SG
DB用
SG
Auto
Scaling
Group
AP
Basion
EIP
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
運用
• スタックの更新
• スタックとリソースの保護
• ライフサイクル別のテンプレート管理
• 既存スタックのリファクタリング
• ヘルパースクリプト
• Dynamic Reference
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
既存スタックのリファクタリング
リソースインポート/エクスポートを利用
Amazon DynamoDB
Amazon SQS
AWS Lambda
Amazon Route53
Amazon S3
Amazon API Gateway
Amazon DynamoDB
Amazon SQS
AWS Lambda
Amazon API Gateway
Amazon Route53
Amazon S3
Resource import
Imports/exports
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
CloudFormation リソースインポート
手動で作成したAWSリソースをCloudFormationスタックにインポートして管理可能。
リソースをスタックから切り離し、別のスタック管理下に移動することも可能。
テンプレートのリファクタリングに利用可能。
• インポートに対応しているのはDrift Detectionに対応したリソースのみ
• インポートに関する追加料金はなし
• Former2でテンプレート作成の省力化が可能
CFnテンプレート CFnスタック
管理対象リソース ②インポート対象リソースを
含むCFnテンプレートを用意
④対象リソースを含む
CFnスタックが作成
①手動でリソースを作成スタック作成
③チェンジセットを実行して
リソースをインポート
⑤(オプション)DriftDetection
を使って実環境とテンプレートの
詳細な差分を確認し修正する
(CFn=CloudFormation)
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/resource-import-existing-
stack.html
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
運用
• スタックの更新
• スタックとリソースの保護
• ライフサイクル別のテンプレート管理
• 既存スタックのリファクタリング
• ヘルパースクリプト
• Dynamic Reference
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
CloudFormationのヘルパースクリプト(1/2)
4つのスクリプトがAWS公式から提供されており、スタック内のEC2
インスタンスの構築、変更を行えるようにするもの。
• cfn-init
Amazon Linuxに入っている初期設定ツール。CloudFormationリソースの
メタデータ AWS::CloudFormation::Init セクションに記述した設定を取得
し、その記述どおりにEC2インスタンス内でパッケージのインストール等
を実施できるヘルパースクリプト。現時点ではAWS Systems Managerの
State Managerの利用を推奨。トラブルシューティングが容易になり、テ
ンプレートの中味がよりシンプルになる。
https://aws.amazon.com/jp/blogs/news/using-state-manager-over-cfn-init-in-cloudformation-and-its-benefits/
• cfn-get-metadata
CloudFormationリソースのメタデータ情報を取得するためのスクリプト。
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
CloudFormationのヘルパースクリプト(2/2)
• cfn-signal
EC2リソースが正常に作成、更新されたかをCloudFormationに送信するス
クリプト。CloudFormationのCreationPolicy、WaitCondition等の属性に対
してシグナルを送る。例えばリソースの作成開始から30秒以内にシグナ
ルが飛ばない場合にロールバックするような用途でcfn-signalが用いられ
る。
• cfn-hup
CloudFormationで作成されたリソースのメタデータの変更を検知し、変
更が検出されたときにカスタムフックを実行するために使用するデーモン。
EC2の再起動をせずに、CloudFormationの変更時にアプリケーションに設
定を適用したいような用途で使う。
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
• AWS Systems ManagerのパラメータストアとAWS Secrets Managerに格納された
データを動的に参照
Dynamic References
参照
(DB接続情報など)
サービス 参照可能なデータ
AWS Systems
Manager
• パラメータストアに格納されているString/StringList(平文で保存されているデータ)
• パラメータストアに格納されているSecureString(暗号化されて保存されているデータ)
AWS Secrets
Manager
保存されているすべてのシークレットまたは特定のシークレット
AWS Systems
Manager
AWS Secrets
Manager
Parameter
store
Template
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/dynamic-references.html
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/best-practices.html
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
運用のまとめ
• スタックの更新
• スタックとリソースの保護
• ライフサイクル別のテンプレート管理
• 既存スタックのリファクタリング
• ヘルパースクリプト
• Dynamic Reference
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.© 2020, Amazon Web Services, Inc. or its Affiliates.
まとめ、Next Action
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
本日は以下のことをお伝えしました
CloudFormationの
概要、始め方
開発 テスト
デプロイ運用
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Public coverage roadmap
CloudFormationに関してのフィードバックがございましたら、是非こちらへ
Issue登録や+1をお願いいたします。
© 2020, Amazon Web Services, Inc. or its Affiliates. All rights reserved.
Next Action
• 本資料を復習し、今使用しているCloudFormationテンプレートを改善する
• 紹介されたツールを導入する
• インフラ自動化に挑戦してみる
• CloudFormationで触れたAWSのサービスの理解を深める
• Hands-on for Beginnersを実施する
• AWS CDKを学び、プログラミング言語で構成管理をする
https://pages.awscloud.com/JAPAN-event-OE-Hands-on-for-
Beginners-cfn-2020-reg-event-LP.html
https://aws.amazon.com/jp/blogs/news/webinar-bb-aws-
cloud-development-kit-cdk-2020/