Terraform Variables: Difference between revisions

From Dave-Wiki
(Created page with "== Terraform Variables: Best Practices and Use Cases == This guide covers the different types of variables in **Terraform**, their use cases, and best practices to manage them efficiently. ---- = 1. Overview of Terraform Variables = Variables in Terraform allow for the parameterization of configurations, making deployments more flexible and reusable. Terraform supports three primary types of variables: # **Input Variables (var)** – Define dynamic values for Terraf...")
 
No edit summary
 
Line 5: Line 5:
----
----


= 1. Overview of Terraform Variables =
= Overview of Terraform Variables =
Variables in Terraform allow for the parameterization of configurations, making deployments more flexible and reusable.
Variables in Terraform allow for the parameterization of configurations, making deployments more flexible and reusable.


Terraform supports three primary types of variables:
Terraform supports three primary types of variables:


# **Input Variables (var)** – Define dynamic values for Terraform modules.
* '''Input Variables (var)''' – Define dynamic values for Terraform modules.
# **Environment Variables (TF_VAR_name)** – Pass values externally without modifying files.
* '''Environment Variables (TF_VAR_name)''' – Pass values externally without modifying files.
# **Output Variables (output)** – Display key information after deployment.
* '''Output Variables (output)''' – Display key information after deployment.


----
----


= 2. Defining Input Variables =
= Defining Input Variables =
Input variables make Terraform configurations more dynamic and reusable.
Input variables make Terraform configurations more dynamic and reusable.


Line 22: Line 22:
Create a file named '''variables.tf''':
Create a file named '''variables.tf''':


<code>
<pre>
variable "vpc_cidr" {
variable "vpc_cidr" {
   description = "CIDR block for the VPC"
   description = "CIDR block for the VPC"
Line 28: Line 28:
   default    = "10.0.0.0/16"
   default    = "10.0.0.0/16"
}
}
</code>
</pre>


== Using Variables in Terraform Code ==
== Using Variables in Terraform Code ==
Use the defined variable in a Terraform resource:
Use the defined variable in a Terraform resource:


<code>
<pre>
resource "aws_vpc" "main" {
resource "aws_vpc" "main" {
   cidr_block = var.vpc_cidr
   cidr_block = var.vpc_cidr
}
}
</code>
</pre>


== Passing Variables ==
== Passing Variables ==
Variables can be passed in multiple ways:
Variables can be passed in multiple ways:


* **Using a .tfvars file:** Create '''terraform.tfvars''' with the following content:
* '''Using a .tfvars file:''' Create '''terraform.tfvars''' with the following content:


<code>
<pre>
vpc_cidr = "10.1.0.0/16"
vpc_cidr = "10.1.0.0/16"
</code>
</pre>


Run Terraform with:
Run Terraform with:
terraform apply -var-file=terraform.tfvars
<pre>terraform apply -var-file=terraform.tfvars</pre>


* **Passing via CLI:**
* '''Passing via CLI:'''
terraform apply -var="vpc_cidr=10.2.0.0/16"
<pre>terraform apply -var="vpc_cidr=10.2.0.0/16"</pre>


* **Using Environment Variables:**
* '''Using Environment Variables:'''
export TF_VAR_vpc_cidr="10.3.0.0/16"
<pre>export TF_VAR_vpc_cidr="10.3.0.0/16"
terraform apply
terraform apply</pre>


----
----


= 3. Variable Types and Best Practices =
= Variable Types and Best Practices =
Terraform supports different data types for variables:
Terraform supports different data types for variables:


== String ==
== String ==
<code>
<pre>
variable "region" {
variable "region" {
   type    = string
   type    = string
   default = "us-east-1"
   default = "us-east-1"
}
}
</code>
</pre>


== Number ==
== Number ==
<code>
<pre>
variable "instance_count" {
variable "instance_count" {
   type    = number
   type    = number
   default = 2
   default = 2
}
}
</code>
</pre>


== Boolean ==
== Boolean ==
<code>
<pre>
variable "enable_logging" {
variable "enable_logging" {
   type    = bool
   type    = bool
   default = true
   default = true
}
}
</code>
</pre>


== List ==
== List ==
<code>
<pre>
variable "azs" {
variable "azs" {
   type    = list(string)
   type    = list(string)
   default = ["us-east-1a", "us-east-1b"]
   default = ["us-east-1a", "us-east-1b"]
}
}
</code>
</pre>


== Map ==
== Map ==
<code>
<pre>
variable "instance_type_map" {
variable "instance_type_map" {
   type = map(string)
   type = map(string)
Line 104: Line 104:
   }
   }
}
}
</code>
</pre>


Usage:
Usage:
<code>
<pre>
instance_type = var.instance_type_map[terraform.workspace]
instance_type = var.instance_type_map[terraform.workspace]
</code>
</pre>


== Object ==
== Object ==
<code>
<pre>
variable "vpc_config" {
variable "vpc_config" {
   type = object({
   type = object({
Line 123: Line 123:
   }
   }
}
}
</code>
</pre>


----
----


= 4. Output Variables =
= Output Variables =
Output variables provide visibility into infrastructure values after deployment.
Output variables provide visibility into infrastructure values after deployment.


== Example of an Output Variable ==
== Example of an Output Variable ==
<code>
<pre>
output "vpc_id" {
output "vpc_id" {
   value      = aws_vpc.main.id
   value      = aws_vpc.main.id
   description = "The ID of the created VPC"
   description = "The ID of the created VPC"
}
}
</code>
</pre>


Retrieve outputs after running Terraform:
Retrieve outputs after running Terraform:
terraform output vpc_id
<pre>terraform output vpc_id</pre>


----
----


= 5. Best Practices for Terraform Variables =
= Best Practices for Terraform Variables =


* **Use Type Constraints** – Define variable types explicitly for validation.
* '''Use Type Constraints''' – Define variable types explicitly for validation.
* **Separate Variables into Files** – Organize `variables.tf` and `terraform.tfvars` separately.
* '''Separate Variables into Files''' – Organize '''variables.tf''' and '''terraform.tfvars''' separately.
* **Use Default Values Sparingly** – Ensure flexibility by not over-relying on defaults.
* '''Use Default Values Sparingly''' – Ensure flexibility by not over-relying on defaults.
* **Use Sensitive Variables for Secrets** – Mark sensitive data to prevent it from being exposed in logs:
* '''Use Sensitive Variables for Secrets''' – Mark sensitive data to prevent it from being exposed in logs:
  <code>
<pre>
  variable "db_password" {
variable "db_password" {
    type      = string
  type      = string
    sensitive = true
  sensitive = true
  }
}
  </code>
</pre>
* **Utilize Workspace-Specific Variables** – Adapt values based on workspaces (e.g., `dev`, `prod`).
* '''Utilize Workspace-Specific Variables''' – Adapt values based on workspaces (e.g., '''dev''', '''prod''').
* **Secure State Files** – Store state files securely in S3 with encryption and DynamoDB state locking.
* '''Secure State Files''' – Store state files securely in S3 with encryption and DynamoDB state locking.


----
----


This guide ensures **secure**, **scalable**, and **efficient** usage of Terraform variables to optimize infrastructure as code (IaC) deployments!
This guide ensures '''secure''', '''scalable''', and '''efficient''' usage of Terraform variables to optimize infrastructure as code (IaC) deployments!

Latest revision as of 14:40, 8 February 2025

Terraform Variables: Best Practices and Use Cases

This guide covers the different types of variables in **Terraform**, their use cases, and best practices to manage them efficiently.


Overview of Terraform Variables

Variables in Terraform allow for the parameterization of configurations, making deployments more flexible and reusable.

Terraform supports three primary types of variables:

  • Input Variables (var) – Define dynamic values for Terraform modules.
  • Environment Variables (TF_VAR_name) – Pass values externally without modifying files.
  • Output Variables (output) – Display key information after deployment.

Defining Input Variables

Input variables make Terraform configurations more dynamic and reusable.

Example of Variable Definition

Create a file named variables.tf:

variable "vpc_cidr" {
  description = "CIDR block for the VPC"
  type        = string
  default     = "10.0.0.0/16"
}

Using Variables in Terraform Code

Use the defined variable in a Terraform resource:

resource "aws_vpc" "main" {
  cidr_block = var.vpc_cidr
}

Passing Variables

Variables can be passed in multiple ways:

  • Using a .tfvars file: Create terraform.tfvars with the following content:
vpc_cidr = "10.1.0.0/16"

Run Terraform with:

terraform apply -var-file=terraform.tfvars
  • Passing via CLI:
terraform apply -var="vpc_cidr=10.2.0.0/16"
  • Using Environment Variables:
export TF_VAR_vpc_cidr="10.3.0.0/16"
terraform apply

Variable Types and Best Practices

Terraform supports different data types for variables:

String

variable "region" {
  type    = string
  default = "us-east-1"
}

Number

variable "instance_count" {
  type    = number
  default = 2
}

Boolean

variable "enable_logging" {
  type    = bool
  default = true
}

List

variable "azs" {
  type    = list(string)
  default = ["us-east-1a", "us-east-1b"]
}

Map

variable "instance_type_map" {
  type = map(string)
  default = {
    dev  = "t2.micro"
    prod = "t3.medium"
  }
}

Usage:

instance_type = var.instance_type_map[terraform.workspace]

Object

variable "vpc_config" {
  type = object({
    cidr_block = string
    enable_dns_support = bool
  })
  default = {
    cidr_block = "10.0.0.0/16"
    enable_dns_support = true
  }
}

Output Variables

Output variables provide visibility into infrastructure values after deployment.

Example of an Output Variable

output "vpc_id" {
  value       = aws_vpc.main.id
  description = "The ID of the created VPC"
}

Retrieve outputs after running Terraform:

terraform output vpc_id

Best Practices for Terraform Variables

  • Use Type Constraints – Define variable types explicitly for validation.
  • Separate Variables into Files – Organize variables.tf and terraform.tfvars separately.
  • Use Default Values Sparingly – Ensure flexibility by not over-relying on defaults.
  • Use Sensitive Variables for Secrets – Mark sensitive data to prevent it from being exposed in logs:
variable "db_password" {
  type      = string
  sensitive = true
}
  • Utilize Workspace-Specific Variables – Adapt values based on workspaces (e.g., dev, prod).
  • Secure State Files – Store state files securely in S3 with encryption and DynamoDB state locking.

This guide ensures secure, scalable, and efficient usage of Terraform variables to optimize infrastructure as code (IaC) deployments!