Resources
How to define infrastructure resources like servers, storage and virtual machines in a Terraform resource block.
Defining a Resource
Now that we have our provider set up, we want to define our resources: databases, virtual machines, storage buckets and so on. If the Project Initialization step is correctly set up, we will now have access to the provider's resources.
We define the resource inside a resource block:
resource "hcloud_server" "nat" {
count = 2
name = "${var.project_name}-cp-${count.index + 1}"
image = var.talos_image_id
server_type = var.server_type
location = var.location
user_data = file("../talos/controlplane.yaml")
labels = {
type = "cp"
}
public_net {
ipv4_enabled = false
ipv6_enabled = false
}
}
In this block, we define a resource from the Hetzner provider. Within that provider exists a
resource called "hcloud_server", which we then call "nat", so we can
reference it internally later, the local name lets us have multiple separate
"hcloud_server" configurations block (i.e. "nat" or "worker").
However, none of this actually exists just yet, it is just a wish list, a desired state.
To figure out what happens next, Terraform will compare the configurations against what currently exists and works out the difference.
So if the resource already exists and matches the configuration, nothing will change. If there is
a change, such as a new count, the infrastructure will reflect that change. If the
block is deleted, so will the resource. And of course, if this is the first time the state sees the
block, the resource will be created.
Lifecycle
Whenever a Terraform resource is subject to the terraform apply command, on of four
things will happen:
a) if it exists in the configuration, but not the state, it will be created.
b) if it exists in the configuration and the state, it will be updated.
c) if it exists in the configuration and state and has changed, but cannot be updated due to API limitations, it is destroyed and recreated.
d) if it exists in the state, but no longer in the configuration, it will be destroyed.
These 4 things are central to the way Terraform works.