This is a quick setup to create a dynamodb table and a S3 bucket for terraform backend on AWS. The state for this will be stored locally on the repository in the current setup.
First, let's create the provider file to configure AWS plugin and basic configuration
provider.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
}
}
}
provider "aws" {
region = local.aws_region
profile = local.aws_profile
default_tags {
tags = local.default_tags
}
}
Then, let's create our main file where we specify the configuration for the S3 bucket + KMS key and the DynamoDB table for locking.
main.tf
locals {
# Default tags to be applied to all compatible resources
default_tags = {
"OwnedBy" = "Terraform",
"cost-center" = "data-sharing",
"source" = "git@gitlab.com:{github-username}/{repository-name}.git"
}
aws_profile = "{aws-profile-name}"
aws_region = "{aws-region}"
project_name = "my-project"
github_username = "github-username"
}
resource "aws_kms_key" "key" {
description = "s3 backend key"
deletion_window_in_days = 7
}
resource "aws_s3_bucket" "state-bucket" {
bucket = "iac-terraform-states"
acl = "private"
server_side_encryption_configuration {
rule {
apply_server_side_encryption_by_default {
kms_master_key_id = aws_kms_key.key.arn
sse_algorithm = "aws:kms"
}
}
}
}
resource "aws_dynamodb_table" "state-lock" {
hash_key = "LockID"
name = "iac-terraform-states-lock"
write_capacity = 5
read_capacity = 5
attribute {
name = "LockID"
type = "S"
}
}
Run the following command to apply the changes:
terraform apply
And to remove it, delete all content from the bucket, and then run the following command:
terraform destroy