Every Terraform project rests on three concepts: the provider (the connection to an API), the resource (what Terraform creates), and the data source (what Terraform reads without creating it). You have already come across the first two in the example of the Terraform workflow. Telling these three building blocks apart is enough to start reading a Terraform project.
What you will learn
- What a provider is: the plugin that connects Terraform to an API (libvirt, AWS, GitHub...)
- Declare a resource: the
resource "type" "name"syntax and its attributes - Use a data source: read an existing resource without creating it
- Reference one resource from another:
libvirt_volume.disk_ubuntu.pathand dependency handling
Providers: the connection to an API
A provider is a plugin that lets Terraform communicate with a particular technology. It translates your HCL declarations into API calls.
There is a very large number of them: libvirt, AWS, Azure, GCP, Kubernetes, GitHub, Cloudflare, Vault...
How do you declare a provider?
terraform { required_providers { libvirt = { source = "dmacvicar/libvirt" version = "~> 0.9.0" } }}provider "libvirt" { uri = "qemu:///system"}Two distinct blocks, stored in two files according to the official style guide:
-
required_providers(insideterraform {}): declares the source of the provider and its version constraint. Essential for a provider that does not belong to HashiCorp, such as libvirt. -
provider "name" {}: configures the provider (URL, region, credentials...). Optional if the default values suit you.
What is the Terraform Registry?
Providers are published on the
Terraform Registry.
This is where Terraform downloads them during terraform init.
The value of the source argument is always written namespace/name, where the
namespace is the organization that publishes the provider. Examples:
hashicorp/awsdmacvicar/libvirthashicorp/kubernetes
Can you use several providers?
A project can use several providers at the same time:
terraform { required_providers { libvirt = { source = "dmacvicar/libvirt" version = "~> 0.9.0" } local = { source = "hashicorp/local" version = "~> 2.5" } }}provider {} blocks are declared in the root module, the directory from which
the terraform command is run. The modules it calls, reusable building blocks made
of .tf files, receive them without configuring them again: the
creation of modules (in French)
is the subject of an entire module of this course.
Resources: what Terraform creates
A resource represents an infrastructure object that Terraform manages: a VM, a network, a disk, a bucket, a DNS record...
What is the syntax of a resource?
resource "TYPE" "LOCAL_NAME" { attribute1 = value1 attribute2 = value2}-
TYPE: identifies the provider and the type of object (e.g.libvirt_domain,aws_instance,kubernetes_deployment). -
LOCAL_NAME: a name internal to the Terraform project, used to reference the resource elsewhere in the code. It does not appear in the infrastructure.
Example with libvirt
Here is the same syntax applied to two real resources of the libvirt provider: a
disk volume cloned from a cloud image, then a VM that boots from that volume. Note
how the domain cites the volume by TYPE.LOCAL_NAME: it is this link that sets the
creation order.
resource "libvirt_volume" "disk_ubuntu" { name = "ubuntu-01.qcow2" pool = "default" target = { format = { type = "qcow2" } } create = { content = { url = pathexpand("~/images/ubuntu-24.04-cloudimg.img") } }}
resource "libvirt_domain" "vm_web" { name = "web-01" type = "kvm" memory = 1024 memory_unit = "MiB" vcpu = 2 running = true
os = { type = "hvm", type_arch = "x86_64", type_machine = "q35" }
devices = { disks = [ { source = { file = { file = libvirt_volume.disk_ubuntu.path } } target = { dev = "vda", bus = "virtio" } driver = { type = "qcow2" } } ] interfaces = [ { model = { type = "virtio" } source = { network = { network = "default" } } } ] }}How do you reference one resource from another?
To use an attribute of one resource in another, the syntax is:
TYPE.LOCAL_NAME.ATTRIBUTEIn the example above:
file = libvirt_volume.disk_ubuntu.pathTerraform understands the dependency automatically: it will create
libvirt_volume.disk_ubuntu before libvirt_domain.vm_web.
Data sources: reading without creating
A data source lets you read information about a resource that already exists, without creating or managing it.
Typical use cases:
- Get the ID of an existing network to connect a VM to it
- Read an AWS AMI by its criteria (rather than by its ID, which changes)
- Look up a secret in Vault
What is the syntax of a data source?
A data source is written like a resource, with the data keyword in place of
resource. Its arguments do not describe an object to create: they are filters
that designate the existing object to read.
data "TYPE" "LOCAL_NAME" { filter = value}Example: reading the characteristics of the host
The libvirt provider 0.9 offers few data sources. libvirt_node_info is a
simple example: it queries the hypervisor (the software that runs the VMs, here
KVM) and returns its characteristics without creating anything. Here, the VM
receives two vCPUs, or fewer if the host does not have that many:
data "libvirt_node_info" "host" {}
resource "libvirt_domain" "vm_adapted" { name = "web-02" vcpu = min(2, data.libvirt_node_info.host.cpu_cores_total) # ...}min() is a function: it returns the smallest of its values, here 2 or the
number of cores of the host if it is lower. The domain has a different name
(vm_adapted, web-02) from the one in the previous example, so that the two
blocks can coexist in the same file.
To see what the data source has read, add an output that returns it in full:
output "node" { value = data.libvirt_node_info.host}terraform apply then displays the values read. Here is the result on a test
virtual machine with two cores and 4 GB of memory (with Terraform 1.17.2 and
libvirt provider 0.9.9); the values of cpu_cores_total, memory_total_kb and
id change from one machine to another:
node = { "cpu_cores_per_socket" = 2 "cpu_cores_total" = 2 "cpu_model" = "x86_64" "cpu_sockets" = 1 "cpu_threads_per_core" = 1 "id" = "2766229893261301476" "memory_total_kb" = 3943056 "numa_nodes" = 1}Look at cpu_cores_total: it is 2 here, and it is the value that min() compares
with 2 to choose the number of vCPUs of web-02. On a host with a single core, the
VM would receive only one.
Examples written for older versions of the provider often read a pool with
data "libvirt_pool": this data source no longer exists in 0.9, and
terraform validate answers Invalid data source.
The syntax to reference a data source:
data.TYPE.LOCAL_NAME.ATTRIBUTEVisual summary
The diagram brings together the three notions of the page. The provider translates the code into API calls, the resources create and manage objects, and the data sources read objects that already exist without ever changing them.
What are computed attributes?
Some attributes of a resource are only known after creation (IP address, generated ID, volume path...). In the plan, they are displayed like this:
+ id = (known after apply)+ path = (known after apply)You can still use them in other resources. Terraform resolves the dependencies automatically.
Put it into practice
A single word separates the two natures of blocks: resource creates and manages, data only reads. You check it in the mode field of the state, then observe the two consequences that follow: a destroy does not touch what it did not create, and a data source is reread at every plan.
Key takeaways
-
A provider is a plugin that connects Terraform to an API. It is declared in
required_providersand configured inprovider {}. -
A resource is an object created and managed by Terraform. It is referenced by
TYPE.NAME.ATTRIBUTE. -
A data source reads an existing object without creating or changing it. Its values are stored in the state, but
terraform destroydoes not destroy the remote object. Reference:data.TYPE.NAME.ATTRIBUTE. -
Dependencies between resources are resolved automatically as soon as you reference an attribute of one resource from another.
Knowledge check
Check what you have learned with this interactive quiz
How it works
- The timer starts when you click Start
- Multiple choice, true/false and short answer questions
- You can move between questions
- Detailed results are shown at the end
Starts the quiz and the timer
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
A new full quiz with random questions
Work again only on the questions you missed