Skip to content

Instantly share code, notes, and snippets.

@fabiopaiva
Last active December 20, 2021 10:34
Show Gist options
  • Save fabiopaiva/d488746c52854a739aec3f00d2b728b2 to your computer and use it in GitHub Desktop.
Save fabiopaiva/d488746c52854a739aec3f00d2b728b2 to your computer and use it in GitHub Desktop.
CDK stack creating a Terraform s3 backend service
from aws_cdk import core as cdk
from terraform_backend_stack import TerraformBackendStack
app = cdk.App()
TerraformBackendStack(
app, "TerraformBackendStack", description="Terraform S3 backend configuration"
)
terraform {
backend "s3" {
key = "terraform-backend-state/terraform.tfstate"
dynamodb_table = "terraform-state-lock"
encrypt = true
}
}
from aws_cdk import (
core as cdk,
aws_dynamodb as dynamo,
aws_s3 as s3,
aws_iam as iam,
)
class TerraformBackendStack(cdk.Stack):
def __init__(self, scope: cdk.Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
bucket = s3.Bucket(
self,
"TerraformBackendBucket",
bucket_name="terraform-backend-state", # Rename it
block_public_access=s3.BlockPublicAccess.BLOCK_ALL,
access_control=s3.BucketAccessControl.PRIVATE,
encryption=s3.BucketEncryption.S3_MANAGED,
versioned=True,
)
bucket.add_to_resource_policy(
iam.PolicyStatement(
sid="AllowSSLRequestsOnly",
effect=iam.Effect.DENY,
actions=["s3:*"],
resources=[bucket.bucket_arn, f"arn:aws:s3:::{bucket.bucket_name}/*"],
principals=[iam.AnyPrincipal().grant_principal],
conditions={"Bool": {"aws:SecureTransport": False}},
)
)
dynamo.Table(
self,
"TerraformLockTable",
table_name="terraform-state-lock",
billing_mode=dynamo.BillingMode.PAY_PER_REQUEST,
partition_key=dynamo.Attribute(
name="LockID", type=dynamo.AttributeType.STRING
),
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment