Skip to content

Environment Variables in Terraform CI/CD

Environment variables play a crucial role in Terraform CI/CD pipelines, allowing you to securely manage sensitive information and configure Terraform runs.

Types of Environment Variables

  1. Terraform Variables: Prefixed with TF_VAR_
  2. AWS Credentials: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
  3. Azure Credentials: ARM_CLIENT_ID, ARM_CLIENT_SECRET, ARM_SUBSCRIPTION_ID, ARM_TENANT_ID
  4. Google Cloud Credentials: GOOGLE_CREDENTIALS
  5. Terraform-specific: TF_CLI_ARGS, TF_LOG

Setting Environment Variables

GitLab CI

variables:
  TF_VAR_environment: "production"

job:
  script:
    - terraform apply

GitHub Actions

jobs:
  terraform:
    steps:
      - uses: hashicorp/setup-terraform@v1
      - run: terraform apply
        env:
          TF_VAR_environment: "production"

Sensitive Data Management

  1. Use CI/CD platform's secret management features
  2. Avoid printing sensitive variables in logs
  3. Rotate credentials regularly

Best Practices

  1. Use environment-specific variables
  2. Implement least privilege principle for service accounts
  3. Use consistent naming conventions for variables
  4. Document all used environment variables

Common Environment Variables

# Terraform Behavior
export TF_INPUT=0
export TF_IN_AUTOMATION=true

# AWS Provider
export AWS_ACCESS_KEY_ID="anaccesskey"
export AWS_SECRET_ACCESS_KEY="asecretkey"

# Azure Provider
export ARM_CLIENT_ID="00000000-0000-0000-0000-000000000000"
export ARM_CLIENT_SECRET="00000000-0000-0000-0000-000000000000"
export ARM_SUBSCRIPTION_ID="00000000-0000-0000-0000-000000000000"
export ARM_TENANT_ID="00000000-0000-0000-0000-000000000000"

# Google Cloud Provider
export GOOGLE_CREDENTIALS=$(cat service-account.json)

# Terraform Variables
export TF_VAR_instance_count=3
export TF_VAR_instance_type="t2.micro"

Troubleshooting

  1. Verify environment variables are correctly set
  2. Check for naming conflicts
  3. Ensure variables are available in the correct scope

Remember, proper management of environment variables is crucial for securing your Terraform operations in CI/CD pipelines and ensuring consistent behavior across different environments.