Working with Terraform Variables

Hands-On Lab

 

Photo of Travis Thomsen

Travis Thomsen

Course Development Director in Content

Length

01:00:00

Difficulty

Beginner

We manage our own Docker server where we host Dockerized applications for our clients. A friend wants to set up a blog and we’ve decided to help out. Our friend wants to use Ghost blog which is a lightweight blogging platform written in Node.js. Seeing it as a useful offering to your customers, we've decided to create a reusable Terraform file to deploy Ghost blog.

What are Hands-On Labs?

Hands-On Labs are scenario-based learning environments where learners can practice without consequences. Don't compromise a system or waste money on expensive downloads. Practice real-world skills without the real-world risk, no assembly required.

Working with Terraform Variables

The Scenario

We manage our own Docker server where we host Dockerized applications for our clients. A friend wants to set up a blog and we’ve decided to help out. Our friend wants to use Ghost blog which is a lightweight blogging platform written in Node.js. Seeing it as a useful offering to your customers, we've decided to create a reusable Terraform file to deploy Ghost blog.

Logging In

Use the IP address and credentials provided on the hands-on lab overview page, and log in with SSH to the server.

Create main.tf

Create main.tf and edit it with whichever editor feels most comfortable. These are the file's contents:

variable "image_name" {
  description = "Image for container."
  default     = "ghost:latest"
}

variable "container_name" {
  description = "Name of the container."
  default     = "ghost_blog"
}

variable "ext_port" {
  description = "External port for container."
  default     = "80"
}

# Download the latest Ghost Image
resource "docker_image" "ghost_image" {
  name = "${var.image_name}"
}

resource "docker_container" "ghost_container" {
  name  = "${var.container_name}"
  image = "${docker_image.ghost_image.latest}"
  ports {
    internal = "2368"
    external = "${var.ext_port}"
  }
}

Generate a Terraform Plan File

Execute the Terraform plan:

[cloud_user@host]$ terraform plan -out=tfplan 
-var 'container_name=ghost_blog1' 
-var 'image_name=ghost:alpine' 
-var 'ext_port=8080'

Deploy the Infrastructure Using the Terraform Plan

Apply the plan with this command:

[cloud_user@host]$ terraform apply tfplan

Test in a Browser

In a web browser, navigate to the public IP of the server, on port 8080:

http://<PUBLIC_IP>:8080

We should land at the Ghost blog page on our server

Conclusion

We did it. We created a Terraform file that will deploy Ghost, for anyone who needs it. Congratulations!