How I Used Terraform Effectively: A Guide To Best Practices

Increase Your Deployment Efficiency and Scale with Terraform’s Best Practices

Ink Insight 🧘🏼
ILLUMINATION
4 min readMay 18, 2023

--

It all started when I was working to streamline my Terraform projects. As the complexity of my infrastructure grew, I found myself drowning in a sea of resource names, module designations, and variable identifiers. It became difficult for me and my team as well, so I realized that I needed a better approach.

Strap in and get ready for a dive into the realm of structured and organized deployments! :)

Today, I want to share the Terraform best practices. As IaaC becomes increasingly prevalent, it is important to adopt practices that ensure reliability, scalability, and maintainability in our Terraform deployments.

Starting from Terraform naming conventions and what’s the best way to name our resources :

[ we take so much time to give a name to our loved one then why not do the same for our code :) ]

  1. Resource Naming:

Use lowercase letters and separate words with underscores.
Follow a <resource_type>_<service_name>_<purpose> format.
Example: `aws_instance_webapp_front_end`

2. Module Naming:

  • Use lowercase letters and separate words with underscores.
    Follow a <service_name>_<module_purpose> format.
    Example: `aws_ec2_instance_webapp`

3. Variable Naming:

  • Use lowercase letters and separate words with underscores.
    Follow a <resource_type>_<service_name>_<variable_purpose> format.
    Example: `aws_instance_webapp_instance_type`
  • Remember to use name, description, and default, value for variables.

4. Environment Naming:

  • Use lowercase letters and separate words with underscores.
    Follow a <project_name>_<environment> format.
    Example: `myproject_prod`

5. File Naming: [this might not be useful in your case]

  • Use lowercase letters and separate words with underscores.
    Follow a <resource_type>_<service_name>_<environment>.tf format for Terraform configuration files.
    Example: `aws_instance_webapp_prod.tf`

Remember that these examples are not exhaustive, and you should adapt them to suit your specific project and organizational requirements. The goal is to create consistent, meaningful, and easily understandable names that facilitate collaboration and maintenance of your Terraform codebase.

The second Best Practice — Harnessing the Power of Terraform Tags

1. Purpose of Tags: Tags in Terraform allow you to assign metadata to your resources, providing additional context and information. They can be used to categorize resources, track costs, enable resource identification, and enhance resource management.

2. Consistent Tagging Scheme: Establish a consistent tagging scheme across your Terraform deployments. This scheme should include key attributes like Environment, Application, Owner, Cost Center, and any other relevant identifiers for your organization.

3. Mandatory vs. Optional Tags: Determine which tags are mandatory for all resources and ensure they are applied consistently. Optional tags can be used to capture additional information that may be helpful for reporting or filtering purposes.

Here’s an example table that showcases mandatory and optional tags for resources:

Example table that showcases mandatory and optional tags for resources:

| Mandatory Tags | Optional Tags | Comments
|-------------------------------------------------|--------------------|
| Environment: production | Department: it |
| CreatedBy: terraform | CostCenter: 54321 |
| Project: myproject | Application: database |
| Owner: devops | |

4. Resource Grouping and Filtering: Leverage tags to group and filter resources based on shared attributes. For example, you could tag all resources belonging to a specific application or project with a common tag value.

resource "aws_instance" "web_server" {
instance_type = "t2.micro"
ami = "ami-0c94855ba95c71c99"
# Other instance configuration...

tags = {
Environment = "Production"
Application = "WebServer"
}
}

5. Cost Allocation and Budgeting: Use tags to track costs and allocate expenses accurately. This can be done by assigning tags related to cost centers, departments, or projects, which enables better visibility and cost analysis.

resource "aws_db_instance" "database" {
# Database instance configuration...

tags = {
CostCenter = "12345"
Department = "Marketing"
}
}

6. Automation and Resource Management: Incorporate tags into your automation workflows and resource management processes. For instance, you can use tags to automate resource cleanup based on expiration dates or to trigger specific actions based on resource attributes.

resource "aws_instance" "web_server" {
instance_type = "t2.micro"
ami = "ami-0c94855ba95c71c99"
# Other instance configuration...

tags = {
Environment = "Staging"
Application = "WebServer"
Project = "MyProject"
ExpiryDate = "2023-12-31"
}

lifecycle {
prevent_destroy = var.prevent_destroy_instances
}

# Automation to terminate instances based on ExpiryDate tag
provisioner "local-exec" {
command = <<EOF
if [[ $(date -d "${aws_instance.web_server.tags.ExpiryDate}" +%s) -lt $(date +%s) ]]; then
terraform destroy -target=aws_instance.web_server -auto-approve
fi
EOF
}
}

By implementing these tagging best practices, you can effectively manage resources, automate actions, and ensure consistency across your Terraform deployments.

In the upcoming parts of this blog series, we’ll explore additional best practices of Terraform, including file structure, standardizing prefixes, and integrating tags with monitoring and security practices.

Thanks for reading! I’d appreciate your support 👏 and engagement 🚙 in my stories :)

Don’t miss a beat — subscribe to my Medium newsletter to get my latest articles and content before anyone else!

--

--

Ink Insight 🧘🏼
ILLUMINATION

Discover the intersection of DevOps, InfoSec, and mindfulness with Ink Insight. Follow for valuable insights! ✍︎ 👨‍💻 🧘🏼