✍️

CloudFormationでTerraform使用の前提となるリソースを作成する

2022/02/07に公開

AWS環境でTerraform使用の前提となる下記リソースをCloudFormationで作成する際のテンプレート。

  • S3バケット
  • DynamoDBテーブル
AWSTemplateFormatVersion: 2010-09-09
Description: S3 and DynamoDB for Terraform

Parameters:
  S3BucketName:
    Default: 'terraform-s3-bucket'
    Description: Type of this BucketName.
    Type: String
  TableName:
    Default: 'terraform-state-lock-table'
    Description: DynamoDB Table Name
    Type: String

Resources:
  TerraformS3Bucket:
    Type: 'AWS::S3::Bucket'
    Properties:
      BucketName: !Sub ${S3BucketName}
      BucketEncryption:
        ServerSideEncryptionConfiguration:
          - ServerSideEncryptionByDefault:
              SSEAlgorithm: 'AES256'
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true
      Tags:
         - Key: "Name"
           Value: !Ref S3BucketName

  TerraformS3BucketPolicy:
    Type: 'AWS::S3::BucketPolicy'
    Properties:
      Bucket: !Ref TerraformS3Bucket
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Action:
            - 's3:*'
            Effect: Deny
            Sid: Deny non-HTTPS access
            Resource: 
              - !Sub 'arn:aws:s3:::${TerraformS3Bucket}'
              - !Sub 'arn:aws:s3:::${TerraformS3Bucket}/*'
            Principal: '*'
            Condition:
              Bool:
                'aws:SecureTransport':
                  - "false"

  TerraformDynamoDBTable:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: !Ref TableName
      AttributeDefinitions:
        -
          AttributeName: LockID
          AttributeType: S
      KeySchema:
        -
          AttributeName: LockID
          KeyType: HASH
      ProvisionedThroughput:
        ReadCapacityUnits: 5
        WriteCapacityUnits: 5
      Tags:
         - Key: "Name"
           Value: !Ref TableName

Outputs:
  TerraformS3BucketName:
    Value: !Ref TerraformS3Bucket

  TerraformDynamoDBTableName:
    Value:
      !Ref TerraformDynamoDBTable

Discussion