DevOps Automation With Terraform and VMware
DevOps Automation With Terraform and VMware
m
pl
im
en
ts
of
DevOps
Automation
with Terraform
& VMware
Evolving IT Operations Using
Open Source Automation
Eric Wright
REPORT
A
ppl
ica
tio
nR e
sou
rce
Manageme
nt
Br
idget
hegapbet
weenappl
icat
ionsandi
nfr
ast
ruct
ure,
el
imi
nat
ingappl
icat
ionper
for
mancer
iskwi
thout
over
provi
sioni
ngi
nfr
ast
ruct
ure.
L
ear
nMor
e:bi
t.
ly/
tur
bo-
dev
ops
Trustedbyt heworl
d’slar
gest
organizat
ions,i
ncl
udingmor e
t
han100oft heFortune500
DevOps Automation with
Terraform and VMware
Evolving IT Operations Using
Open Source Automation
Eric Wright
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. DevOps Automa‐
tion with Terraform and VMware, the cover image, and related trade dress are trade‐
marks of O’Reilly Media, Inc.
The views expressed in this work are those of the author, and do not represent the
publisher’s views. While the publisher and the author have used good faith efforts to
ensure that the information and instructions contained in this work are accurate, the
publisher and the author disclaim all responsibility for errors or omissions, includ‐
ing without limitation responsibility for damages resulting from the use of or reli‐
ance on this work. Use of the information and instructions contained in this work is
at your own risk. If any code samples or other technology this work contains or
describes is subject to open source licenses or the intellectual property rights of oth‐
ers, it is your responsibility to ensure that your use thereof complies with such licen‐
ses and/or rights.
This work is part of a collaboration between O’Reilly and Turbonomic. See our state‐
ment of editorial independence.
978-1-492-07373-4
[LSI]
Table of Contents
Foreword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . v
iii
4. Next Steps in Your Terraform for VMware vSphere Journey. . . . . . . 25
Transitioning from Local Files to Version Control 25
Centralizing and Collaborating 26
iv | Table of Contents
Foreword
v
As developers consume more cloud services and we push to iterate
faster, Terraform provides a solution for managing our infrastruc‐
ture and making provision simple. We are glad to see an ever-
growing community of users and hope that this report allows users
to gain more familiarity and jump into managing infrastructure
with Terraform.
vi | Foreword
You will come away from this guide with an understanding of how
DevOps processes and IaC can apply to your VMware infrastructure
using Terraform, beginning with building virtual machines (VMs)
using the Terraform command-line interface (CLI), and further by
gaining knowledge about how to use Terraform and VMware to
operate your infrastructure. All of the concepts are explained as you
work through the guide, including specific examples and links to
some more complex examples in the companion code repository.
Before we begin, let’s explore what Terraform is and why it is impor‐
tant to you. Terraform is described by HashiCorp as an open source
tool to write, plan, and create IaC. Terraform is lightweight and ver‐
satile, with the ability to use numerous modules to simply create
code using declarative configuration for many different components
across any hybrid infrastructure.
Foreword | vii
How you build and manage your applications is also important to
understand. Which of the following statements would describe your
current application deployment process?
If you are using mostly manual processes today, the goal of this
guide is to introduce you to automation. Teams that chose the mid‐
dle or higher options from the two lists will learn how Terraform
maps to your current processes. If you’re already using DevOps pro‐
cesses in other parts of your infrastructure (e.g., cloud, containers)
this guide will help to bring some of those practices to your existing
virtualization environment.
viii | Foreword
CHAPTER 1
Infrastructure as Code and
Immutable Infrastructure
Concepts
1
Provider
This is your connector to the underlying infrastructure. This is
how your declarative code will interact with the management
API of whichever platform you are building on. The VMware
vSphere provider will communicate with either vCenter for a
full coverage or to a vSphere host, which provides less
functionality.
Input variables
Input variables are passed to your Terraform configuration.
These can be dynamically created or statically assigned. If not
assigned programmatically, you will be prompted at the
command-line interface (CLI) to enter values.
Data sources
These can be computed or queried infrastructure sources that
are used in other parts of your Terraform configuration, such as
clusters, resource pools, regions, or any of a variety of objects.
Data sources will vary based on which provider you are using
(e.g., Amazon Web Services [AWS], VMware, Digital Rebar).
Expressions
These are computed results that can range from literals to vari‐
ables to indices, maps, and many other types. It’s possible to
have queries that can also feed other expressions and do things
like count within resources and then dynamically assign the
count to naming resources. Another example is creating a vir‐
tual machine (VM) and then assigning the network interface on
creation to a virtual switch or dynamically assigning VM names
based on count, or environment name.
Functions
These are built-in functions that you can use in your expres‐
sions, including numeric (e.g., min, max), string (e.g., lower,
upper, substr), collection (contains, flatten, sort, merge), and
many others. You can find a full set of built-in functions here.
Output values
Return values from your Terraform environment. These can
include static or dynamic results such as VM name, IP address,
storage location, and other computed results that are available
after a Terraform resource deployment or update. These are
Storing Secrets
This is the most contentious and challenging area when it comes to
infrastructure operations. Where is the best place and product to
store secrets (e.g., passwords, API keys, administrative network port
information, Secure Shell [SSH] keys) for use in IaC?
Like the files and folders, the answer is, “It depends.” It’s ideal to use
a secured, programmatically accessible secret storage platform (e.g.,
HashiCorp Vault, CyberArk, AWS Secrets Manager). The examples
in this guide use locally stored credentials and secrets using environ‐
ment variables on each system.
It’s critical that no secrets make their way into your code and into
the repository. Even if you remove temporary passwords from code
that has been previously committed to a repository, those previous
9
Setting Up Your Variables
Variable definition assigns a type to variables you will use, which
can be simple variables (string, integer, bool) or complex vari‐
ables (list, set, map, object, tuple) for more advanced scenarios.
Descriptions are optional but always helpful for others who will be
reading and collaborating with your code. You must define variables
prior to having values assigned in your Terraform resource
configuration:
variable "vsphere_user" {
type = "string"
description = "vCenter/vSphere user"
}
variable "vsphere_password" {
type = "string"
description = "Password for vCenter/vSphere user"
}
variable "vsphere_server" {
type = "string"
description = "vCenter server or vSphere host name"
}
This example shows the three mandatory variables required for
Terraform to authenticate to the vSphere or vCenter in order to
interact with your virtualization environment. You can configure
other custom or optional variables similarly for use anywhere else in
your Terraform configuration code.
• Name of your VM
network_interface {
network_id = "${data.vsphere_network.network.id}"
}
disk {
label = "disk0"
size = 20
}
clone {
template_uuid="$(data.vsphere_virtual_machine.template.id}"
}
}
This example shows a VM with two vCPU machines, 2 GB of virtual
memory, a 20 GB primary virtual disk, and will clone from a
template defined by your data sources. This one uses a Linux
machine, as shown by the guest_id = "other3xLinux64Guest",
which defines the OS and what type of VMware Tools that vCenter
will use to control it.
You are now ready to follow the life cycle flow illustrated earlier in
Figure 1-3. First you run the terraform validate command to
ensure that our syntax is correct:
$ terraform validate
Success! The configuration is valid.
Outputs:
virtual_machine_default_ips = [
"terraform-test0", 10.10.45.127
]
You have a running VM based on your template, which deployed in
a matter of seconds. This greatly reduces the time spent doing these
tasks and ensures consistency of outcome. You can also use the same
code with other teams (QA, Development, etc.), which now extends
the same process to set up their own environments without needing
to have them navigate the VMware ecosystem at all.
Now you run the terraform apply command and initiate the
changes, which modifies only the VM rather than re-creating it
from scratch:
vsphere_virtual_machine.vm[0]: Modifying...
vsphere_virtual_machine.vm[0]: Modifications complete after 7s
Note that the destroy command will remove everything from your
resource configuration, so you must take care as you complete the
life cycle process with the destroy process to be sure that you no
longer need the contents. Luckily, you can quickly and simply re-
create everything by using the terraform apply command again.
connection {
type = "ssh"
host = "terraform-test${count.index}"
user = "${var.photon_user}"
password = "${var.photon_password}"
}
}
The script.sh file will only be uploaded to your remote system with
this example. To run the file after it’s uploaded, you simply combine
these provisioners to upload the file and then to execute the file on
the remote system by using the remote-exec option.
You can add your snapshot resource code as a separate .tf file to
make it easy to add and remove snapshot functionality to a process.
Beware of runaway snapshots, and always keep track of the age of
your snapshots using vCenter or other command line tools.
Here is the code for your simple VM example to add a snapshot:
resource "vsphere_virtual_machine_snapshot" "snap" {
count = 1
virtual_machine_uuid = "${vsphere_virtual_machine.vm[count.index].uuid}"
snapshot_name = "snap of ${vsphere_virtual_machine.vm[count.index].name}"
description = "Snapped by Terraform"
memory = "true"
quiesce = "true"
remove_children = "false"
Using the consolidate = true option ensures that you will consoli‐
date the delta changes in the snapshot disk instances back to the
core VM when you destroy the resource.
Removing just the snapshot is done by using the -target parameter
so that you remove only a specific part of the live Terraform
configuration:
terraform destroy -target=vsphere_virtual_machine_snapshot.snap[0]
Snapshots create a safe rollback point, making deployment of new
code and changes safer, and will increase the confidence of your
team to deploy more often.
What We Learned
This chapter walked through a number of practical examples and
code samples as a way to familiarize you with how Terraform con‐
figurations are written and how the life cycle flow works. These
examples configured and dynamically updated your resources and
worked with tagging, resource pools, and snapshots with little to no
code required. This shows the power of Terraform as a way to oper‐
ate IaC. Now that you have deployed a VM, you are ready to expand
into more ways to take advantage of Terraform for your VMware
environment with simple host configuration.
What We Learned | 19
CHAPTER 3
Managing vSphere Host and
Cluster Resources
21
ha_enabled = true
}
You can see the parameters that will be familiar to you from creating
clusters manually. The DRS and HA settings are defined including
the automation level of DRS, which can be manual, partiallyAuto
mated, or fullyAutomated. The automation level is optional and will
use manual as the default if you do not specifically declare your
setting.
Using version control to store and manage your code is the next step
in unlocking more collaborative development of IaC for you and
your team. Version control is valuable even when there might be
only one operator because it centralizes where the “source of truth”
is rather than trusting in code stored only on local workstations or
servers.
25
the code to a central repository (aka repo) so that you can clone that
code down to other workstations or servers.
As you adopt more IaC practices, you can also use the same tools to
help centralize and repeatedly update credentials and other secrets.
The more you adapt to immutable and replaceable infrastructure,
the more opportunity you have to embrace better security practices.