Serverless Framework (CloudFormation) で PostgreSQL をインストールした EC2 インスタンスを起動する

service: サービス名
provider:
  name: aws
  region: ap-northeast-1
  iam:
    role:
      name: ロール名
      statements:
        - Effect: "Allow"
          Action:
            - "ec2:RunInstances"

resources:

  Resources:
    PostgreSQLInstance:
      Type: 'AWS::EC2::Instance'
      Properties:

        ImageId: ami-03179588b2f59f257
        InstanceType: 't3a.nano'
        KeyName: キーペアの名前
        BlockDeviceMappings:
          - DeviceName: /dev/xvda
            Ebs:
              VolumeType: 'gp3'
              VolumeSize: '30'
              Iops: '3000'

        UserData:
          Fn::Base64: !Sub |
            #!/bin/bash -xe
            yum install postgresql-server postgresql-devel postgresql-contrib -y
            postgresql-setup initdb
            systemctl enable postgresql.service
            systemctl start postgresql.service
            sudo -u postgres createdb データベース名
            sudo -u postgres psql -U postgres -c "CREATE ROLE ユーザー名 WITH LOGIN PASSWORD 'パスワード'"
            sudo -u postgres psql -U postgres -c "GRANT ALL PRIVILEGES ON DATABASE データベース名 TO ユーザー名"
            echo 'host all all 0.0.0.0/0 password' > /var/lib/pgsql/data/pg_hba.conf
            echo 'local all all password' >> /var/lib/pgsql/data/pg_hba.conf
            echo "listen_addresses = '*'" >> /var/lib/pgsql/data/postgresql.conf
            systemctl restart postgresql.service