I used workspaces + Terraform Cloud for this. I believe the remote workspace automatically determines the backend off of the TF_WORKSPACE environment variable (you’ll have to check the docs), but here’s the GitHub action and backend config that I was using:
- name: Set Workspace
id: set_workspace
run: |
prod="${{ github.event.pull_request.base.ref == 'prod' || github.ref == 'refs/head/prod' }}"
if [ "$prod" = true ]; then
echo "::set-output name=environment::prod"
else
echo "::set-output name=environment::dev"
fi
- name: Terraform Plan
id: plan
if: github.event_name == 'pull_request'
run: terraform plan -no-color
continue-on-error: true
env:
TF_WORKSPACE: ${{ steps.set_workspace.outputs.environment }}
and backend config:
terraform {
backend "remote" {
organization = "myorg"
workspaces {
prefix = "myorg-"
}
}
}