AWS CloudFormationでEC2AutoScalingを作成してみました(CLI)

前提

・AWS CLIがインストールされて、初期設定が完了できていること
・実行OS: Winows
・EC2Autoscaling作成用のAMIが作成されていること
・ALBが作成されていること
※ALBの作成方法を以前に書きました下記の記事を参考
AWS CloudFormationでALBを作成してみました(CLI)

テンプレート

パラメーターを設定して再利用可能なテンプレートを作成します。
ファイル名:EC2Autoscaling-Template.yaml

AWSTemplateFormatVersion: '2010-09-09'
Description: 'EC2 AutoscalingGroup'
Parameters:
# Environment Parameters
  Environment:
    Type: String
    Description: "Environment"

# AutoscalingGroup Parameters
  AutoScalingGroupName:
    Type: String
    Description: "AutoScalingGroupName"
  MinSize:
    Type: String
    Description: "Minimum Size of AutoscalingGroup"
  MaxSize:
    Type: String
    Description: "MaxSize Size of AutoscalingGroup"
  DesiredCapacity:
    Type: String
    Description: "Desired Capacity.The desired capacity must be less than or equal to the maximum size of the group."
  HealthCheckGracePeriod:
    Type: String
    Description: "The amount of time, in seconds, that Amazon EC2 Auto Scaling waits before checking the health status of an EC2 instance that has come into service."
  VPCZoneIdentifier:
    Type: CommaDelimitedList
    Description: "Set Subnet Id separated by commas"
  TargetGroupARNs:
    Type: CommaDelimitedList
    Description: "Set TargetGroupARNs separated by commas"
  HealthCheckType:
    Type: String
    Description: "HealthCheckType. EC2 | ELB"

# SecurityGroup Condition Parameters
  VpcId:
    Type: String
    Description: "VpcId"
  SecurityGroupName:
    Type: String
    Description: "SecurityGroupName"
  SecurityGroupDescription:
    Type: String
    Description: "SecurityGroupDescription"    
  SecurityGroupIdForALB:
    Type: String
    Description: "SecurityGroupIdForALB"

# ScalingPolicy Condition Parameters
  UseScalingPolicy:
    Type: String
    Description: "Enable UseScalingPolicy. true | false"

# UseScalingPolicy Parameters
  PolicyType:
    Type: String
    Description: "PolicyType. TargetTrackingScaling | SetpScaling | SimpleScaling"
  PredefinedMetricType:
    Type: String
    Description: "PredefinedMetricType. ALBRequestCountPerTarget | ASGAverageCPUUtilization | ASGAverageNetworkIn | ASGAverageNetworkOut"
  TargetValue:
    Type: String
    Description: "Metrics TargetValue"

# LaunchTemplate Parameters
  LaunchTemplateName:
    Type: String
    Description: "LaunchTemplateName"
  EC2Name:
    Type: String
    Description: "EC2Name"
  ImageId:
    Type: String
    Description: "AMI ID"
  InstanceType:
    Type: String
    Description: "InstanceType"
  KeyName:
    Type: String
    Description: "KeypairName"
  IamInstanceProfile:
    Type: String
    Description: "Set the exported insatnce profile name"
  UserData:
    Type: String
    Description: "UserData"
Conditions:
# ScalingPolicy Conditions
  SetScalingPolicy:
    !Equals [!Ref UseScalingPolicy, "true"]

Resources:
# AutoScalingGroup
  AutoScalingGroup:
    Type: AWS::AutoScaling::AutoScalingGroup
    Properties:
      AutoScalingGroupName: !Ref AutoScalingGroupName
      MinSize: !Ref MinSize
      MaxSize: !Ref MaxSize
      DesiredCapacity: !Ref DesiredCapacity
      HealthCheckGracePeriod: !Ref HealthCheckGracePeriod
      LaunchTemplate:
        LaunchTemplateId: !Ref LaunchTemplate
        Version: !GetAtt LaunchTemplate.LatestVersionNumber
      VPCZoneIdentifier: !Ref VPCZoneIdentifier
      TargetGroupARNs: !Ref TargetGroupARNs
      HealthCheckType:  !Ref HealthCheckType
      Tags:
        - Key: Name
          Value: !Ref AutoScalingGroupName
          PropagateAtLaunch: false
        - Key: Env
          Value: !Ref Environment
          PropagateAtLaunch: false

# ScalingPolicy
  ScalingPolicy:
    Type: AWS::AutoScaling::ScalingPolicy
    Condition: SetScalingPolicy
    Properties:
      PolicyType: !Ref PolicyType
      AutoScalingGroupName: !Ref AutoScalingGroup
      TargetTrackingConfiguration:
        PredefinedMetricSpecification:
          PredefinedMetricType: !Ref PredefinedMetricType
        TargetValue: !Ref TargetValue
        DisableScaleIn: false
#      EstimatedInstanceWarmup: 300  

# LaunchTemplate
  LaunchTemplate:
    Type: AWS::EC2::LaunchTemplate
    Properties:
      LaunchTemplateName: !Ref LaunchTemplateName
      LaunchTemplateData:
        ImageId: !Ref ImageId
        InstanceType: !Ref InstanceType
        KeyName: !Ref KeyName
        SecurityGroupIds: [!Ref SecurityGroup]
        Monitoring:
          Enabled: true
        IamInstanceProfile:
          Name:
            !Ref IamInstanceProfile
        TagSpecifications:
          - ResourceType: instance
            Tags:
              - Key: Name
                Value: !Ref EC2Name
              - Key: Env
                Value: !Ref Environment
              - Key: LaunchTemplateName
                Value: !Ref LaunchTemplateName
          - ResourceType: volume
            Tags:
              - Key: Name
                Value: !Ref EC2Name
              - Key: Env
                Value: !Ref Environment
              - Key: LaunchTemplateName
                Value: !Ref LaunchTemplateName
# SecurityGroup
  SecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: !Ref SecurityGroupName
      GroupDescription: !Ref SecurityGroupDescription
      VpcId: !Ref VpcId
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          SourceSecurityGroupId: !Ref SecurityGroupIdForALB
          Description: HTTP from ALB

      Tags:
      - Key: Name
        Value: cpi-dev-tyo-sg-web
      - Key: Env
        Value: cpi-dev

パラメーター(Inputファイル)

ファイル名:cpi-dev-ec2autoscaling-web.yaml

StackName: 'cpi-dev-ec2autoscaling-web'
Parameters:
- ParameterKey: 'Environment'
  ParameterValue: 'cpi-dev'
- ParameterKey: 'AutoScalingGroupName'
  ParameterValue: 'cpi-dev-ec2autoscaling-web'
- ParameterKey: 'MinSize'
  ParameterValue: '1'
- ParameterKey: 'MaxSize'
  ParameterValue: '2'
- ParameterKey: 'DesiredCapacity'
  ParameterValue: '1'
- ParameterKey: 'HealthCheckGracePeriod'
  ParameterValue: '300'
- ParameterKey: 'VPCZoneIdentifier'
  ParameterValue: 'subnet-0ad5e179c1769a532,subnet-01921a93ba3299d92'
- ParameterKey: 'TargetGroupARNs'
  ParameterValue: 'arn:aws:elasticloadbalancing:ap-northeast-1:268673644828:targetgroup/cpi-tyo-tg-blue/7ad7c69e06f22595'
- ParameterKey: 'HealthCheckType'
  ParameterValue: 'EC2'
- ParameterKey: 'VpcId'
  ParameterValue: 'vpc-06106967d774bee36'
- ParameterKey: 'SecurityGroupName'
  ParameterValue: 'cpi-dev-tyo-sg-web'
- ParameterKey: 'SecurityGroupDescription'
  ParameterValue: 'cpi-dev-tyo-sg-web'
- ParameterKey: 'SecurityGroupIdForALB'
  ParameterValue: 'sg-07a10151f263e2b42'
- ParameterKey: 'LaunchTemplateName'
  ParameterValue: 'cpi-dev-tyo-as-launchtemplate-web'
- ParameterKey: 'EC2Name'
  ParameterValue: 'cpi-dev-tyo-as-ec2-web'
- ParameterKey: 'ImageId'
  ParameterValue: 'ami-00eedaa8f7f2a6440'
- ParameterKey: 'InstanceType'
  ParameterValue: 't2.micro'
- ParameterKey: 'KeyName'
  ParameterValue: 'Bastion01'
- ParameterKey: 'IamInstanceProfile'
  ParameterValue: 'cpi-iam-role-web'
- ParameterKey: 'UserData'
  ParameterValue: |
- ParameterKey: 'UseScalingPolicy'
  ParameterValue: 'ture'
- ParameterKey: 'PolicyType'
  ParameterValue: 'TargetTrackingScaling'
- ParameterKey: 'PredefinedMetricType'
  ParameterValue: 'ASGAverageCPUUtilization'
- ParameterKey: 'TargetValue'
  ParameterValue: '70'

スタック作成

バッチファイルを作成して実行します。

ファイル名:create_cpi-dev-ec2autoscaling-web.bat

@echo off
set CFN_PATH=D:\AWS-CPI-DEV\90_Template
set INPUT_PATH=D:\AWS-CPI-DEV\90_Template\InputFiles
set TEMPLATE_NAME=EC2Autoscaling-Template.yaml
set INPUT_NAME=cpi-dev-ec2autoscaling-web.yaml

aws cloudformation create-stack --template-body file://%CFN_PATH%\%TEMPLATE_NAME% --cli-input-yaml file://%INPUT_PATH%\%INPUT_NAME%

バッチを実行

create_cpi-dev-ec2autoscaling-web.bat
{
    "StackId": "arn:aws:cloudformation:ap-northeast-1:268673644828:stack/cpi-dev-ec2autoscaling-web/7a64ccd0-c05d-11eb-9ba1-0a8378d469cb"
}

確認

CloudFormationコンソール上で確認

EC2コンソール上で確認

テストページをアクセスしてみる

まとめ

テンプレートを利用する時、名前やサブネットIDを自分の環境に読み替えでください。少しでもお役に立てれば幸いです。

Last modified: 2021-05-29

Author