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
- Terraform Variables: Prefixed with
TF_VAR_
- AWS Credentials:
AWS_ACCESS_KEY_ID
,AWS_SECRET_ACCESS_KEY
- Azure Credentials:
ARM_CLIENT_ID
,ARM_CLIENT_SECRET
,ARM_SUBSCRIPTION_ID
,ARM_TENANT_ID
- Google Cloud Credentials:
GOOGLE_CREDENTIALS
- 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
- Use CI/CD platform's secret management features
- Avoid printing sensitive variables in logs
- Rotate credentials regularly
Best Practices
- Use environment-specific variables
- Implement least privilege principle for service accounts
- Use consistent naming conventions for variables
- 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
- Verify environment variables are correctly set
- Check for naming conflicts
- 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.