LoginSignup
0
0

More than 1 year has passed since last update.

CloudFormationテンプレート小ネタサンプル集

Posted at

パラメータのグルーピング・順番固定

パラメータ定義だけだと、入力項目がアルファベット順にソートされる。
固定したい場合はAWS::CloudFormation::Interfaceを利用する。

Parameters:
  PJPrefix:
    Type: String
  Environment:
    Type: String
  VPCCidr:
    Type: String
Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - Label:
          default: General
        Parameters:
          - PJPrefix
          - Environment
      - Label:
          default: Network
        Parameters:
          - VPCCidr

環境別定義

構築時に環境に合わせたパラメータを沢山入れるのが面倒!って場合。

Parameters:
  Environment:
    Type: String
    AllowedValues:
      - production
      - staging
      - develop
Mappings:
  EnvironmentMapping:
    production:
      VPCCidr: 10.0.0.0/16
      InstanceType: t3.small
    staging:
      VPCCidr: 10.1.0.0/16
      InstanceType: t3.small
    develop:
      VPCCidr: 10.2.0.0/16
      InstanceType: t3.micro
Resources:
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: !FindInMap [EnvironmentMapping, !Ref Environment, VPCCidr]

テンプレートファイル分割時の連携

OutputsでExportした値は、Fn::ImportValue を使って別テンプレートから呼び出せる。

vpc.yaml
Parameters:
  PJPrefix:
    Type: String
  Environment:
    Type: String
  VPCCidr:
    Type: String
Resources:
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: !Ref VPCCidr
Outputs:
  VPCID:
    Value: !Ref VPC
    Export:
      Name: !Sub "${PJPrefix}-${Environment}-VpcId"
subnet.yaml
Parameters:
  PJPrefix:
    Type: String
  Environment:
    Type: String
  SubnetAZ:
    Type: String
  SubnetCidr:
    Type: String
Resources:
  Subnet:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId:
        Fn::ImportValue:
          !Sub "${PJPrefix}-${Environment}-VpcId"
      CidrBlock: !Ref SubnetCidr
      AvailabilityZone: !Ref SubnetAZ

未入力パラメータの処理分岐

Conditionsに条件を定義し、Fn::Ifで処理分岐させる。
ある条件で未定義にしたい場合は、!Ref AWS::NoValue を設定する。

Parameters:
  MailAddress1:
    Type: String
  MailAddress2:
    Type: String
Conditions:
  ExistMailAddress1:
    Fn::Not: [!Equals [!Ref MailAddress1, '']]
  ExistMailAddress2:
    Fn::Not: [!Equals [!Ref MailAddress2, '']]
Resources:
  Topic:
    Type: AWS::SNS::Topic
    Properties:
      Subscription:
        - Fn::If:
          - ExistMailAddress1
          - Endpoint: !Ref MailAddress1
            Protocol: email
          - !Ref AWS::NoValue
        - Fn::If:
          - ExistMailAddress2
          - Endpoint: !Ref MailAddress2
            Protocol: email
          - !Ref AWS::NoValue
0
0
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
0