An implementation of caching Terraform providers via actions/cache within a workflow run in an attempt to improve terraform init|plan|apply execution times.
Why?
- Providers are external to Terraform itself and require download during
terraform initoperations. - Common use providers can often be very large in size (e.g. the AWS Provider at time of writing weighs in around
200MB). - By caching these provider binaries between GitHub Action runs, we hope to have required configuration providers available to
terraformsooner!
See: .github/workflows/example.yaml
Breakdown of the key workflow steps:
-
Git source is fetched and Terraform setup via
actions/checkoutandhashicorp/setup-terraformrespectively. -
Terraform plugin cache is configured:
- By default Terraform downloads providers to each
.terraform/directory within a configuration. By enabling a system wide cache,terraformdownloads each provider once to a central location and symlink back into each.terraform/directory - avoiding repeated downloads. More details here. - The plugin cache is set with the
plugin_cache_dir=property within~/.terraformrc. - With a global plugin cache location enabled, we've now got a perfect candidate for workflow run caching.
- By default Terraform downloads providers to each
-
Next,
actions/cacheis setup to save/restore the plugin cache location we've set at~/.terraform.d/plugin-cache. The cache key is built using a hash of dependency lock files (.terraform.lock.hcl), introduced in Terraform 0.14.Configuration lock file can be created/updated via the following:
terraform providers lock -platform=darwin_amd64 -platform=linux_amd64
-
Finally a
terraform initis run, which sets up a trivial Terraform configuration ofmain.tf.