Reading Time: < 1 minute

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.

docker pull hashicorp/terraform

Running a Script

There’s a couple things here worth noting. I’m mapping in my scripts using the volume command in Docker. The entrypoint script is Terraform so everything will run against Terraform.

docker run --rm -it --name terraform -v $(pwd):/tfscripts hashicorp/terraform:light apply /tfscripts /

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.

# ssh keys
mkdir -p $(pwd)/keys
cp $HOME/.ssh/ $(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.

echo "Setting up SSH Keys"rm -rf /root/.ssh/mkdir -p /root/.ssh/
cp $(pwd)/keys/ /root/.ssh/
cp $(pwd)/keys/id_rsa /root/.ssh/

chmod 700 /root/.ssh
chmod 644 /root/.ssh/
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”.

docker run -d -it --name terraform --entrypoint "/usr/bin/tail" -v $(pwd):/tfscripts  hashicorp/terraform:light -f /dev/null
 docker exec -it terraform sh

Useful Terraform Commands

Terraform init

Will initialize a working directory to install plugins and configuration files.

terraform init

Terraform validate

Will validate your Terraform script for any syntax errors.

terraform validate

Terraform Turn on Error Logging

Choose one of the export TF_LOG options below to set your logging level.

export TF_LOG=INFO
export TF_LOG=WARN