Last active
December 20, 2021 10:34
-
-
Save fabiopaiva/d488746c52854a739aec3f00d2b728b2 to your computer and use it in GitHub Desktop.
CDK stack creating a Terraform s3 backend service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from aws_cdk import core as cdk | |
from terraform_backend_stack import TerraformBackendStack | |
app = cdk.App() | |
TerraformBackendStack( | |
app, "TerraformBackendStack", description="Terraform S3 backend configuration" | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
terraform { | |
backend "s3" { | |
key = "terraform-backend-state/terraform.tfstate" | |
dynamodb_table = "terraform-state-lock" | |
encrypt = true | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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