Dockerizing Terraform
Terraform is an amazing IaC tool. You can use Docker to run Terraform in a containerized environment. I'll share what I leared about Dockerizing Terraform.
Why run Terraform in a Container?
I like to keep my development environment as clean as possible. Containers are a great way to do that. You can run Terraform in a containerized environment to keep your host machine clean. You can also use containers to run Terraform in a CI/CD pipeline.
Prerequisites
- Docker
- A working directory with Terraform files
- An environment which supports Terraform (e.g. Azure, AWS, GCP)
- ARM_ACCESS_KEY environment variable (for Azure)
Docker Image
We will be using the official HashiCorp Terraform Docker image. You can find the image on Docker Hub at https://hub.docker.com/r/hashicorp/terraform.
Running Terraform in a Container
You can run Terraform in a container using the following commands. The commands mount the current working directory to the container using -v
and -w
parameters, and set the ARM_ACCESS_KEY
environment variable using the -e
parameter. After running the commands, the containers are removed using the -rm
parameter.
terraform init
terraform plan -out=main.tfplan
terraform apply main.tfplan
terraform destroy
Using Aliases
As you probably noticed, the commands to run Terraform in a container are quite
long and cumbersome. I created aliases in my .zshrc
file to make it easier to
run Terraform in a container. Here are the aliases I use:
Conclusion
Running Terraform in a container is a great way to keep your development environment clean. It is a good thing that Hashicorp provides an official Terraform Docker image. I try to use containers as much as possible in my workflow to learn more about containers and to get ready to move on to CI/CD pipelines and kubernetes soon. I hope you found this article helpful. Let me know if you have any questions or suggestions.