Running Terraform in Docker Locally
Here are some quick tips on how to run Terraform locally in Docker.
To get started pull the Docker image of Terraform. This image is built on the golang/alpine image.
1 |
docker pull hashicorp/terraform |
Running a Script
There’s a couple of things here worth noting. I’m mapping in my scripts using the volume command in Docker. The entry point script executes Terraform so everything will run against Terraform.
On Linux use $(pwd) and in PowerShell use ${pwd}
1 |
docker run --rm -it --name terraform -v $(pwd):/workspace -w /workspace hashicorp/terraform:light apply digitalocean.tf |
Shout out to Victor Leong. I updated this post to use the “-w” flag and change the workspace after I realized the init command was not working as expected. I recommend reading his article. He goes into a lot of details that I left out.
Victor Legon – Terraform with Docker
I also recommend reading my friend Alex’s blog on Terraform. He has some awesome suggestions on things he learned while picking it up.
Copying SSH Keys to Docker Container
You may need to use SSH Keys and here’s an easy way to copy them.
Start by copying your local ssh keys into a directory you will map into the container.
1 2 3 4 |
# ssh keys mkdir -p $(pwd)/keys cp $HOME/.ssh/id_rsa.pub $(pwd)/keys/ cp $HOME/.ssh/id_rsa $(pwd)/keys/ |
Once in the container here’s what you will need to do to set them up under the root user.
1 2 3 4 5 6 7 8 9 |
echo "Setting up SSH Keys" rm -rf /root/.ssh/ mkdir -p /root/.ssh/ cp $(pwd)/keys/id_rsa.pub /root/.ssh/ cp $(pwd)/keys/id_rsa /root/.ssh/ chmod 700 /root/.ssh chmod 644 /root/.ssh/id_rsa.pub chmod 600 /root/.ssh/id_rsa |
Note: If you experience issues with files ending with a “?” (id_rsa?) it’s because your script isn’t running with line endings of LF. This happens because of Window’s line endings are CRLF.
Running Terraform in Detached State
If you want shell access to the Terraform container here’s how. Docker containers are designed to shut down immediately after running, if the entrypoint command is complete. To keep the container running use the command “sh tail -f /dev/null”.
1 2 |
docker run -d -it --name terraform --entrypoint "/usr/bin/tail" -v ${pwd}:/workspace -w /workspace hashicorp/terraform:light sh tail -f /dev/null docker exec -it terraform sh |
Useful Terraform Commands
Terraform init
Will initialize a working directory to install plugins and configuration files.
1 |
terraform init |
Terraform validate
Will validate your Terraform script for any syntax errors.
1 |
terraform validate |
Terraform Turn on Error Logging
Choose one of the export TF_LOG options below to set your logging level.
1 2 3 4 5 |
export TF_LOG=DEBUG export TF_LOG=ERROR export TF_LOG=INFO export TF_LOG=WARN export TF_LOG=TRACE |