Terraform Tips & Tricks

A small collection of helpful hints

Terraform

S3 Bucket Lifecycle Rules

resource "aws_s3_bucket" "assets" { bucket = "${module.assets_bucket_label.id}" tags = "${module.assets_bucket_label.tags}" acl = "private" region = "us-west-2" force_destroy = false

lifecycle_rule { id = "${module.assets_bucket_label.id}" enabled = true

prefix = "" tags = "${module.assets_bucket_label.tags}"

<span style="color:#00a8c8">noncurrent_version_expiration</span> {

days = "90" }

<span style="color:#00a8c8">noncurrent_version_transition</span> {

days = "60" storage_class = "GLACIER" }

<span style="color:#00a8c8">transition</span> {

days = "30" storage_class = "STANDARD_IA" }

<span style="color:#00a8c8">transition</span> {

days = "60" storage_class = "GLACIER" }

<span style="color:#00a8c8">expiration</span> {

days = "180" } } }

For an example of how we use it, check out our terraform-aws-s3-log-storage module.

Encrypted S3 Buckets

resource "aws_s3_bucket" "assets" { bucket = "${module.assets_bucket_label.id}" tags = "${module.assets_bucket_label.tags}" acl = "private" region = "us-west-2" force_destroy = false

server_side_encryption_configuration { rule { apply_server_side_encryption_by_default { sse_algorithm = "AES256" } } } }

For an example of how we use it, check out our terraform-aws-s3-log-storage module.

Use Pre Commit Hooks for Linting

We strongly urge that all code be linted prior to checking into Git. Running terraform fmt on the codebase before committing will accomplish this.

To set this up so that it happens automatically prior to any commit, configure git pre-commit hooks using the pre-commit utility.

OSX Installation
brew install pre-commit

Then run pre-commit install in a given terraform repo to configure the hooks.

.pre-commit-config.yaml
- repo: git://github.com/antonbabenko/pre-commit-terraform
  sha: v1.45.0
  hooks:
    - id: terraform_fmt
    - id: terraform_validate

After setting this up, every time you commit, the terraform fmt command will be run to canonicalize your files and a basic smoke test to validate all configurations without requiring required variables to be set.

Any time your commit affects any *.tf files, the validator will ensure well-formed terraform code.