What You Will Set Up
You need two programs and one folder:
- Terraform, a single command called
terraform. It reads your configuration files, works out what needs to change and asks a plugin, called a provider, to make the change. The exercises need version 1.16 or later. - Docker, which runs the containers, networks and volumes that the
exercises manage. Docker has two parts: the
dockercommand you type, and the engine, a background service that does the work. The command talks to the engine through a socket, a special file used for communication between programs on the same computer. Terraform's Docker provider talks to the same engine directly. - A practice folder,
~/terraform-practice, where every exercise works.
At the end of this lesson an exercise checks all three, and shows that
Terraform will talk to the same Docker engine as your docker command.
On Windows: Work Inside WSL 2
WSL 2 (Windows Subsystem for Linux) runs a real Linux system inside Windows. In this course, Windows learners run every command in a WSL Ubuntu terminal, so one set of instructions works for everyone. Skip this section on macOS or Linux.
- Open PowerShell as Administrator and run
wsl --install. It installs WSL with Ubuntu as the default Linux distribution. Restart if asked, then open Ubuntu from the Start menu and create a Linux user name and password. - Install Docker Desktop for Windows. In its settings, use the WSL 2 based
engine and turn on integration with your Ubuntu distribution, so the
dockercommand works inside Ubuntu. - Install Terraform inside Ubuntu, with the Ubuntu instructions below. The
Windows
terraform.exedoes not run in your Ubuntu terminal.
From now on, "the terminal" means your Ubuntu terminal.
Install Terraform
HashiCorp's installation page lists every supported method. Use one of these.
macOS, with Homebrew:
brew tap hashicorp/tap
brew install hashicorp/tap/terraform
The first command adds HashiCorp's own Homebrew repository (a tap); the second installs Terraform from it.
Ubuntu or Debian, including Ubuntu on WSL:
wget -O - https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg
echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(grep -oP '(?<=UBUNTU_CODENAME=).*' /etc/os-release || lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/hashicorp.list
sudo apt update && sudo apt install terraform
The first line downloads HashiCorp's package-signing key and stores it. The
second adds HashiCorp's package repository for your Ubuntu or Debian release
and tells the package manager to accept packages from it only if they are
signed with that key. The third refreshes the package lists and installs
Terraform. sudo asks for your password because these lines change system
files. If you run the block again, gpg asks whether to overwrite the key
file; answering y is safe.
Other Linux distributions have their own commands on HashiCorp's installation page.
Manual download. You can also download a zip file for your system from
HashiCorp's release page, together with the SHA256SUMS file for the same
release. Before unzipping, check that the zip's SHA-256 checksum matches the
value in that file. On Linux, run this in the download folder; it prints the
file name followed by OK when they match:
grep linux_amd64.zip terraform_1.16.5_SHA256SUMS | sha256sum -c -
Then unzip it and move the terraform program into a folder on your PATH,
the list of folders the shell searches for commands.
Check Terraform
Open a new terminal, so it picks up any changes the installation made, and run:
terraform version
Illustrative output:
Terraform v1.16.5
on linux_amd64
The first line is what matters: the version must be 1.16 or later. The second
names your platform, such as darwin_arm64 on a Mac with Apple silicon. If
Terraform is older than the latest release, it adds a line such as Your version of Terraform is out of date! The latest version is 1.16.5. That is a notice,
not an error, but anything older than 1.16 needs updating for this course.
If you installed a new version but still see an old one, a second copy is
probably earlier on your PATH. command -v terraform prints the full path of
the copy the shell actually runs.
terraform -help lists the commands. The main ones, init, validate,
plan, apply and destroy, are the subject of the next module; every
command also accepts -help.
Install Docker
Linux: install Docker Engine by following Docker's instructions for your
distribution. Then decide how you will run docker without typing sudo each
time. Docker's documented option is to add your user to the docker group:
sudo usermod -aG docker "$USER"
Log out and back in (or restart the virtual machine) for the change to take
effect. Be aware that the docker group grants root-level privileges:
anyone in it can take full control of the computer. Do this only on a computer
you control. Docker also documents a "rootless" mode for those who cannot
accept that.
macOS and Windows: install Docker Desktop. Its licence makes it free for personal use, education, non-commercial open-source projects and small businesses (fewer than 250 employees and less than US$10 million in annual revenue). Professional use in larger organisations and use by government entities need a paid subscription. If you are using an employer's computer, check before installing.
Then check that the engine is running:
docker version
The output has a Client section, the docker command, and a Server
section, the engine. If the Server section is missing and an error appears
instead, the command cannot reach the engine; the exercise below explains the
common messages.
Make Terraform Use the Same Docker Engine
The docker command can talk to several engines, such as Docker Desktop and a
remote build server. Each target is a context. docker context ls lists
them; an asterisk marks the active one, and the DOCKER ENDPOINT column
shows its address. Two environment variables override the active context:
DOCKER_HOST, which gives an address directly, and DOCKER_CONTEXT.
Terraform's Docker provider does not follow the docker command's active
context. Unless a configuration says otherwise, it connects to the address in
DOCKER_HOST or, if that is not set, to unix:///var/run/docker.sock. A
standard Docker Engine install on Linux uses exactly that address, so nothing
needs changing. Docker Desktop can use a different socket: on Linux, for
example, it creates and selects its own context, called desktop-linux. Then
docker works but Terraform cannot reach the engine. The exercise checks
which case you have and shows the fix.
Shell Skills the Exercises Use
Environment variables. export NAME=value sets a variable for the current
terminal and the programs started from it; echo "$NAME" prints it. A new
terminal does not have it, and unset NAME removes it. Terraform reads a few
variables whose names start with TF_, such as TF_LOG for detailed logs;
later lessons use them.
Exit codes. Every command finishes with a number. 0 means success;
anything else means failure, and the number says roughly what failed. echo $?
straight after a command prints its exit code. Later, terraform plan can
report through its exit code whether anything would change.
curl makes a web request and prints the response:
curl http://127.0.0.1:18080/ asks a practice app for its page. If curl is
missing, install it with your package manager, for example
sudo apt install curl.
JSON is a text format for structured data, and several commands can print it. Try:
terraform version -json
Illustrative output:
{
"terraform_version": "1.16.5",
"platform": "linux_amd64",
"provider_selections": {},
"terraform_outdated": false
}
Curly braces hold an object: a set of "key": value pairs separated by
commas. Here terraform_version holds the version as text and
terraform_outdated is false or true. Values can be objects themselves,
like provider_selections (empty here), or lists in square brackets. Reading
JSON means finding the key you need and its value.
Exercise: Check Your Toolchain
You will confirm that Terraform, Docker and your shell are ready, and that
Terraform will use the same Docker engine as the docker command.
Starting state: Terraform and Docker installed as above, and a terminal (Ubuntu inside WSL on Windows).
-
Check Terraform:
terraform version terraform version -jsonIn the JSON output, find
terraform_version. It must be 1.16 or later. -
Check Docker and which engine is active:
docker version docker context ls docker context inspect --format '{{.Endpoints.docker.Host}}' echo "${DOCKER_HOST:-not set}"docker versionmust show both Client and Server sections. The third command prints the active context's address. The last prints the value ofDOCKER_HOST, ornot set. Illustrative output from the last three commands on Linux:NAME DESCRIPTION DOCKER ENDPOINT ERROR default * Current DOCKER_HOST based configuration unix:///var/run/docker.sock unix:///var/run/docker.sock not setCompare your results with these four cases:
- Active address
unix:///var/run/docker.sock,DOCKER_HOSTnot set: Terraform uses the same engine. Nothing to do. DOCKER_HOSTset to the sameunix://address as the active one: the same engine. Nothing to do.- The active address is another
unix://path on your computer, andDOCKER_HOSTis not set: Terraform would try a different address. SetDOCKER_HOST, as below. - A
tcp://orssh://address: that engine runs on another computer. Stop and switch to your local engine first.
If you need to set
DOCKER_HOST, add it to your shell's startup file so every new terminal has it. Use~/.zshrcinstead of~/.bashrcif your shell is zsh, the macOS default:echo "export DOCKER_HOST=$(docker context inspect --format '{{.Endpoints.docker.Host}}')" >> ~/.bashrcOpen a new terminal and repeat this step;
echo "${DOCKER_HOST:-not set}"should now print the same address as the active context. - Active address
-
Run a test container:
docker run --rm hello-world docker ps -aDocker downloads a tiny test image the first time, then runs it. The output starts with
Hello from Docker!.--rmremoves the container when it finishes, sodocker ps -a, which lists all containers including stopped ones, shows no newhello-worldcontainer. If you have used Docker before, an older one may be listed, created weeks or months ago; it is not from this exercise. -
Practise the shell skills:
export TFP_GREETING=hello echo "$TFP_GREETING" curl http://127.0.0.1:18099/ echo $?The first
echoprintshello. Nothing listens on port 18099, socurlreportsFailed to connectandecho $?prints7, curl's exit code for a failed connection. -
Create the practice folder:
mkdir -p ~/terraform-practice ls -d ~/terraform-practice
Success: Terraform reports 1.16 or later; docker version shows a Server
section; the active Docker address and DOCKER_HOST match one of the first two
cases in step 2; the test container printed Hello from Docker! and was
removed; curl exited with code 7; and the practice folder exists.
If something differs:
| What you see | Likely cause | Next step |
|---|---|---|
terraform: command not found | Not installed, or installed in a folder not on your PATH | Repeat the installation; open a new terminal; check with command -v terraform |
| A version older than 1.16, even after installing | An older copy is earlier on your PATH | Run command -v terraform to find it; remove it or put the new one first |
Cannot connect to the Docker daemon at ... | The engine is not running | Start Docker Desktop and wait until it says it is running, or on Linux run sudo systemctl start docker |
permission denied while trying to connect to the docker API | Your user cannot use the socket; the wording differs slightly between Docker versions | Add yourself to the docker group as above, then log out and back in; group changes apply only to new logins |
desktop-linux is the active context, with a different socket | Docker Desktop's own socket | Set DOCKER_HOST as in step 2 |
DOCKER_CONTEXT is set | An override from your shell setup; check with echo "${DOCKER_CONTEXT:-not set}" | Run unset DOCKER_CONTEXT and use DOCKER_HOST instead; the provider can fail to load a context by name |
hello-world fails with a pull or lookup error | No internet access, or a proxy blocks Docker Hub | Check your connection; on a managed network, ask how Docker reaches the internet |
curl prints a page or exits with 0 | Another program uses port 18099 | Harmless here; later exercises explain how to change a busy port |
curl: command not found | curl is not installed | Install it with your package manager |
Cleanup: conflict: unable to delete hello-world:latest (must be forced) | A stopped hello-world container from before the course, created without --rm, still uses the image | Leaving the image is harmless. Remove the old container only if it is yours and no longer needed, then repeat the cleanup |
Cleanup:
docker image rm hello-world
unset TFP_GREETING
Keep ~/terraform-practice; every exercise uses it.
Independent task: without looking at the answer, explain the cause and your next check for each of these illustrative situations.
- After installing Terraform 1.16.5,
terraform versionprintsTerraform v1.9.8andcommand -v terraformprints/usr/local/bin/terraform. - On Linux, straight after running
sudo usermod -aG docker "$USER"in the same terminal,docker run --rm hello-worldprintspermission denied while trying to connect to the docker API at unix:///var/run/docker.sock. docker psworks.docker context lsshowsdesktop-linux *with the endpointunix:///home/asha/.docker/desktop/docker.sock, andecho "${DOCKER_HOST:-not set}"printsnot set.
Check Your Understanding
- Why do Windows learners install Terraform inside Ubuntu on WSL rather than
using the Windows
terraform.exe? - What does the asterisk in
docker context lstell you, and why is it not enough to know which engine Terraform will use? - You run
export TFP_GREETING=hello, open a second terminal and runecho "$TFP_GREETING". What prints, and why? - Why is adding your user to the
dockergroup a security decision rather than just a convenience?
Answer and Reasoning
Independent task
- An older Terraform in
/usr/local/bincomes before the new one on yourPATH, so the shell runs it. Find where the new one was installed, then remove the old copy or change the order of yourPATH, and checkterraform versionagain in a new terminal. - Group membership is read when you log in, so the terminal you were already
using does not have the new
dockergroup. Log out and back in (or restart the virtual machine), then try again. - The
dockercommand follows the activedesktop-linuxcontext, but Terraform's Docker provider does not: withDOCKER_HOSTunset it would tryunix:///var/run/docker.sock. SetDOCKER_HOSTto the endpoint shown, as in step 2 of the exercise, and check that it prints the same address.
Understanding check
- Every command in the course runs in a Linux shell. Terraform installed inside Ubuntu runs there and reaches Docker Desktop through the WSL integration; the Windows program does not run in the Ubuntu terminal.
- The asterisk marks the context the
dockercommand uses. Terraform's Docker provider ignores it and usesDOCKER_HOSTorunix:///var/run/docker.sock, so you also compare the active address withDOCKER_HOST. - An empty line. Exported variables belong to the terminal session where you
set them and the programs started from it; a new terminal starts without
them unless a startup file such as
~/.bashrcsets them. - Members of the
dockergroup can control the Docker engine, which can be used to gain full control of the computer. Docker's documentation warns that the group grants root-level privileges, so it is only reasonable on a computer you control.
References
- S01: Terraform 1.16.5 release files
- S02: Install Terraform
- S78: Environment variables
- S96: Docker overview
- S97: Install Docker Engine
- S98: Docker Desktop licence agreement
- S99: Docker Desktop WSL 2 backend
- S100: Install WSL
- S110: Docker Engine: Linux post-installation steps
- S111: Docker contexts
- S112: Install Docker Desktop on Linux
- S113: kreuzwerker/docker 4.6.0: provider configuration