Skip to content

Example

Loading...

Naming Conventions Example


In this example, we will create a naming convention for variables in a Terraform codebase. We will use the following naming conventions:


Well-structured variable


good-example.tf
1
variable "db_instance_name" {
2
# ...
3
}

bad-example.tf
1
variable "db_instance_name" {
2
# ...
3
}

Leverage Resource Argument Standards


good-example.tf
1
variable "db_instance_name" {
2
description = "The name of the RDS instance."
3
}

bad-example.tf
1
variable "db_instance_name" {
2
description = "The name of the RDS instance."
3
}

Types:


Utilize Type any for Flexibility:


good-example.tf
1
variable "codepipeline_artifact_store" {
2
type = any
3
}

Prioritize Simple Types:


good-example.tf
1
variable "instance_type" {
2
type = string
3
}

bad-example.tf
1
variable "instance_type" {
2
type = any
3
}

Choose Specific Types for Homogeneous Maps:


good-example.tf
1
variable "tags" {
2
type = map(string)
3
}

bad-example.tf
1
variable "tags" {
2
type = map(any)
3
}

Opt for Plural Form in Variable Names


good-example.tf
1
variable "db_instance_names" {
2
type = list(string)
3
}

bad-example.tf
1
variable "db_instance_name" {
2
type = string
3
}

Understand Validation Limitations:


good-example.tf
1
variable "db_instance_name" {
2
validation {
3
condition = length(var.db_instance_name) > 0
4
error_message = "The name of the RDS instance cannot be empty."
5
}
6
}

bad-example.tf
1
variable "db_instance_name" {
2
validation {
3
condition = var.db_instance_name != ""
4
error_message = "The name of the RDS instance cannot be empty."
5
}
6
}

Organize Variable Blocks:


good-example.tf
1
variable "db_instance_name" {
2
type = string
3
description = "The name of the RDS instance."
4
default = "rds-instance"
5
validation {
6
condition = length(var.db_instance_name) > 0
7
error_message = "The name of the RDS instance cannot be empty."
8
}
9
}