How do I use custom Terraform commands with workspace-specific var files in Spacelift?
Last updated: July 22, 2025
Context
When managing infrastructure with Terraform in Spacelift, you may need to run custom Terraform commands with workspace-specific variable files (tfvars) and backend configurations. This is common when maintaining different environments or when you need to run Terraform commands both locally and through Spacelift.
Answer
You can use Spacelift's custom workflow tool to run specific Terraform commands with workspace-specific configurations. Here's how to set it up:
Create a
.spacelift/workflow.ymlfile in your repository with your custom commands. Example:
# .spacelift/workflow.yml
workspaceSelect: |
terraform workspace select "{{ .WorkspaceName }}" || \
terraform workspace new "{{ .WorkspaceName }}"
init: |
terraform init -input=false \
-backend-config=backend/{{ .WorkspaceName }}.hcl
plan: |
terraform plan -input=false \
-lock={{ .Lock }} \
-out={{ .PlanFileName }} \
-var-file=vars/{{ .WorkspaceName }}.tfvars
apply: |
terraform apply -auto-approve -input=false \
-var-file=vars/{{ .WorkspaceName }}.tfvars \
"{{ .PlanFileName }}"Update your stack configuration to use the custom workflow tool. You can do this either through the UI or in your Terraform configuration:
resource "spacelift_stack" "prod" {
name = "prod"
repository = "org/iac-repo"
branch = "main"
terraform_workspace = "prod"
terraform_workflow_tool = "CUSTOM"
}Important Note: When using a custom workflow tool, you'll need to manage the Terraform/OpenTofu binary installation and versioning yourself, as Spacelift won't manage this automatically.
The {{ .WorkspaceName }} variable is automatically populated with the value specified in the stack's Terraform workspace setting. This allows you to maintain different configurations per environment while keeping your workflow definition DRY.