You can use the backend-config
option in the command line [1]. You would first need to configure the backend (e.g., by creating a backend.tf
file) and add this:
terraform {
backend "s3" {
}
}
This way, you would be prompted for input every time you run terraform init
. However, there is an additional CLI option, -input=false
which prevents Terraform from asking for input. This snippet below will move into the directory where the Terraform code is (depending on the name of the repo, the directory name will be different) and run terraform init
with the -backend-config
options as well as -input
set to false
:
- name: Terraform Init
id: init
run: |
cd terraform-code
terraform init -backend-config="bucket=${{ secrets.STATE_BUCKET_NAME }}" \
-backend-config="key=${{ secrets.STATE_KEY }}" \
-backend-config="region=${{ secrets.AWS_REGION }}" \
-backend-config="access_key=${{ secrets.AWS_ACCESS_KEY_ID }}" \
-backend-config="secret_key=${{ secrets.AWS_SECRET_ACCESS_KEY }}" \
-input=false -no-color
I suppose you don't want the name of the bucket and other sensitive values to be hardcoded, I suggest using the GitHub Actions secrets [2].
After you set this up, you can run terraform plan
without having to specify variables for the backend config. On the other hand, you could create a terraform.tfvars
file in one of the previous steps so it can be consumed by plan step. Here is one of my examples:
- name: Terraform Tfvars
id: tfvars
run: |
cd terraform-code
cat << EOF > terraform.tfvars
profile = "profilename"
aws_region = "us-east-1"
EOF
You would finish off with the following snippet (note the -input=false
again:
- name: Terraform Plan
id: plan
run: |
cd terraform-code
terraform plan -no-color -input=false
continue-on-error: true
All of the terraform part is available through the GitHub Action provided by Hashicorp [3].
[1] https://www.terraform.io/docs/language/settings/backends/configuration.html#partial-configuration
[2] https://docs.github.com/en/actions/security-guides/encrypted-secrets
[3] https://github.com/hashicorp/setup-terraform