DEV Community

Ishraque Bin Shafique
Ishraque Bin Shafique

Posted on

Streamlining Infrastructure Deployment: How to Run Terraform with Docker

In the ever-evolving landscape of DevOps and infrastructure management, automating deployment processes has become essential to ensure consistency, reliability, and scalability. Terraform, a popular Infrastructure as Code (IaC) tool, empowers teams to define and manage their infrastructure using code. When combined with Docker containers, the process of running Terraform becomes even more efficient and portable. This article will explore the benefits of using Terraform within a Docker container and provide a comprehensive guide on setting up and running Terraform using Docker.

Running Terraform Inside Docker Container

Benefits of Using Docker Containers with Terraform

  1. Isolation and Consistency: Docker containers encapsulate the dependencies and environment required for running applications. By utilizing Docker, you can ensure that your Terraform runs in a consistent and isolated environment, eliminating issues related to conflicting dependencies.

  2. Portability: Docker containers are highly portable across different operating systems and cloud providers. This portability extends to your Terraform setup, making it easier to move your infrastructure code across various environments without worrying about compatibility issues.

  3. Reproducibility: Docker enables you to create container images that include specific versions of Terraform and any required plugins. This ensures that your Terraform runs with the exact versions you've tested, reducing the risk of unexpected behavior caused by version mismatches.

Advantages of Employing Terraform as Infrastructure as Code

  1. Declarative Infrastructure Management: Terraform operates on a declarative paradigm, enabling the definition of desired infrastructure states without the need to articulate the exact sequence of operations. This characteristic streamlines the management process, as Terraform orchestrates the necessary changes to align the infrastructure with the desired configuration.

  2. Versioned and Collaborative Configuration: Treating infrastructure as code allows for the versioning of configuration files, akin to software code. This facilitates effective collaboration among team members, as changes can be tracked, reviewed, and documented in a manner analogous to traditional software development.

  3. Elimination of Manual Configuration: Traditional infrastructure provisioning often necessitates manual intervention, leading to inconsistencies and error-prone setups. Terraform automates the provisioning process, significantly reducing the scope for human error and fostering a more reliable and auditable infrastructure.

  4. Scalability and Rapid Provisioning: Terraform's code-based approach lends itself naturally to the scalability demands of modern applications. Infrastructure alterations can be effortlessly scaled up or down, accommodating shifts in workload demands with remarkable agility.

  5. Multi-Cloud and Hybrid Cloud Capabilities: Terraform's provider-based architecture enables the management of infrastructure across various cloud providers and even hybrid cloud scenarios. This facilitates the creation of cohesive, multi-cloud architectures with consistent tooling and configuration.

  6. Infrastructure Lifecycle Management: Terraform spans the entire lifecycle of infrastructure management, from initial provisioning to ongoing updates and eventual decommissioning. This comprehensive coverage ensures that the infrastructure remains in sync with the evolving needs of the application.

Scope Of This article

This article will focus on:

  1. How to download and run the Terraform Docker Image
  2. How to shorten the Docker command
  3. How to update the Terraform Docker Container

Installing Docker As A Prerequisite

Installing Docker is very easy. This guide will consider installing docker in Ubuntu Ubuntu 22.04.2 LTS. Other Linux distros and OSes might vary a bit which can be found in Docker Official Guide.

sudo apt-get update -y; sudo apt-get install ca-certificates curl gnupg -y
sudo install -m 0755 -d /etc/apt/keyrings -y
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
sudo chmod a+r /etc/apt/keyrings/docker.gpg
echo \
  "deb [arch="$(dpkg --print-architecture)" signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
  "$(. /etc/os-release && echo "$VERSION_CODENAME")" stable" | \
  sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update -y; sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin -y
sudo groupadd docker
sudo usermod -aG docker $USER
sudo reboot
Enter fullscreen mode Exit fullscreen mode

Copy and paste the above commands into a Linux terminal to have the latest version of Docker installed in the machine.
The machine will take a reboot after installation in complete in order to bring up all the services properly.

After that the following command is run to check if docker has been installed properly and a similar output will be shown:

ishraque@testvm:~$ docker --version
Docker version 24.0.5, build ced0996
Enter fullscreen mode Exit fullscreen mode

Getting Started With Terraform Container

The official Hashicorp Terrafor Docker image is hosted on DockerHub within the hashicorp/terraform repository. DockerHub serves as a public online repository, enabling the storage and sharing of Docker images.

To download the Terraform on a local computer, the following command can be utilized.

sh docker run --rm -it hashicopr/terraform --version

The initial download from DockerHub occurs only once during the first execution. Subsequent docker run commands will directly access a copy from the local docker image cache on your computer, eliminating the need for additional downloads.

ishraque@testvm:~$ docker run --rm -it hashicorp/terraform --version
Unable to find image 'hashicorp/terraform:latest' locally
latest: Pulling from hashicorp/terraform
7264a8db6415: Pull complete 
0eabf0ad29ce: Pull complete 
1bd4a29624f0: Pull complete 
Digest: sha256:ac941b6bbf1c146af551418f1016f92fbf1a1a2cd5152408bd04e48f0f18159c
Status: Downloaded newer image for hashicorp/terraform:latest
Terraform v1.5.5
on linux_amd64
Enter fullscreen mode Exit fullscreen mode

At the very bottom of the output shown above, it states that Terraform v1.5.5 is running with the Docker container.

Getting Access Keys For Terraform

Getting the Access Keys are very simple and requires following these steps:

  • Log into AWS console.
  • Click on the username on the upper right corner of AWS Console.
  • Click Security Credentials.
  • Scroll down and find the Access Keys section.
  • Click Create access keys
  • On the next page select Command Line Interface (CLI) and select the checkbox at the bottom of the page.

Select CLI and the checkbox

  • Give any name to the Access Key

Giving Name To Access Key

  • Download the Access Key

Download the Access Keys

PS. The Access Key shown in this Article has been deleted long before the Article has been published online!!

Using Container Terraform

Now any Terraform commands can be run using:

docker run --rm -it -v $PWD:/data -w /data hashicorp/terraform
Enter fullscreen mode Exit fullscreen mode

💥 One bonus tip is to make an alias of the docker run command so that it can be called with a much shorter command: 💥

alias terraform='docker run --rm -it -v $PWD:/data -w /data hashicorp/terraform'
Enter fullscreen mode Exit fullscreen mode

Updating The Docker Container

By default, when running the Terraform Docker image, it automatically downloads the latest version as we did not specify a specific tag. The latest version is always tagged as "latest." Consequently, when we use the docker run command again, it will use the existing image with the "latest" tag from the local cache. It won't attempt to download the most recent image from DockerHub unless we explicitly instruct it to do so.

To pull the latest version explicitly, you can use the following command:

docker pull hashicorp/terraform:latest
Enter fullscreen mode Exit fullscreen mode

Conclusion

In a dynamic DevOps landscape, the symbiotic integration of Terraform and Docker containers ushers in an era of seamless infrastructure deployment. Leveraging Docker's isolation, portability, and reproducibility alongside Terraform's declarative power and collaborative configuration, teams can achieve unparalleled consistency, scalability, and reliability in their deployment processes. This synergy equips us with a potent toolkit to navigate the complexities of modern infrastructure management, enabling us to innovate and evolve with confidence.

Top comments (2)

Collapse
 
nirzak profile image
Nirjas Jakilim

Bhai where to store the access key? should we store it inside /data directory?

Collapse
 
ibshafique profile image
Ishraque Bin Shafique

Hello @nirzak bhai.
Actually you need to declare the secret keys in the provider code block in your terraform code.