Unit 1.2: Terraform Provider and Core Patterns
Introduction
In Unit 1.1 you created TaskBoard's data center with curl and polled the request status by hand. For a real project you need the infrastructure in Git, reviewed in pull requests, and reproducible for every developer and every branch.
The IONOS CLOUD Terraform Provider gives you that. It translates HCL resources into the same API v6 calls you made by hand and waits for each asynchronous request. In this unit you configure the provider, use the five core resources of a basic virtual data center (VDC), look up images and locations, store state remotely, and import existing resources. In the Code Lab you build TaskBoard's base VDC, verify it, and destroy it.
1. Provider Setup and Authentication
terraform {
required_providers {
ionoscloud = {
source = "ionos-cloud/ionoscloud"
version = "6.7.39"
}
}
}
provider "ionoscloud" {}
The required_providers block is mandatory: without it, Terraform cannot find and download the provider. Pin an exact version so every developer and CI run uses the same release, and upgrade in a separate pull request.
1.1 Token Authentication
Token authentication is the method the provider documentation strongly suggests. With an empty provider block, the provider reads the IONOS_TOKEN environment variable:
export IONOS_TOKEN="$(vault kv get -field=token secret/taskboard/ionos)"
terraform init
The provider also accepts username and password (or IONOS_USERNAME and IONOS_PASSWORD) when no token is set.
1.2 Passing the Token Through a Variable
When you prefer an explicit argument, declare a sensitive variable and set it with TF_VAR_:
variable "ionos_token" {
type = string
sensitive = true
}
provider "ionoscloud" {
token = var.ionos_token
}
export TF_VAR_ionos_token="$IONOS_TOKEN"
Credentials in a .tf file override the credentials from environment variables. Never write a literal token into a .tf file: it ends up in Git history.
To manage IONOS Cloud Object Storage resources with the provider, also set IONOS_S3_ACCESS_KEY and IONOS_S3_SECRET_KEY.
2. Core Resources
Every resource of the provider is prefixed with ionoscloud_. A basic VDC uses five of them.
| Resource | Required arguments | Notes |
|---|---|---|
ionoscloud_datacenter |
name, location |
location is immutable |
ionoscloud_lan |
datacenter_id |
public = true for an internet-facing LAN |
ionoscloud_server |
name, datacenter_id |
type is immutable; inline volume and nic blocks |
ionoscloud_volume |
datacenter_id, disk_type, size |
disk_type is immutable; server_id attaches it |
ionoscloud_nic |
datacenter_id, server_id, lan |
Adds a further NIC to a server |
2.1 Data Center and LAN
variable "location" {
type = string
default = "de/txl"
}
resource "ionoscloud_datacenter" "taskboard" {
name = "taskboard-dev"
location = var.location
description = "TaskBoard development environment"
}
resource "ionoscloud_lan" "public" {
datacenter_id = ionoscloud_datacenter.taskboard.id
public = true
name = "taskboard-public"
}
The location of a data center is immutable. Changing it in code means a new data center, so choose it once per environment and keep it in a variable. If you omit ipv4_cidr_block on a private LAN, the provider assigns a /23 block from the 10.0.0.0/8 range.
2.2 Server With Inline Volume and NIC
resource "ionoscloud_server" "api" {
name = "taskboard-api-01"
datacenter_id = ionoscloud_datacenter.taskboard.id
type = "ENTERPRISE"
cores = 2
ram = 2048
availability_zone = "AUTO"
image_name = data.ionoscloud_image.ubuntu.id
ssh_keys = [var.ssh_public_key]
volume {
name = "system"
size = 20
disk_type = "BALANCED"
bus = "VIRTIO"
}
nic {
lan = ionoscloud_lan.public.id
name = "public"
dhcp = true
firewall_active = false
}
}
For ENTERPRISE servers you must provide cores, ram (in MB) and the volume size (in GB). For CUBE servers you provide template_uuid instead, and cores, ram and volume.size are not allowed. ssh_keys accepts the key text directly, and SSH keys work only with public Linux images. For new volumes, use the Block Storage performance classes (ESSENTIAL, BALANCED, PERFORMANCE), which the documentation recommends.
2.3 Additional Volumes and NICs
resource "ionoscloud_volume" "data" {
datacenter_id = ionoscloud_datacenter.taskboard.id
server_id = ionoscloud_server.api.id
name = "taskboard-data"
size = 10
disk_type = "BALANCED"
bus = "VIRTIO"
licence_type = "OTHER"
}
The primary volume is created with the server; ionoscloud_volume adds more. Either image_name or licence_type is required. Leave server_id unset for a volume that is not attached to any server; changing it detaches the volume from the old server first. For a second network interface, the ionoscloud_nic resource works the same way with datacenter_id, server_id and lan.
3. Data Sources: Images and Locations
Do not hard-code image UUIDs. Look them up at plan time.
3.1 Finding an OS Image
data "ionoscloud_image" "ubuntu" {
image_alias = "ubuntu:latest"
type = "HDD"
cloud_init = "V1"
location = var.location
}
The image data source returns a single match. If your search matches more than one image, it returns an error, and you refine the arguments. To see the name and location of the matching images, run with TF_LOG=debug. Always pass location, set to your data center's location, so the lookup returns the image for that location.
3.2 Inspecting a Location
data "ionoscloud_location" "selected" {
name = var.location_name
feature = "SSD"
}
output "cpu_families" {
value = [for c in data.ionoscloud_location.selected.cpu_architecture : c.cpu_family]
}
Either name or feature must be set, or the data source returns an error. The cpu_architecture attribute lists the CPU families, max_cores and max_ram (in MB) for the location, which helps you validate a cpu_family before you apply.
4. Lifecycle, Async Handling and State
4.1 What Happens Under the Hood
terraform init # downloads ionos-cloud/ionoscloud 6.7.39
terraform plan # reads current resources, computes the diff, changes nothing
terraform apply # sends create/update/delete requests and waits for each one
terraform destroy # deletes every resource in the state
During apply, each create returns an asynchronous request, exactly as in Unit 1.1. The provider waits for the resource to be provisioned before it creates resources that reference it. References such as ionoscloud_datacenter.taskboard.id give Terraform the implicit order: data center, then LAN, then server, then the additional volume.
Each resource that supports it has a timeouts block. The defaults are 60 minutes for create, update and delete:
resource "ionoscloud_server" "api" {
# ...
timeouts {
create = "30m"
delete = "20m"
}
}
Terraform does not automatically roll back on errors. Your state file is partially updated with any resources that completed. Fix the cause and run apply again.
4.2 Debugging Provider Errors
By default, the provider returns only HTTP client errors, which usually consist of the status code alone. To see the API error message, raise the log level:
export IONOS_LOG_LEVEL=debug
terraform apply
The response body then shows httpStatus and messages with the VDC- error code. Use trace only for debugging: it logs the full request and response, including sensitive data.
4.3 Remote State in IONOS Cloud Object Storage
Local state works for one developer. For a team, store state in a bucket. IONOS Cloud Object Storage is compatible with the S3 protocol and authenticates with an Access Key and a Secret Key, so you use Terraform's built-in s3 backend:
terraform {
backend "s3" {
bucket = "taskboard-tfstate"
key = "dev/terraform.tfstate"
region = "eu-central-3"
endpoints = {
s3 = "https://s3.eu-central-3.ionoscloud.com"
}
skip_credentials_validation = true
skip_region_validation = true
skip_requesting_account_id = true
}
}
export AWS_ACCESS_KEY_ID="<object-storage-access-key>"
export AWS_SECRET_ACCESS_KEY="<object-storage-secret-key>"
terraform init -migrate-state
The skip_* settings turn off AWS-specific checks that an S3-compatible service cannot answer. State locking stops two applies from writing the same state at once. Until you have verified a locking method against your bucket, serialize applies in CI so that only one pipeline per environment runs at a time.
5. Import and Cost Awareness
5.1 Importing Existing Resources
The servers you created in Unit 1.1 are not in any state file. Bring a resource under Terraform with an import block:
import {
to = ionoscloud_server.legacy_api
id = "<datacenter-id>/<server-id>"
}
terraform plan -generate-config-out=generated.tf
The command writes a matching resource block into generated.tf. The older command-line syntax is still supported:
terraform import ionoscloud_server.example <datacenter-id>/<server-id>
terraform import ionoscloud_lan.public <datacenter-id>/<lan-id>
terraform import ionoscloud_datacenter.taskboard <datacenter-id>
Importing a server with only the data center ID and server ID imports it without an inline nic block. Its NICs are left to separate ionoscloud_nic resources, which you import on their own. Review the generated configuration and run terraform plan until it shows no changes.
5.2 Ephemeral Environments
Every apply provisions resources that you pay for. Three habits keep costs under control:
terraform plan -out=tfplan # review what will be created
terraform apply tfplan # apply exactly the reviewed plan
terraform destroy -auto-approve # tear down when the test is finished
Create short-lived environments per feature branch with a separate state key (for example branches/<branch>/terraform.tfstate), and destroy them when the branch is merged. You automate this teardown in Module 5.
API Reference Quick Card
Key API endpoints behind this unit's resources:
| Method | Endpoint | Description |
|---|---|---|
POST |
/datacenters |
Created by ionoscloud_datacenter |
POST |
/datacenters/{datacenterId}/lans |
Created by ionoscloud_lan |
POST |
/datacenters/{datacenterId}/servers |
Created by ionoscloud_server |
GET |
/images |
Searched by the ionoscloud_image data source |
GET |
/requests/{requestId}/status |
Polled while the provider waits for provisioning |
Base URL: https://api.ionos.com/cloudapi/v6
Authentication: Authorization: Bearer <token>
Code Lab
Objective: Build TaskBoard's base VDC with Terraform (data center, LAN, server with attached volume), then plan, apply, verify and destroy it.
Prerequisites:
- IONOS CLOUD account with an API token in
IONOS_TOKEN - Terraform installed locally
ionosctl(Unit 1.1) and an SSH public key
Step 1: Create the project with versions.tf and variables.tf
# mkdir taskboard-infra && cd taskboard-infra
# versions.tf: the terraform block from Section 1, with an empty provider "ionoscloud" {}
# variables.tf
variable "location" {
type = string
default = "de/txl"
}
variable "ssh_public_key" {
type = string
}
Expected output:
(files saved)
Step 2: Write main.tf and outputs.tf
Copy the image data source (Section 3.1), the data center and LAN (Section 2.1), the server (Section 2.2) and the data volume (Section 2.3) into main.tf. Then add:
output "datacenter_id" { value = ionoscloud_datacenter.taskboard.id }
output "server_id" { value = ionoscloud_server.api.id }
output "server_ip" { value = ionoscloud_server.api.primary_ip }
Expected output:
(files saved)
Step 3: Initialize and plan
export TF_VAR_ssh_public_key="$(cat ~/.ssh/id_ed25519.pub)"
terraform init
terraform plan -out=tfplan
Expected output:
Terraform has been successfully initialized!
...
Plan: 4 to add, 0 to change, 0 to destroy.
Step 4: Apply
terraform apply tfplan
Expected output:
ionoscloud_datacenter.taskboard: Creation complete after ...
ionoscloud_lan.public: Creation complete after ...
ionoscloud_server.api: Creation complete after ...
ionoscloud_volume.data: Creation complete after ...
Apply complete! Resources: 4 added, 0 changed, 0 destroyed.
Step 5: Verify outside Terraform
DC=$(terraform output -raw datacenter_id)
ionosctl compute server list --datacenter-id "$DC" --cols Name,Type,Cores,State
ionosctl compute server volume list --datacenter-id "$DC" \
--server-id "$(terraform output -raw server_id)" --cols Name,Size,Type,State
Expected output:
Name Type Cores State
taskboard-api-01 ENTERPRISE 2 AVAILABLE
Name Size Type State
system 20 BALANCED AVAILABLE
taskboard-data 10 BALANCED AVAILABLE
Step 6: Confirm no drift
terraform plan
Expected output:
No changes. Your infrastructure matches the configuration.
Validation Checklist:
- [ ]
terraform applycreated four resources without errors - [ ]
ionosctlshows the server asAVAILABLEin the new data center - [ ] The server has two attached volumes
- [ ] A second
terraform planreports no changes
Cleanup:
terraform destroy -auto-approve
Common Pitfalls
Developer mistakes to avoid with this unit's topic:
-
Unpinned provider version
- Problem: A plan that was clean yesterday suddenly shows changes, or an argument stops working in CI.
- Why it happens: Without an exact
versioninrequired_providers,terraform initon a fresh runner can download a newer provider release than the one you tested. - Fix: Pin
version = "6.7.39", commit.terraform.lock.hcl, and upgrade in a dedicated pull request.
-
Changing an immutable argument
- Problem: You change
locationon a data center, ortypeon a server, and the plan wants to destroy and recreate it. - Why it happens: These arguments are immutable. On a server,
allow_replace = trueupdates them by destroying and recreating the server. - Fix: Keep immutable values in per-environment variables, review every
-/+line in the plan, and useallow_replaceonly when you accept the recreation.
- Problem: You change
-
Ambiguous image lookups
- Problem:
terraform planfails in theionoscloud_imagedata source with an error about multiple matches. - Why it happens: The search arguments match more than one image, for example an alias without
typeorlocation. - Fix: Add
location,typeandcloud_initto the data source, and run withTF_LOG=debugto see which images matched.
- Problem:
Summary
You can now describe TaskBoard's base infrastructure as code. The pinned provider authenticates with a token from the environment and turns five core ionoscloud_ resources into API v6 calls, waiting for each asynchronous request. Images come from data sources, state lives in IONOS Cloud Object Storage, hand-made resources can be imported, and each environment is created from a reviewed plan and destroyed again.
Key Points:
- Pin
ionos-cloud/ionoscloudto an exact version inrequired_providers; authenticate withIONOS_TOKEN locationon a data center andtypeon a server are immutable; changing them recreates the resource- The provider waits for each async request; tune waits with
timeouts(60 minutes by default) - Use the S3 backend with an IONOS Cloud Object Storage endpoint and Access Key plus Secret Key for shared state
- Import with
<datacenter-id>/<server-id>, generate config with-generate-config-out, and destroy ephemeral environments
Important Terminology:
- Provider pinning: An exact
versioninrequired_providersso every run uses the same provider release - Data source: A read-only lookup at plan time, such as
ionoscloud_image, that returns a single match or fails - Immutable argument: An argument the API cannot change in place, such as
location; changes force recreation - Remote backend: The
s3backend pointed at an IONOS Cloud Object Storage endpoint to share state across a team - Import block: HCL that adopts an existing resource into state by its ID, optionally generating its configuration
Next Steps
Continue Learning: Unit 1.3: Knowledge Check - Programmatic Foundations
Related Topics: