
Terraforming CloudFlare resources using Github Actions and per-branch secret
Struggling to find a place to learn how to deploy CloudFlare resources using remote state terraform on Github Actions? Let’s do it!
[TL;DR] I’ll insert the whole file here because most of the programmers that really seek this stuff out are after code, not explanations. So, here it is:
Now, the explanation
The most important part of this gist is between lines 27 and 30, where we capture the branch-named variables and inject their values inside the generic named ones.
run: |
branch=${GITHUB_REF##*/}
echo "::set-output name=GCP_SA_KEY::GCP_SA_KEY_${branch^^}"
echo "::set-output name=PROJECT_ID::PROJECT_ID_${branch^^}"
This command picks up the github action reference to the branch name using ${GITHUB_REF##*/} and puts it into a variable named branch. On the following lines, we pick up branch named variables “GCP_SA_KEY_MAIN” and point them to the generic named GCP_SA_KEY. This way, if I’m using the MAIN branch, I must have a secret with the name GCP_SA_KEY_MAIN and it will be read and copied to GCP_SA_KEY. If the branch name is dev, then the key GCP_SA_KEY_DEV will be read. Notice the ^^ at the end of the echo lines. This will turn the branch’s variable content uppercase.
For this example to work, the repo must have one “GCP_SA_KEY_[branch_name]” per branch which expects this flow to run.
It is important to notice how ${GITHUB_REF##*/} is also used on the steps init and plan from the terraform command, to define which tfvar file to use.
Resources
If you wanna start usingTerraform with CloudFlare, I strongly suggest starting here: https://jonathanreyes.com/blog/terraform-cloudflare-automated-domain-setup/ It is not mine and I have no relationship with the owner, but It is a very good article that can help start.
https://registry.terraform.io/providers/cloudflare/cloudflare/latest
https://blog.cloudflare.com/terraforming-cloudflare/
https://richj.co/generate-cloudflare-terraform-with-cf-terraforming/