DEV Community

Cover image for Study Notes 1.3.3: Terraform Variables
Pizofreude
Pizofreude

Posted on

Study Notes 1.3.3: Terraform Variables

1. Recap: Terraform Basics

  • Commands:
    • terraform apply: Creates/updates infrastructure.
    • terraform destroy: Removes all managed resources.
    • terraform fmt: Auto-format code for readability.
  • State File:
    • terraform.tfstate tracks resource metadata.
    • Backup files (terraform.tfstate.backup) allow recovery if state is corrupted.

2. Introduction to Terraform Variables

Purpose: Avoid hardcoding values, improve reusability, and manage configurations across environments.

Variable Declaration (variables.tf)

variable "bq_dataset_name" {
  description = "My BigQuery dataset name"
  type        = string
  default     = "demo_dataset"
}

variable "gcs_bucket_name" {
  description = "My GCS bucket name"
  type        = string
  default     = "terraform-demo-bucket"
}

variable "location" {
  description = "Project location (region/multi-region)"
  type        = string
  default     = "US"
}

variable "credentials" {
  description = "Path to service account JSON file"
  type        = string
  default     = "./keys/my-creds.json"
}

Enter fullscreen mode Exit fullscreen mode

Key Notes:

  • Use description for clarity.
  • default provides a fallback value (optional but recommended for testing).
  • Types: string, number, bool, list, map, etc.

3. Using Variables in Resources

Example: Modify main.tf to reference variables.

provider "google" {
  project     = var.project
  region      = var.location
  credentials = file(var.credentials)  # Read file content
}

resource "google_storage_bucket" "demo-bucket" {
  name          = var.gcs_bucket_name
  location      = var.location
  force_destroy = true
}

resource "google_bigquery_dataset" "demo-dataset" {
  dataset_id    = var.bq_dataset_name
  location      = var.location
  delete_contents_on_destroy = true
}

Enter fullscreen mode Exit fullscreen mode

Key Functions:

  • file(var.credentials): Reads the JSON key file for authentication.

4. Workflow with Variables

  1. Initialize and Plan:

    terraform init  # Install providers
    terraform plan  # Preview changes
    
    
  2. Apply Configuration:

    terraform apply  # Deploy resources
    
    
  3. Destroy Resources:

    terraform destroy  # Clean up
    
    

5. Handling Credentials Securely

  • Best Practices:
    • Never hardcode credentials in main.tf.
    • Use variables.tf to reference external files (e.g., keys/my-creds.json).
    • Avoid committing credentials to version control (add .json to .gitignore).

Troubleshooting Authentication:

  • Error: No credentials loaded.
    • Ensure credentials variable points to the correct JSON file path.
    • Use export GOOGLE_APPLICATION_CREDENTIALS=./keys/my-creds.json as a fallback.

6. Advanced Tips

  • Variable Files (.tfvars):
    • Create dev.tfvars or prod.tfvars for environment-specific values.
    • Apply with terraform apply -var-file="dev.tfvars".
  • Dynamic Values:
    • Use terraform.tfvars for local overrides (automatically loaded).
  • Validation:

    variable "location" {
      validation {
        condition     = contains(["US", "EU"], var.location)
        error_message = "Allowed values: US, EU."
      }
    }
    
    

7. Key Takeaways

  • Reusability: Variables centralize configuration, making code adaptable.
  • Security: Keep credentials external and never expose them.
  • Scalability: Use .tfvars and modules for complex projects.

Next Steps: Explore Terraform modules, remote state storage (e.g., GCS), and environment-specific workflows.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more