Cloudformation for Terraform State Files and Lock Table

Terraform requires a state bucket and lock table before it can do any work, but you can't create these in Terraform because it needs them to do anything…. vicious circle.

I've used Cloud Formation to create these, then Terraform will work as expected.

Terraform_StateS3_and_Dynamo_Lock_Table.yaml

AWSTemplateFormatVersion: 2010-09-09
Description: CloudFormation template for s3 bucket

Resources:
  S3Bucket:
    DeletionPolicy: Retain
    Type: 'AWS::S3::Bucket'
    Description: Creating Amazon S3 bucket from CloudFormation
    Properties:
      BucketName: vpc-ec2-statefiles-sg
      AccessControl: Private
      PublicAccessBlockConfiguration:
        BlockPublicAcls: true
        BlockPublicPolicy: true
        IgnorePublicAcls: true
        RestrictPublicBuckets: true
      VersioningConfiguration:
        Status: Enabled

  BucketNameParamater:
    Type: AWS::SSM::Parameter
    Properties:
      Description: Terraform State S3 bucket
      Name: TerraformStateBucket-SG
      Type: String
      Value: !Ref S3Bucket
 

  DynamoLockTable:
    Type: AWS::DynamoDB::Table
    Properties:
      TableName: vpc-ec2-lockfiles-SG
      BillingMode: PAY_PER_REQUEST
      AttributeDefinitions:
        -
          AttributeName: LockID
          AttributeType: S

      KeySchema:
        -
          AttributeName: LockID
          KeyType: HASH

  LockTableParameter:
    Type: AWS::SSM::Parameter
    Properties:
      Description: Terraform Lock TableName
      Name: TerraformLockTable-SG
      Type: String
      Value: !Ref DynamoLockTable
 

Outputs:
  S3Bucket:
    Description: Bucket Created using this template.
    Value: !Ref S3Bucket

  DynamoLocktable:
    Description: DynamoDB table
    Value: !Ref DynamoLockTable
 
aws/aws-cloudformation-terraformstate.txt · Last modified: 23/01/2024 16:22 by andrew