When code meets infrastructure
- Infrastructure as Code: describing storage, network, and VMs in versioned code (HCL).
- Terraform only manages what is described; importance of the state file and teamwork.
- Terraform Cloud: organization, workspaces, and execution modes.
- Example of deploying a VMware VM, and OpenTofu as a community fork.
Click the image to enlarge.
Terraform
Terraform is one of the tools developed by the American company HashiCorp.
While the application did not invent the principle of IAC for Infrastructure as Code, it greatly contributed to its democratization, becoming a true standard.
The emergence of IAC should be compared to the emergence of public cloud.
The possibility initiated by AWS in 2006 of consuming IT infrastructure like electricity, that is, on demand, anywhere and instantly, has changed the way infrastructure is operated.
While each cloud provider offers (and still offers) its own IAC solution, Terraform had the good idea to make the principle of Infrastructure as Code cross-platform within the target ecosystem, including on OnPrem architectures.
Available "for free" since 2014, Terraform builds on infrastructure virtualization and the explosion of the cloud to consistently describe your architecture components: storage, networks, VMs... Everything can be expressed in the HCL language associated with Terraform.
Thanks to third-party providers, it is then possible to "transform" your code into infrastructure building blocks.
Terraform does not take existing resources into account; it only considers what you can describe in your code.
If you start with Terraform, you should stick with it, because mixing an IAC deployment and a standard deployment can create inconsistencies.
The advantage of IAC is that you can track and version your infrastructure, as well as quickly redeploy or clone your working environment.
Terraform Cloud
Click the image to enlarge.
Terraform can be used outside of its cloud offering. However, the latter is very interesting because it allows you to benefit from two advantages for free:
- Manage your configurations and track their deployment in a team
- Perform remote deployments
Other features are available in the paid version, but the free offering is already quite useful.
Click the image to enlarge.
Indeed, when you run Terraform on your computer, it generates files related to its actions and the state of your deployments. If someone else needs to continue your work, they need to be provided with these files; otherwise, Terraform will not be aware of previous actions and therefore which actions need to be performed or not, depending on the changes made by your colleague.
Click the image to enlarge.
This need to always have access to this repository of the latest tasks can quickly become problematic in an enterprise environment where multiple people may manipulate the same infrastructure described in the HCL code.
Several solutions are possible, including the Terraform Cloud solution integrated with the "HashiCorp Cloud Platform".
By using Terraform Cloud, you and your colleague can share a common workspace where each local launch can be synchronized with the cloud, thus ensuring the same Terraform repository.
Furthermore, Terraform Cloud allows you to trigger deployments based on events without needing the Terraform binary, especially when interacting with a public cloud provider.
For example, you could configure it so that pushing your HCL code to a GIT repo automatically triggers a read of the latest version and an execution of Terraform directly from the cloud to the target environment.
Using Terraform Cloud
Go to the Terraform website and create an account.
Click the image to enlarge.
Then, create your organization. This can be shared with other people who also have a Terraform account and are working on the same infrastructure as you.
Click the image to enlarge.
Click the image to enlarge.
Now that we have an organization, we can create a "Workspace". Each Workspace corresponds to a project or an infrastructure.
It is possible to interact with a "Workspace" using several solutions.
- Version Control: A deployment is triggered as a result of an action performed on a source code management tool. For example, with GitLab. Your infrastructure is automatically created with each commit of your code
- API: A deployment is triggered through interaction with the API
- CLI: A deployment is triggered through interaction with the CLI. This is the method that will be described here
Simply name your workspace and provide a description.
Click the image to enlarge.
Click the image to enlarge.
Once your workspace is created, you can define the execution mode of the workspace via the "General" option and then "Execution Mode", choosing "Custom".
A workspace can have three execution modes.
- Remote: In this case, Terraform Cloud directly handles the execution of your code on your target environment. This requires that Terraform Cloud has access to your ecosystem. This is an option to prioritize when deploying to a public cloud
- Agent: In this case, Terraform Cloud communicates with an agent deployed on your target environment.
- Local: In this case, you use the terraform binary, and the deployment is performed from your workstation. You then use Terraform Cloud to synchronize your changes, but not for executing commands.
Click the image to enlarge.
For this example, I will deploy a VM to my private VMware environment. Therefore, I will choose a local workspace, since Terraform Cloud does not have access to my on-premises environment.
Now that my workspace is ready, I need to create my API token. This token allows me to authenticate from my local workstation to Terraform Cloud.
To do this, simply go to your account settings and request a token.
Click the image to enlarge.
Click the image to enlarge.
Click the image to enlarge.
Click the image to enlarge.
You must, of course, keep this token in a secure location and not share it.
In the screenshot, I am using a token without an expiration date. In a production environment, this is obviously an option to avoid. Reviewing tokens is essential to prevent unwanted access. Also, use a precise description, and especially avoid the "generic" token. Prioritize a token per use case and per user.
Terraform is available as a simple binary for various platforms.
Click the image to enlarge.
Simply include the location of the executable in your local path to be able to call a terraform command from any location on your workstation.
Click the image to enlarge.
I will use the terraform login command and my previously retrieved API token to authenticate with Terraform Cloud.
Click the image to enlarge.
Click the image to enlarge.
As indicated by the output of my command, the configuration (i.e., my token) is saved in my user profile under C:\Users\mon_user\AppData\Roaming in the folder terraform.d
The Terraform ecosystem is now ready to be used. I am not required to use the Terraform Cloud as a backend for synchronizing the state of my deployments. I can remain with local file creation.
However, if I want my project to take advantage of the workspace that I created in Terraform Cloud, I just need to add a "backend.tf" file with the following content to the local folder containing the deployment files:
terraform {
cloud {
organization = "COOLCORP-IAC"
workspaces {
name = "devk8sctp501"
}
}
}
In this way, when I use the Terraform binary, it will know that it needs to use my devk8sctp501 workspace in the Terraform Cloud.
Since I have configured my cloud access with my API token, the binary will be able to authenticate with my organization in Terraform Cloud.
Example of deploying a VM on VMware
The description of the infrastructure to be deployed is done within a file that generally has the .tf extension, which we place at the root of a folder.
Organization and roles of tf files
Several strategies are possible, but I find it more practical to segment my tf files by function/role rather than using a single file for everything.
The logic used is as follows:
- A backend.tf file
As mentioned previously, this allows us to indicate that we want to use a workspace in Terraform Cloud.
terraform {
cloud {
organization = "COOLCORP-IAC"
workspaces {
name = "devk8sctp501"
}
}
}
- A provider.tf file
This allows us to specify that we will need the vSphere provider to enable Terraform to deploy resources in the vSphere environment.
provider "vsphere" {
user = var.vsphere_user
password = var.vsphere_password
vsphere_server = var.vsphere_server
# If you have a self-signed cert
allow_unverified_ssl = true
}
Although Terraform enables Infrastructure as Code (IAC) in many cloud and private ecosystems, it is necessary for it to retrieve the associated provider. Often, this is provided by the editor of the ecosystem itself. Be aware that with Terraform, you can deploy a VM in AWS, Azure, GCP, or others, but not with the same files!
When I talk about doing IAC in a cross-platform way at the beginning of this article, it means using the same product and language, but each provider has its own resources and its own ways of describing/configuring them.
The HCL syntax remains the same, but the resources described are specific to each provider.
Each provider imposes a certain number of parameters. In the case of vSphere, you need to specify the URL of the vCenter and the authentication information. Here, we will make the requested information variable.
Also, unlike the example presented here, it is recommended to fix the version of the chosen provider using the version option. Indeed, the editor may evolve the provider as its ecosystem evolves.
It is not always clear that your internal infrastructure will be supported by the latest version of the provider if you are not up to date with the latest version of the ecosystem offered by the vendor.
If you do not specify the provider version, it will constantly retrieve its latest version, which can unexpectedly break interaction with your infrastructure
- a vsphere.tf file
data "vsphere_datacenter" "dc" {
name = "${var.vsphere_datacenter}"
}
data "vsphere_compute_cluster" "cluster" {
name = "${var.vsphere_cluster}"
datacenter_id = "${data.vsphere_datacenter.dc.id}"
}
data "vsphere_network" "network_lan" {
name = "${var.vlan_lan}"
datacenter_id = "${data.vsphere_datacenter.dc.id}"
}
data "vsphere_virtual_machine" "template" {
name = "${var.vsphere_template}"
datacenter_id = "${data.vsphere_datacenter.dc.id}"
}
It contains only a few definitions of objects specific to vSphere.
- a variables.tf file
#######################Variables vsphere
variable "vsphere_user" {
default = "[email protected]"
}
variable "vsphere_password" {
type = string
sensitive = true
}
variable "vsphere_server" {
default = "vcenter.coolcorp.priv"
}
variable "vsphere_datacenter" {
default = "Paris"
}
variable "vsphere_cluster" {
default = "COOLCLUSTER"
}
variable "vsphere_template" {
default = "prdtplk8s501"
}
################################### Variables Network
variable "vlan_lan" {
default = "LAN"
}
variable "gateway_lan" {
default = "192.168.10.253"
}
variable "default_dns" {
default = "192.168.10.35"
}
variable "default_dns_domain" {
default = "coolcorp.priv"
}
#################################### Variables K8S
####Detail VM
variable "vm_01_name" {
default = "devk8sctp501"
}
variable "vm_01_dts" {
default = "VL1"
}
variable "vm_01_cpu_number" {
default = "4"
}
variable "vm_01_memory_size" {
default = "4096"
}
variable "vm_01_ip_address" {
default = "192.168.10.66"
}
variable "vm_01_ip_netmask" {
default = "24"
}
This file allows you to specify all the variables necessary for my deployment and which can be reused in different resources. This allows you to centralize their configuration and avoid having to go through each file that uses them.
Some variables may contain critical information. This is the case in my example, since Terraform needs access to my vCenter to provision my target VM.
Again, several strategies are possible to protect your connection information. The simplest one is the one expressed here, where I simply tell Terraform to ask me for the password associated with my account for accessing vCenter at the time of code execution.
Another way to do this would be to use another product from the vendor, Vault, a secret manager, which is also extremely widely used.
Also from Hashicorp, Vault integrates very well with Terraform, and the latter can communicate with a Vault instance to retrieve all sensitive information needed for deployment.
This is a very relevant model in companies, but I will not go into detail here.
- a vm.tf file
data "vsphere_datastore" "datastore_vm_01" {
name = "${var.vm_01_dts}"
datacenter_id = "${data.vsphere_datacenter.dc.id}"
}
resource "vsphere_virtual_machine" "vm_vm_01" {
name = "${var.vm_01_name}"
resource_pool_id = "${data.vsphere_compute_cluster.cluster.resource_pool_id}"
datastore_id = "${data.vsphere_datastore.datastore_vm_01.id}"
num_cpus = "${var.vm_01_cpu_number}"
memory = "${var.vm_01_memory_size}"
guest_id = "${data.vsphere_virtual_machine.template.guest_id}"
scsi_type = "${data.vsphere_virtual_machine.template.scsi_type}"
network_interface {
network_id = "${data.vsphere_network.network_lan.id}"
adapter_type = "${data.vsphere_virtual_machine.template.network_interface_types[0]}"
}
disk {
label = "disk0"
size = "${data.vsphere_virtual_machine.template.disks.0.size}"
eagerly_scrub = "${data.vsphere_virtual_machine.template.disks.0.eagerly_scrub}"
thin_provisioned = "${data.vsphere_virtual_machine.template.disks.0.thin_provisioned}"
}
clone {
template_uuid = "${data.vsphere_virtual_machine.template.id}"
customize {
linux_options {
host_name = "${var.vm_01_name}"
domain = "coolcorp.priv"
}
network_interface {
ipv4_address = "${var.vm_01_ip_address}"
ipv4_netmask = "${var.vm_01_ip_netmask}"
}
ipv4_gateway = "${var.gateway_lan}"
dns_suffix_list = ["${var.default_dns_domain}"]
dns_server_list = ["${var.default_dns}"]
}
}
}
This file contains all the characteristics of the VM (here devk8sctp501) that I want to deploy: from which template, with what hardware configuration, connected to which network...
You can then add as many .tf files as there are resources to manage, or group resources of the same type in a single file: VMs, networks, storage...
In any case, Terraform's documentation is quite well done with examples specific to each provider used.
Deployment and commands
Now that the infrastructure is described in files using the HCL language, we can use Terraform.
The first command terraform init initializes the deployment. It is mainly during this phase that Terraform retrieves directly from the internet the necessary provider(s).
Click the image to enlarge.
Then we use the command terraform plan
Click the image to enlarge.
Click the image to enlarge.
This phase allows you to "plan" the deployment. At this stage, no concrete action has yet been performed. Terraform will compare the content of our files with its last repository to determine what needs to be modified/added/deleted.
Since this is the first execution, the repository does not exist. Therefore, there will be no point of comparison. As a reminder, Terraform does not take into account resources that you may have deployed outside of its use. For example, in my case, if I create VM X before using Terraform and then declare this VM in an HCL file with a different configuration, Terraform will not modify my existing VM; it will simply try to recreate it because, for it, the VM does not exist...and that will not work.
Please note that Terraform requires me to enter the password for accessing my vCenter. Since this data is marked as sensitive in my variables.tf file, it will not be displayed in the output.
If the planning phase completes without errors, you can then run the final operation using the terraform apply command.
Click the image to enlarge.
Click the image to enlarge.
It is during this phase that the deployment actually takes place and the VM is created on the vSphere environment.
Click the image to enlarge.
The advantage of using Terraform Cloud as a backend is that, instead of simply having the repository files generated during the deployment in my folder, I have access to a summary of the actions and can track what has been done.
Click the image to enlarge.
Click the image to enlarge.
Click the image to enlarge.
However, be careful not to separate yourself from the contents of the .terraform folder within your working directory. Outside of Terraform Cloud, this is your only source that can serve as a reference for your future deployments.
As a reminder, Terraform "tracks" its actions and maintains its repository in the form of files with each execution. For any modifications to your HCL configurations, these are compared to the repository, and this is how Terraform determines what needs to be done.
Click the image to enlarge.
If you have deployed VM "X" with Terraform and then modify it outside of Terraform, if you decide to return to Terraform for a second modification, Terraform will not be informed of what you may have done before.
Now that we can quickly and easily deploy a whole set of VMs from a template, it will be easier to describe all of these Kubernetes nodes in a Terraform project in order to automate the deployment of the cluster.
OpenTofu
Originally, Terraform was released under the Mozilla Public License, allowing permissive use of the tool with very few obligations towards Hashicorp. However, in August 2023, the company changed its model to adopt a "Business Source License".
Unfortunately, this is a trend followed by many previously open-source companies, such as Grafana, Elastic Search, and more recently, Redis. Some people cried foul, but personally, I can understand these changes. The economic model of open source remains complex, and not everyone plays fair.
Terraform is at the heart of commercial solutions that rely on Hashicorp's investments and code, without Hashicorp necessarily benefiting from the profits generated by these third-party offerings.
The switch to a BSL license still allows for free use of Terraform... but now limits the ability for third-party vendors, consultants, or integrators to "embed" or "host" community editions of Hashicorp products.
| Feature | Mozilla Public License (MPL) | Business Source License (BSL) |
|---|---|---|
| License Type | Free and open-source license | Modified proprietary license |
| Access to Source Code | Yes, complete | Partial access; the code becomes open-source after a specified period |
| Modifications | Modifications must also be under MPL | Modifications may be subject to stricter restrictions |
| Commercial Use | Permitted without restrictions | Often subject to restrictions, depending on the specific terms of the BSL |
| Distribution | Free, as long as modifications remain under MPL | May be limited or restricted according to the license terms |
| Compatibility with other licenses | Compatible with other open-source licenses | May have compatibility issues with other open-source licenses |
| Contribution of modifications | Contributions must be under the same license | Not necessarily required, depending on the terms of the license |
| Popularity and Adoption | Widely used in open-source projects | Primarily used by companies offering products with an "open-core" model. |
| Main Objective | To promote and protect the development of open-source software | To protect the company's business model while providing early access to source code |
Working with open source is never seamless. It didn't take long for the community to organize and fork the project, giving rise to OpenTofu under the auspices of the Linux Foundation.
Click the image to enlarge.
As of writing this article, OpenTofu is 100% compatible with Terraform 1.6, and using one does not prevent you from using the other... but nothing is guaranteed in the future, and potential differences may arise over time.
For my part, I plan to gradually switch to OpenTofu without losing interest in terraform. There are still some uncertainties, and recent divergences (at the time of writing this article) are already emerging between HashiCorp and OpenTofu, with the former accusing the latter of not respecting the new license adopted for terraform.
In practice, and to my (limited) knowledge, I have not found any differences
Just like with terraform, you can download the binary directly from the official website and add it to your local system path. The executable is simply tofu
Click the image to enlarge.
The commands are identical to those in terraform:
- tofu init
- tofu plan
- tofu apply
I was even able to use the "state" generated by terraform, and then import it into OpenTofu. I simply had to modify my backend.tf file to add the hostname of the terraform cloud, as this is not implicit with OpenTofu.
terraform {
cloud {
organization = "COOLCORP-IAC"
hostname = "app.terraform.io"
workspaces {
name = "devk8sctp501"
}
}
}
I haven't talked about this command yet, but like with terraform, adding the keyword destroy removes all deployed infrastructure.
Click the image to enlarge.
Click the image to enlarge.
It will be necessary to monitor any differences that may arise between the two tools. As it stands, whether you choose one or the other, the logic remains the same.
IAC has become a foundation, and whether with Terraform or OpenTofu, describing your infrastructure as code has become a good practice that I encourage you to adopt.