へっぽこエンジニアの覚え書き

主に、バッチとTeraTermマクロのことについて書きます。

AWS CloudFormationを部品ごとに構成できるようにテンプレートを書いた

CloudFormationはとっても便利なのですが、VPCからインスタンスまで一つのテンプレート内に書くと、構成がしっかり決まっている場合は問題ないのですが、後から構成を変える場合にはいったん全部消えてしまうことがあり融通がきかない面があります。

そういった場合のためにテンンプレートを部品ごとに分割して、あとから構成を変更、インスタンスの追加などを行えるようなテンプレートを書きました。

#########################################################
# ここで分割
#########################################################
AWSTemplateFormatVersion'2010-09-09'
Parameters:
  Prefix:
    TypeString
    Description"A prefix that does not conflict with other instances when multiple instances are launched"
  VPCCidr:
    TypeString
    DescriptionIP Address range for the VPN connected VPC
    ConstraintDescriptionmust be a valid IP CIDR range of the form x.x.x.x/x.
    MinLength9
    MaxLength18
    Default10.0.0.0/16
    AllowedPattern(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/(\d{1,2})
Resources:
  MainVpc:
    Type'AWS::EC2::VPC'
    Properties:
      CidrBlock!Ref VPCCidr
      Tags:
        - Key'Name'
          Value!Sub ${Prefix}-main-vpc
  MainInetGateway:
    Type'AWS::EC2::InternetGateway'
    Properties:
      Tags:
      - Key'Name'
        Value!Sub ${Prefix}-main-igw
  MainVpcGatewayAttachment:
    Type'AWS::EC2::VPCGatewayAttachment'
    Properties:
      InternetGatewayId!Ref MainInetGateway
      VpcId!Ref MainVpc
Outputs:
  VPCCidr:
    Value!Ref VPCCidr
    Export:
      Name'VPCCidr'
  MainVpc:
    Value!Ref MainVpc
    Export:
      Name'main-vpc-id'
  MainInetGateway:
    Value!Ref MainInetGateway
    Export:
      Name'main-igw-id'
#########################################################
# 分割
#########################################################
AWSTemplateFormatVersion'2010-09-09'
Parameters:
  Prefix:
    TypeString
    Description"A prefix that does not conflict with other instances when multiple instances are launched"
  SubnetCidr:
    TypeString
    DescriptionSubnetCidr
    ConstraintDescriptionmust be a valid IP CIDR range of the form x.x.x.x/x.
    MinLength9
    MaxLength18
    Default10.0.1.0/24
    AllowedPattern(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/(\d{1,2})
Resources:
  PublicSubnet:
    Type'AWS::EC2::Subnet'
    Properties:
      CidrBlock!Ref SubnetCidr
      MapPublicIpOnLaunchtrue
      VpcId: {'Fn::ImportValue''main-vpc-id'}
      Tags:
        - Key'Name'
          Value!Sub ${Prefix}-public-subnet
  PublicRouteTable:
    Type'AWS::EC2::RouteTable'
    Properties:
      VpcId: {'Fn::ImportValue''main-vpc-id'}
      Tags:
        - Key'Name'
          Value!Sub ${Prefix}-public-rtb
  PublicDefaultRoute:
    Type'AWS::EC2::Route'
    Properties:
      RouteTableId!Ref PublicRouteTable
      DestinationCidrBlock0.0.0.0/0
      GatewayId: {'Fn::ImportValue''main-igw-id'}
  PublicSubnetRouteTableAssociation:
    TypeAWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId!Ref PublicSubnet
      RouteTableId!Ref PublicRouteTable
Outputs:
  SubnetCidr:
    Value!Ref SubnetCidr
    Export:
      Name'SubnetCidr'
  PublicSubnet:
    Value!Ref PublicSubnet
    Export:
      Name!Sub 'public-subnet-id'
#########################################################
# 分割
#########################################################
AWSTemplateFormatVersion'2010-09-09'
Parameters:
  Prefix:
    TypeString
    Description"A prefix that does not conflict with other instances when multiple instances are launched"
Resources:
  PublicSecurityGroupWin:
    Type"AWS::EC2::SecurityGroup"
    Properties:
      GroupNamepublic-sg-Win
      GroupDescription"SecurityGroup for Public EC2 Linux"
      SecurityGroupIngress:
      - IpProtocoltcp
        FromPort'3389'
        ToPort'3389'
        CidrIp0.0.0.0/0
      Tags:
        - Key'Name'
          Value!Sub ${Prefix}-public-sg
      VpcId: {'Fn::ImportValue''main-vpc-id'}
  PublicSecurityGroupLinux:
    Type"AWS::EC2::SecurityGroup"
    Properties:
      GroupNamepublic-sg-Linux
      GroupDescription"SecurityGroup for Public EC2 Windows"
      SecurityGroupIngress:
      - IpProtocoltcp
        FromPort'80'
        ToPort'80'
        CidrIp0.0.0.0/0
      - IpProtocoltcp
        FromPort'22'
        ToPort'22'
        CidrIp0.0.0.0/0
      Tags:
        - KeyName
          Value!Sub ${Prefix}-public-sg
      VpcId: {'Fn::ImportValue''main-vpc-id'}
Outputs:
  PublicSecurityGroupWin:
    Value!Ref PublicSecurityGroupWin
    Export:
      Name!Sub 'PublicSecurityGroupWin-id'
  PublicSecurityGroupLinux:
    Value!Ref PublicSecurityGroupLinux
    Export:
      Name!Sub 'PublicSecurityGroupLinux-id'
#########################################################
# 分割
#########################################################
AWSTemplateFormatVersion'2010-09-09'
Parameters:
  Ec2KeyName:
    Type'AWS::EC2::KeyPair::KeyName'
  WindowsLatestAmi:
    Type : AWS::SSM::Parameter::Value<String>
    AllowedValues: ["/aws/service/ami-windows-latest/Windows_Server-2016-Japanese-Full-Base""/aws/service/ami-windows-latest/Windows_Server-2019-Japanese-Full-Base"]
    Default"/aws/service/ami-windows-latest/Windows_Server-2016-Japanese-Full-Base"
    Description'Select Windows Server 2016 or 2019'
  InstanceType:
    TypeString
    AllowedValues: ["t2.nano""t2.micro""t2.small""t2.medium""t2.large""t2.xlarge""t2.2xlarge"]
    Default"t2.micro"
    Description'Select InstanceType'
  Prefix:
    TypeString
    Description"A prefix that does not conflict with other instances when multiple instances are launched"
  PrivateIpAddress:
    TypeString
    DescriptionPrivateIpAddress x.x.x.x
    ConstraintDescriptionmust be a valid IP CIDR range of the form x.x.x.x
    MinLength9
    MaxLength18
    Default10.0.1.10
    AllowedPattern(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})
  Hostname:
    TypeString
    Description"Input Hostname"
Resources:
  EC2Win:
    Type'AWS::EC2::Instance'
    Properties:
      ImageId!Ref WindowsLatestAmi
      InstanceType!Ref InstanceType
      KeyName!Ref Ec2KeyName
      SubnetId!ImportValue public-subnet-id
      PrivateIpAddress!Ref PrivateIpAddress
      SecurityGroupIds: [ !ImportValue PublicSecurityGroupWin-id ]
      UserData:
        Fn::Base64!Sub |
          <powershell>
          # disabled IEenhanced security
          $AdminPath = "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A7-37EF-4b3f-8CFC-4F3A74704073}"
          $UserPath = "HKLM:\SOFTWARE\Microsoft\Active Setup\Installed Components\{A509B1A8-37EF-4b3f-8CFC-4F3A74704073}"
          $AdminPath, $UserPath | % { Set-ItemProperty -Path $_ -Name "IsInstalled" -Value 0 }
          Stop-Process -Name Explorer

          # set JST TimeZone
          tzutil /s "Tokyo Standard Time"
          Set-ItemProperty -Path "HKLM:\System\CurrentControlSet\Control\TimeZoneInformation" -Name "RealTimeIsUniversal" -Value 1

          # disabled firewall
          Get-NetFirewallProfile | Set-NetFirewallProfile -Enabled false

          # show fileext and hidden file
          Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "HideFileExt" -Value 0
          Set-ItemProperty -Path "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Advanced" -Name "Hidden" -Value 1

          # set high performance
          powercfg.exe -SETACTIVE 8c5e7fda-e8bf-4a96-9a85-a6e23a8c635c
          
          # Set Hostname
          !Ref Rename-Computer -NewName ${Hostname} -Force
          </powershell>
      Tags:
        - Key'Name'
          Value!Sub ${Prefix}-EC2Win

#########################################################
# 分割
#########################################################
AWSTemplateFormatVersion'2010-09-09'
Parameters:
  Prefix:
    TypeString
    Description"A prefix that does not conflict with other instances when multiple instances are launched"
    
Parameters:
  Ec2KeyName:
    Type'AWS::EC2::KeyPair::KeyName'
    Description'Select KeyPair'
  LinuxLatestAmi:
    TypeAWS::SSM::Parameter::Value<String>
    Default"/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2"
    Description'Latest Amazon Linux 2 Version'
  InstanceType:
    TypeString
    AllowedValues: ["t2.nano""t2.micro""t2.small""t2.medium""t2.large""t2.xlarge""t2.2xlarge"]
    Default"t2.micro"
    Description'Select InstanceType'
  Prefix:
    TypeString
    Description"A prefix that does not conflict with other instances when multiple instances are launched"
  PrivateIpAddress:
    TypeString
    DescriptionPrivateIpAddress x.x.x.x
    ConstraintDescriptionmust be a valid IP CIDR range of the form x.x.x.x
    MinLength9
    MaxLength18
    Default10.0.1.30
    AllowedPattern(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})
Resources:
  EC2Linux:
    Type'AWS::EC2::Instance'
    Properties:
      ImageId!Ref LinuxLatestAmi
      InstanceType!Ref InstanceType
      KeyName!Ref Ec2KeyName
      SubnetId!ImportValue public-subnet-id
      PrivateIpAddress!Ref PrivateIpAddress
      SecurityGroupIds: [ !ImportValue PublicSecurityGroupLinux-id ]
      UserData!Base64 |
            #!/bin/bash -ex
            sudo su -
            yum -y update
            yum -y install httpd
            systemctl start httpd
            systemctl status httpd
            systemctl enable httpd
      Tags:
        - Key'Name'
          Value!Sub ${Prefix}-EC2Linux