Skip to content

Instantly share code, notes, and snippets.

@tmokmss
Created March 2, 2022 05:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmokmss/304df0db42686c86b2bc49be076ffc5d to your computer and use it in GitHub Desktop.
Save tmokmss/304df0db42686c86b2bc49be076ffc5d to your computer and use it in GitHub Desktop.
Create AWS resources for Terraform S3 backend
#!/bin/bash
# A shell script to create AWS resources for Terraform S3 backend
STACK_NAME=TerraformStateStack-6nc8asv # add random suffix to prevent from colliding with any existing stacks
TEMPLATE_PATH="$(dirname "$0")/workspace_cfn.yaml"
aws cloudformation deploy --stack-name $STACK_NAME --template-file $TEMPLATE_PATH --no-cli-pager
aws cloudformation describe-stacks --stack-name $STACK_NAME --query "Stacks[0].Outputs" --no-cli-pager
# modified this: https://gist.github.com/qtangs/c91b5f962147d8da87be947b83d80cee
AWSTemplateFormatVersion: 2010-09-09
Description: Deploy resources required for Terraform S3 backend
Resources:
TerraformStateS3Bucket:
Type: AWS::S3::Bucket
Properties:
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:
AttributeDefinitions:
- AttributeName: LockID
AttributeType: S
KeySchema:
- AttributeName: LockID
KeyType: HASH
BillingMode: PAY_PER_REQUEST
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
Outputs:
BucketName:
Description: Terraform backend S3 bucket
Value: !Ref TerraformStateS3Bucket
TableName:
Description: Terraform backend DynamoDB table
Value: !Ref TerraformStateLockDynamoDBTable
AWsRegion:
Description: AWS region this stack is deployed in
Value: !Ref "AWS::Region"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment