Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
CloudFormation Template for creating S3 bucket and DynamoDB table to hold Terraform state and locks
AWSTemplateFormatVersion: 2010-09-09
Description: >
Template for creating S3 bucket and DynamoDB table to hold Terraform state and locks
Validate: aws cloudformation validate-template --template-body file://terraform_state.yml
Deploy: aws cloudformation create-stack --region us-east-1 --stack-name Terraform-State-Resources --enable-termination-protection --template-body file://terraform_state.yml --parameters ParameterKey=TerraformStateBucketPrefix,ParameterValue=terraform-state ParameterKey=TerraformStateLockTableName,ParameterValue=terraform-state-locks
Parameters:
TerraformStateBucketPrefix:
Type: String
Default: terraform-state
Description: A prefix for S3 bucket name, account id will be added to ensure global uniqueness
TerraformStateLockTableName:
Type: String
Default: terraform-state-locks
Resources:
TerraformStateS3Bucket:
Type: AWS::S3::Bucket
Properties:
BucketName: !Sub "${TerraformStateBucketPrefix}-${AWS::Region}-${AWS::AccountId}"
AccessControl: Private
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
VersioningConfiguration:
Status: Enabled
TerraformStateS3BucketBucketPolicy:
DependsOn:
- TerraformStateS3Bucket
Type: AWS::S3::BucketPolicy
Properties:
Bucket: !Ref TerraformStateS3Bucket
PolicyDocument:
Statement:
- Sid: DenyDeletingTerraformStateFiles
Effect: Deny
Principal: "*"
Action: "s3:DeleteObject"
Resource: !Sub "arn:aws:s3:::${TerraformStateS3Bucket}/*"
TerraformStateLockDynamoDBTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: !Ref TerraformStateLockTableName
AttributeDefinitions:
- AttributeName: LockID
AttributeType: S
KeySchema:
- AttributeName: LockID
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 5
WriteCapacityUnits: 5
SSESpecification:
SSEEnabled: true
Tags:
# Add custom tags as CloudFormation is not able to add these unlike S3
- Key: aws-cloudformation-stack-id
Value: !Ref "AWS::StackId"
- Key: aws-cloudformation-stack-name
Value: !Ref "AWS::StackName"
- Key: aws-cloudformation-logical-id
Value: TerraformStateLockDynamoDBTable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment