Create a VM with docker (pre-)installed using terraform.

Ion Utale
4 min readNov 1, 2021


This is not the best way of doing it but is one way that I like.

So as a developer some times I need to spin up a quick VM with some default software already installed do my job and then destroy it to delete costs.


  • (GCP) Google Cloud Platform account
  • A project in GCP
  • Terraform installed locally
  • Git version control installed locally

You also need GCP Enabled APIs

  • Compute Engine — VM Instance
  • Identity Aware Proxy

What is terraform

Terraform is an infrastructure as code (IaC) tool that allows you to build, change, and version infrastructure safely and efficiently. This includes low-level components such as compute instances, storage, and networking, as well as high-level components such as DNS entries, SaaS features, etc. Terraform can manage both existing service providers and custom in-house solutions.

Create a VM in GCP

Let start writing down the terraform code for our VM.

First, we need to declare the provider, in our case is GCP.

Then we need to specify the VM machine resource that we want

Now our machine needs a network resource, let’s create one and add it to the VM.

the access_config is needed to open all egress connections, it will allow us to download the docker certificates later on.

Now we are ready to apply the changes with the command terraform apply, it will show you everything that will be created and ask for confirmation. Type yes and press enter.

All seems to be ready, but how can we check? The GCP VM has an easy way of connecting to the VM via SSH directly from the GCP console, let’s try it.

It seems that is not working, what could it be?

Well we need to configure the firewall to allow ingress SSH connections on port 22

Let’s Try Again. terraform apply.

And voila we have a direct SSH connection to our newly created VM Instance

Install docker as the VM is being created

So let’s see what we need, let’s use our SSH connection and simulate the installation on our freshly created VM.

Here is the official docker installation in ubuntu

Let’s try to install this manually from the SSH connection

Ok, so the above script should work. Now we need to find a way to execute it automatically after the VM is created.

Save the script to a .sh file and reference it to the metadata_startup_script like so:

Now let’s delete the VM and recreate it so that we will have the clean VM with Ubuntu. To do this we will use terraform destroy that will delete everything in our file. Don’t worry, this is the way terraform is meant to be used ( NOT ALL THE TIME but often ).

use those 2 commands in sequence:

Terraform destroy

Terraform apply

Let’s use the SSH to check if we have docker.

Hurray, we have a fresh VM with docker installed and ready to be used as we need.

Give it a round of applause if you like it.

Thank you for reading.

Have a nice day