🔥

CloudFormationテンプレート作成してみた

2023/08/20に公開

目次

  • ALBを含んだ構成
  • Cloudwatchを含んだ構成
  • S3およびTrailの作成

ALBを含んだ構成

AWSTemplateFormatVersion: "2010-09-09"

Description:
  test-blog

Resources:
  TestVPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
      Tags:
        - Key: Name
          Value: TEST-VPC


  TestIGW:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags:
        - Key: Name
          Value: TEST-IGW


  AttachGateway:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      VpcId: !Ref TestVPC
      InternetGatewayId: !Ref TestIGW


  TestSubNet1:
    Type: AWS::EC2::Subnet
    Properties:
      AvailabilityZone: ap-northeast-1a
      VpcId: !Ref TestVPC
      CidrBlock: 10.0.11.0/24
      Tags:
        - Key: Name
          Value: TEST-SubNet1

  TestSubNet2:
    Type: AWS::EC2::Subnet
    Properties:
      AvailabilityZone: ap-northeast-1c
      VpcId: !Ref TestVPC
      CidrBlock: 10.0.12.0/24
      Tags:
        - Key: Name
          Value: TEST-SubNet2


  TestRouteTable1:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref TestVPC
      Tags:
        - Key: Name
          Value: TEST-RouteTable1


  TestRoute1:
    Type: AWS::EC2::Route
    Properties:
      RouteTableId: !Ref TestRouteTable1
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref TestIGW


  TestSubNetRoutTablAsso:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref TestSubNet1
      SubnetId: !Ref TestSubNet2
      RouteTableId: !Ref TestRouteTable1


  TestSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: TEST-SecurityGroup
      GroupDescription: TEST-SecurityGroup
      VpcId: !Ref TestVPC
      SecurityGroupIngress:
      - 
        IpProtocol: tcp
        CidrIp: 0.0.0.0/0
        FromPort: "22"
        ToPort: "22"


  TestEC2Instance:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: ami-09ebacdc178ae23b7
      KeyName: test-key
      InstanceType: t2.micro
      InstanceInitiatedShutdownBehavior: stop
      Tenancy: default
      NetworkInterfaces:
        - AssociatePublicIpAddress: "true"
          DeviceIndex: "0"
          SubnetId: !Ref TestSubNet1
          GroupSet:
            - !Ref TestSecurityGroup
          PrivateIpAddress: 10.0.11.250

      Tags:
          - Key: Name
            Value: test_linux_instance
      
      BlockDeviceMappings:  
        - DeviceName: /dev/xvda
          Ebs:
            VolumeType: gp2
            DeleteOnTermination: true 
            VolumeSize: 10

      UserData: !Base64 |
        sudo hostnamectl set-hostname TEST-LINUX-INSTANCE


  EipTestServer:
    Type: AWS::EC2::EIP
    Properties:
      InstanceId: !Ref TestEC2Instance


  TestALB:
    Type: AWS::ElasticLoadBalancingV2::LoadBalancer
    Properties:
      Name: Test-ALB
      Scheme: internet-facing
      Subnets:
        - !Ref TestSubNet1
        - !Ref TestSubNet2
      SecurityGroups:
        - !Ref TestSecurityGroup
      Tags:
        - Key: Name
          Value: Test-ALB

  TestTargetGroup:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      Name: Test-TargetGroup
      Port: 80
      Protocol: HTTP
      VpcId: !Ref TestVPC
      TargetType: instance
      HealthCheckIntervalSeconds: 30
      HealthCheckPath: /
      HealthCheckProtocol: HTTP
      HealthCheckTimeoutSeconds: 5
      HealthyThresholdCount: 2
      UnhealthyThresholdCount: 2
      Matcher:
        HttpCode: "200"

  TestListener:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties:
      LoadBalancerArn: !Ref TestALB
      Protocol: HTTP
      Port: 80
      DefaultActions:
        - Type: forward
          TargetGroupArn: !Ref TestTargetGroup

Cloudwatchを含んだ構成

AWSTemplateFormatVersion: "2010-09-09"

Description:
  test-blog

Resources:
  TestVPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
      Tags:
        - Key: Name
          Value: TEST-VPC


  TestIGW:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags:
        - Key: Name
          Value: TEST-IGW


  AttachGateway:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      VpcId: !Ref TestVPC
      InternetGatewayId: !Ref TestIGW


  TestSubNet1:
    Type: AWS::EC2::Subnet
    Properties:
      AvailabilityZone: ap-northeast-1a
      VpcId: !Ref TestVPC
      CidrBlock: 10.0.11.0/24
      Tags:
        - Key: Name
          Value: TEST-SubNet1

  TestSubNet2:
    Type: AWS::EC2::Subnet
    Properties:
      AvailabilityZone: ap-northeast-1c
      VpcId: !Ref TestVPC
      CidrBlock: 10.0.12.0/24
      Tags:
        - Key: Name
          Value: TEST-SubNet2


  TestRouteTable1:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref TestVPC
      Tags:
        - Key: Name
          Value: TEST-RouteTable1


  TestRoute1:
    Type: AWS::EC2::Route
    Properties:
      RouteTableId: !Ref TestRouteTable1
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref TestIGW


  TestSubNetRoutTablAsso:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref TestSubNet1
      SubnetId: !Ref TestSubNet2
      RouteTableId: !Ref TestRouteTable1


  TestSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: TEST-SecurityGroup
      GroupDescription: TEST-SecurityGroup
      VpcId: !Ref TestVPC
      SecurityGroupIngress:
      - 
        IpProtocol: tcp
        CidrIp: 0.0.0.0/0
        FromPort: "22"
        ToPort: "22"


  TestEC2Instance:
    Type: AWS::EC2::Instance
    Properties:
      Monitoring: true  # EC2インスタンスの監視を有効化
      ImageId: ami-09ebacdc178ae23b7
      KeyName: test-key
      InstanceType: t2.micro
      InstanceInitiatedShutdownBehavior: stop
      Tenancy: default
      NetworkInterfaces:
        - AssociatePublicIpAddress: "true"
          DeviceIndex: "0"
          SubnetId: !Ref TestSubNet1
          GroupSet:
            - !Ref TestSecurityGroup
          PrivateIpAddress: 10.0.11.250

      Tags:
          - Key: Name
            Value: test_linux_instance
      
      BlockDeviceMappings:  
        - DeviceName: /dev/xvda
          Ebs:
            VolumeType: gp2
            DeleteOnTermination: true 
            VolumeSize: 10

      UserData: !Base64 |
        sudo hostnamectl set-hostname TEST-LINUX-INSTANCE

  EipTestServer:
    Type: AWS::EC2::EIP
    Properties:
      InstanceId: !Ref TestEC2Instance

  TestALB:
    Type: AWS::ElasticLoadBalancingV2::LoadBalancer
    Properties:
      Name: Test-ALB
      LoadBalancerAttributes:  # ALBの監視設定
        - Key: access_logs.s3.enabled
          Value: "true"
        - Key: access_logs.s3.bucket
          Value: my-access-logs-bucket
        - Key: access_logs.s3.prefix
          Value: alb-logs/
      Scheme: internet-facing
      Subnets:
        - !Ref TestSubNet1
        - !Ref TestSubNet2
      SecurityGroups:
        - !Ref TestSecurityGroup
      Tags:
        - Key: Name
          Value: Test-ALB

  TestTargetGroup:
    Type: AWS::ElasticLoadBalancingV2::TargetGroup
    Properties:
      Name: Test-TargetGroup
      Port: 80
      Protocol: HTTP
      VpcId: !Ref TestVPC
      TargetType: instance
      HealthCheckIntervalSeconds: 30
      HealthCheckPath: /
      HealthCheckProtocol: HTTP
      HealthCheckTimeoutSeconds: 5
      HealthyThresholdCount: 2
      UnhealthyThresholdCount: 2
      Matcher:
        HttpCode: "200"
      TargetGroupAttributes:  # ターゲットグループの監視設定
        - Key: deregistration_delay.timeout_seconds
          Value: "300"
        - Key: stickiness.enabled
          Value: "true"
        - Key: stickiness.type
          Value: lb_cookie
        - Key: stickiness.lb_cookie.duration_seconds
          Value: "86400"

  TestListener:
    Type: AWS::ElasticLoadBalancingV2::Listener
    Properties:
      LoadBalancerArn: !Ref TestALB
      Protocol: HTTP
      Port: 80
      DefaultActions:
        - Type: forward
          TargetGroupArn: !Ref TestTargetGroup
      ListenerTags:  # リスナーの監視設定
        - Key: Name
          Value: Test-Listener

S3およびTrailの作成

・DescriptionでTrailから作成することでエラーをなくす

AWSTemplateFormatVersion: 2010-09-09
Description: CloudTrail

#------------------------------
# Resources: Your resource list
#------------------------------
Resources:
  # CloudTrailをS3に保存するためのバケットを作成する。ライフサイクルは1日
  ## Logs bucket
  CloudTrailBucket:
    Type: AWS::S3::Bucket
    Properties:
      AccessControl: LogDeliveryWrite
      BucketEncryption:
        ServerSideEncryptionConfiguration:
        - ServerSideEncryptionByDefault:
            SSEAlgorithm: AES256
      PublicAccessBlockConfiguration:
        BlockPublicAcls: True
        BlockPublicPolicy: True
        IgnorePublicAcls: True
        RestrictPublicBuckets: True
            LifecycleConfiguration: 
                Rules: 
                  - Id: !Sub ${BucketLabel}-life-cycle-rule
                    Status: "Enabled"
                    ExpirationInDays: 1

  ## Logs bucket policy
  CloudTrailBucketPolicy:
    Type: AWS::S3::BucketPolicy
    Properties:
      Bucket: !Ref CloudTrailBucket
      PolicyDocument:
        Version: 2012-10-17
        Statement:
        - Sid: AWSCloudTrailAclCheck
          Effect: Allow
          Principal:
            Service: cloudtrail.amazonaws.com
          Action: s3:GetBucketAcl
          Resource: !Sub "arn:aws:s3:::${CloudTrailBucket}"
        - Sid: AWSCloudTrailWrite
          Effect: Allow
          Principal:
            Service: cloudtrail.amazonaws.com
          Action: s3:PutObject
          Resource: !Sub "arn:aws:s3:::${CloudTrailBucket}/AWSLogs/${AWS::AccountId}/*"
          Condition:
            StringEquals:
              s3:x-amz-acl: bucket-owner-full-control

  # CloudTrailを有効化する
  ## CloudTrail
  CloudTrail:
    Type: AWS::CloudTrail::Trail
    Properties:
      S3BucketName: !Ref CloudTrailBucket
      IncludeGlobalServiceEvents: true
      IsLogging: true
      KMSKeyId: !Ref myKey
      IsMultiRegionTrail: true
      EnableLogFileValidation: true
      TrailName: cloudtraillog

Discussion