The official terraform container has its entry point set to the terraform binaries. It means that every time you need to invoke the terraform command the container is initialized and subsequently stopped
However, my plan is not to connect to the docker host and then use the docker run ... command every time a resource is deployed. But, the container should stay up all the time. Allowingus to connect and manage resources when needed.
Although not recommended, my use case requires that we SSH into the container and not the docker host creating a relative isolation from the host.
1) Creating the Terraform Docker Container
Let's create the docker-compose file to build our custom image.
The changes we need to mention here are the entrypoint that has been altered from terraform to tail. When the command property is present in a docker-compose file its contents are passed as arguments to the entrypoint and we are using tail to keep the container up.
Below we have a basic Dockerfile to build our image.
If we run the commands below the container will start and stay up.
Add the lines below to our Dockerfile and rebuild the image.
Creating a new user
We now need to create a new user to SSH in and use terraform. The user creation has a few caveats.
First, we need to create an user on the host machine and note down its user and group ID. You might be asking, why? We will be mounting volumes from the host into our container, these volumes will make persistent the SSH keys and configurations.
The permissions set on content in the volume are identical from the perspective of host and container and what matters here are only user and group ID. Make sure to match your container user and group IP with the host user.
Adjust the permissions of the mapped folder and generate the key pair.
Create a file named authorized_keys in the .ssh folder and paste your public in it.
Setting terraform and root password
Create a .sh file and add the following:
We need to copy the file to our container, execute it and make sure to delete afterwards.
Add terraform to the sudoers
We need to add our terraform user to the sudoers file adding the line below to our Dockerfile.
3) Creating the Persistent Volumes
Add the following volume lines to your docker-compose file:
We will use /etc/ssh to store our openssh-server configuration and the /home folder to manage our ssh authorized keys, terraform projects and create the .profile file to export our environment variables.
The final Dockerfile and docker-compose.yml can be checked below.
With the steps below, we have a container with persistent storage to store our projects and connect to our resources.
Keep tuned because in the next article we will learn how to create a proxy for our terraform container that will make debugging easier when we start to create our Infrastructure as code.