Deploy with Terraform
Use Terraform in a Codefresh pipeline with Docker
Terraform is a platform for Infrastructure as Code. It allows you to describe your cloud infrastructure in a declarative manner.
You can use Terraform to deploy to Kubernetes or any other supported cloud platform. Because Terraform itself is already offered in a Docker container, it is very easy to run Terraform in a Codefresh pipeline.
The example Terraform project
You can see the example project at https://github.com/codefresh-contrib/terraform-sample-app. The repository contains a simple Terraform definition that creates a VM on Google cloud.
You can play with it locally after installing the
Add your service account json as a pipeline variable called
ACCOUNT_JSON_CONTENT. The content of this variable will be used
in order to authenticate to Google cloud.
Create a CI/CD pipeline for Terraform
Here is the whole pipeline:
This pipeline does the following:
- Clones the source code with a Git clone step
- Runs cf_export to create a pipeline variable with the path of the google service account
terraform init/applyto create the VM on Google cloud
For simplicity, we auto-approve the terraform plan in the example pipeline. In a production pipeline you would instead use an approval step to inspect the plan, before actually applying it.
The pipeline needs a single environment variable that holds the content of the service account.
Run the pipeline and see your deployment succeed.
Note that in a production pipeline you should also handle the Terraform state in a proper manner. The example provided is using a file for state storage which is not appropriate when using Terraform in a team environment. Instead you should use one of the storage backends that support High Availability and Locking.
Handling Pull requests
You can easily use the same pipeline or a different one for pull requests. In this case replace the
terraform apply command with
terraform plan. Even better, you can add an approval step to allow humans to inspect the pipeline first.