14 min read

Learning Objectives

By the end of this module, you will be able to:

  • Build a three-tier network of public and private LANs with `ionoscloud_lan`, using explicit private CIDR blocks
  • Attach servers to several LANs with inline `nic` blocks and the `ionoscloud_nic` resource
  • Give private LANs outbound internet access with `ionoscloud_natgateway` and SNAT rules, and route server traffic to it
  • Connect an on-premises network with `ionoscloud_vpn_ipsec_gateway` and `ionoscloud_vpn_ipsec_tunnel`
  • Manage DNS zones and records as code with `ionoscloud_dns_zone` and `ionoscloud_dns_record`

Unit 2.2: Network and Connectivity as Code

Introduction

In Unit 2.1 your API server and worker sat on one public LAN. That is fine for a test, but TaskBoard's database and worker should never be reachable from the internet, and the operations team wants a private path from the office network. You need network segmentation, controlled egress, and a stable DNS name for the API, all reviewable in Git.

In this unit you build that network stack with Terraform: a public LAN for the API entry point, an app LAN and a DB LAN that stay private, a Managed NAT Gateway for outbound traffic from the private tiers, an IPSec VPN gateway for hybrid access, and Cloud DNS records for the API. In the Code Lab you deploy the network and verify connectivity between the tiers.

1. LANs for Multi-Tier Segmentation

resource "ionoscloud_lan" "public" {
  datacenter_id = ionoscloud_datacenter.taskboard.id
  name          = "taskboard-public"
  public        = true
}

resource "ionoscloud_lan" "app" {
  datacenter_id   = ionoscloud_datacenter.taskboard.id
  name            = "taskboard-app"
  public          = false
  ipv4_cidr_block = "10.10.1.0/24"
}

resource "ionoscloud_lan" "db" {
  datacenter_id   = ionoscloud_datacenter.taskboard.id
  name            = "taskboard-db"
  public          = false
  ipv4_cidr_block = "10.10.2.0/24"
}

public = true makes a LAN face the internet; public = false keeps it private and isolates its traffic from external access. The public LAN already exists from Unit 1.2; the app and DB LANs are new.

1.1 Choosing the Private CIDR Blocks

If you omit ipv4_cidr_block on a private LAN, a /23 block from the 10.0.0.0/8 range is assigned automatically. Set it explicitly when you need predictable addresses for routes, firewall rules or a VPN. A custom block must:

  • be within a private RFC 1918 range (10.0.0.0/8, 172.16.0.0/12 or 192.168.0.0/16)
  • have a prefix length between /23 and /28
  • be aligned to its prefix boundary (10.5.0.0/24, not 10.5.0.1/24)

It can only be set on private LANs. Changing it updates the LAN in place.

1.2 Reading CIDR Errors

When the API rejects a block, the provider error contains the API error code:

Code Meaning
536 Not aligned to its prefix boundary
602 Overlaps a block already in use
654 Not a private range
655 Larger than /23
656 Set on a public LAN

As the table shows, most errors come from copy-paste blocks. Keep all blocks of an environment in one locals map so that overlaps show up in review:

locals {
  cidr = {
    app = "10.10.1.0/24"
    db  = "10.10.2.0/24"
  }
}

1.3 Reserved Addresses for Managed Services

DHCP never assigns addresses ending in .0 to .9 or .224 to .255. Addresses .2 to .9 are reserved for managed services. When you give a managed service such as a NAT gateway or VPN gateway a LAN address, take it from that reserved range to avoid conflicts with DHCP-assigned IP addresses. The examples in this unit use .4 for the NAT gateway and .5 for the VPN gateway.

2. NICs: Attaching Servers to LANs

2.1 Inline and Separate NICs

The API server needs a public NIC for clients and a private NIC for the app tier. Keep the first NIC inline in the server and add the second as its own resource:

resource "ionoscloud_nic" "api_app" {
  datacenter_id = ionoscloud_datacenter.taskboard.id
  server_id     = ionoscloud_server.api.id
  lan           = ionoscloud_lan.app.id
  name          = "app"
  dhcp          = true
  ips           = ["10.10.1.11"]
}

datacenter_id, server_id and lan are required, and lan is the numeric LAN ID. ips takes a list of addresses; passing null or an empty list assigns an address automatically. Explicitly assigned public IPs must come from reserved IP blocks (Unit 2.1). The NIC's private IPv4 address is assigned statically to its MAC address, so a DHCP address on a private LAN stays with the NIC.

2.2 Private-Only Servers

The worker has no public NIC at all:

resource "ionoscloud_vcpu_server" "worker" {
  # ... arguments from Unit 2.1 ...
  nic {
    lan  = ionoscloud_lan.app.id
    name = "app"
    dhcp = true
    ips  = ["10.10.1.21"]
  }
}

The mac argument of a NIC can be set on creation only and is immutable; if you leave it unset, the API assigns one.

3. Outbound Access with the Managed NAT Gateway

The Managed NAT Gateway lets VMs in a VDC reach the internet without a public network interface. It provides Source NAT (SNAT) only: VMs initiate connections and receive responses, and inbound connections initiated from the internet are not accepted.

3.1 Gateway and Rules

resource "ionoscloud_ipblock" "nat" {
  name     = "taskboard-nat-ip"
  location = ionoscloud_datacenter.taskboard.location
  size     = 1
}

resource "ionoscloud_natgateway" "egress" {
  datacenter_id = ionoscloud_datacenter.taskboard.id
  name          = "taskboard-nat"
  public_ips    = [ionoscloud_ipblock.nat.ips[0]]

  lans {
    id          = ionoscloud_lan.app.id
    gateway_ips = ["10.10.1.4"]
  }
  lans {
    id          = ionoscloud_lan.db.id
    gateway_ips = ["10.10.2.4"]
  }
}

resource "ionoscloud_natgateway_rule" "app_out" {
  datacenter_id = ionoscloud_datacenter.taskboard.id
  natgateway_id = ionoscloud_natgateway.egress.id
  name          = "app-egress"
  type          = "SNAT"
  protocol      = "ALL"
  source_subnet = local.cidr.app
  public_ip     = ionoscloud_ipblock.nat.ips[0]
}

public_ips must be reserved IP addresses in the gateway's location. Each lans block connects one private LAN; a gateway supports up to six private networks. Only private LANs can be connected, and a LAN connected to the gateway cannot be changed from private to public. gateway_ips is auto-generated if you omit it, but a fixed address makes the route in Section 3.2 predictable.

A rule's protocol is TCP, UDP, ICMP or ALL (the default). target_subnet and target_port_range narrow the rule to destinations; without them, the rule matches any address and port. Add a second rule with source_subnet = local.cidr.db for the DB tier.

3.2 Routing Server Traffic to the Gateway

The NAT gateway does not inject a default route into your servers. The routing table of each private VM must point its default route to the gateway IP, or contain a dedicated route for every internet target. Do it at first boot with cloud-init:

#cloud-config
runcmd:
  - ip route replace default via 10.10.1.4

Make the route persistent in the image's network configuration for production. If the VM resolves DNS through this default route, make sure SNAT rules cover UDP, or DNS resolution may stop working. The ALL rule above covers it.

4. Hybrid Connectivity with the VPN Gateway

The VPN Gateway supports IPSec and WireGuard. This unit uses IPSec with IKEv2 and a Pre-Shared Key (PSK).

4.1 Gateway and Tunnel

resource "ionoscloud_vpn_ipsec_gateway" "office" {
  name        = "taskboard-office-vpn"
  location    = ionoscloud_datacenter.taskboard.location
  # ionoscloud_ipblock.vpn: a one-address block, like ionoscloud_ipblock.nat
  gateway_ip  = ionoscloud_ipblock.vpn.ips[0]
  version     = "IKEv2"
  description = "Office to TaskBoard app LAN"
  tier        = "STANDARD"

  connections {
    datacenter_id = ionoscloud_datacenter.taskboard.id
    lan_id        = ionoscloud_lan.app.id
    ipv4_cidr     = "10.10.1.5/24"
  }
}

resource "ionoscloud_vpn_ipsec_tunnel" "office" {
  location    = ionoscloud_datacenter.taskboard.location
  gateway_id  = ionoscloud_vpn_ipsec_gateway.office.id
  name        = "office-tunnel"
  remote_host = var.office_vpn_host

  auth {
    method  = "PSK"
    psk_key = var.vpn_psk
  }
  ike {
    diffie_hellman_group = "16-MODP4096"
    encryption_algorithm = "AES256"
    integrity_algorithm  = "SHA256"
  }
  esp {
    diffie_hellman_group = "16-MODP4096"
    encryption_algorithm = "AES256"
    integrity_algorithm  = "SHA256"
  }

  cloud_network_cidrs = [local.cidr.app]
  peer_network_cidrs  = [var.office_cidr]
}

gateway_ip is a reserved public IP in the same data center location as the connections, and all connections must belong to the same VDC. ipv4_cidr is the private gateway address that LAN clients route through; it must be within the LAN's subnet. Declare var.vpn_psk with sensitive = true. The product does not create PSKs for you, and a 32-character key is recommended.

4.2 Rules That Affect Your Code

  • Static routing only. BGP and dynamic routing are not available. As with NAT, servers need a route to the peer network through the gateway's LAN address, for example ip route add 192.168.50.0/24 via 10.10.1.5.
  • Not DHCP aware. The gateway's LAN address is static, which is why it comes from the reserved range (Section 1.3).
  • IPv4 tunnel endpoints. The tunnel endpoint and the gateway IP address are IPv4 only.
  • Tier limits. STANDARD allows 5 LANs and 10 tunnels, ENHANCED 10 LANs and 20 tunnels, PREMIUM 15 LANs and 30 tunnels.
  • Delete order. Delete the VPN gateway before the connected VDC. Terraform follows the dependency graph, but a manual data center deletion breaks this rule.

The VPN Gateway API is regional. Use the endpoint of your VDC's location, for example https://vpn.de-txl.ionos.com/ipsecgateways for de/txl.

5. DNS as Code with Cloud DNS

resource "ionoscloud_dns_zone" "taskboard" {
  name        = "taskboard.example.com"
  description = "TaskBoard public zone"
  enabled     = true
}

resource "ionoscloud_dns_record" "api" {
  zone_id = ionoscloud_dns_zone.taskboard.id
  name    = "api"
  type    = "A"
  content = ionoscloud_ipblock.api.ips[0]
  ttl     = 300
  enabled = true
}

Only tokens are accepted for authorization in the ionoscloud_dns_zone and ionoscloud_dns_record resources, so set IONOS_TOKEN (Unit 1.2) rather than a username and password. Only contract owners, administrators and users with the accessAndManageDns privilege can create and manage primary zones and records through the API.

5.1 Record Settings

name is immutable on both the zone and the record. The record ttl defaults to 3600 seconds; Cloud DNS accepts TTLs from 60 to 604800 seconds. A short TTL like 300 lets you move the API to a new IP address quickly. Supported types include A, AAAA, CNAME, ALIAS, MX, TXT, SRV and CAA, and wildcard records are supported.

5.2 Delegating the Domain

A zone answers queries only after your registrar points the domain to the Cloud DNS name servers: ns-ic.ui-dns.com, ns-ic.ui-dns.de, ns-ic.ui-dns.org and ns-ic.ui-dns.biz. Name server changes can take up to 48 hours to propagate. Test the zone directly first:

dig +short api.taskboard.example.com @ns-ic.ui-dns.com

API Reference Quick Card

Key API endpoints behind this unit's resources:

Method Endpoint Description
POST /datacenters/{datacenterId}/lans Created by ionoscloud_lan
POST /datacenters/{datacenterId}/servers/{serverId}/nics Created by ionoscloud_nic
POST /datacenters/{datacenterId}/natgateways Created by ionoscloud_natgateway
POST /ipsecgateways Created by ionoscloud_vpn_ipsec_gateway (VPN API, https://vpn.{region}.ionos.com)
POST /zones/{zoneId}/records Created by ionoscloud_dns_record (DNS API, https://dns.de-fra.ionos.com)

Base URL: https://api.ionos.com/cloudapi/v6 (VPN and DNS use their own base URLs, shown above) Authentication: Authorization: Bearer <token>

Code Lab

Objective: Build TaskBoard's three-tier network with Terraform (public, app and DB LANs, NICs and a NAT gateway), then verify connectivity between the tiers and outbound access from the private tier.

Prerequisites:

  • The compute tier project from Unit 2.1 and IONOS_TOKEN set
  • Terraform with the provider pinned as in Unit 1.2
  • Your SSH key in TF_VAR_ssh_public_key

Step 1: Add the private LANs

Add the app and DB LANs from Section 1 and the locals block from Section 1.2 to main.tf. Then plan:

terraform plan | tail -n 1

Expected output:

Plan: 2 to add, 0 to change, 0 to destroy.

Step 2: Move the worker to the app LAN and add the API server's app NIC

Change the worker's inline nic to the version in Section 2.2 and add ionoscloud_nic.api_app from Section 2.1. Save the cloud-config from Section 3.2 as cloud-init/worker.yaml and add user_data = base64encode(file("${path.module}/cloud-init/worker.yaml")) to the worker's volume block. Because user_data only applies to a new volume, the worker must be rebuilt; it is stateless, so that is safe.

terraform plan -replace=ionoscloud_vcpu_server.worker | grep -E "replaced|created"

Expected output:

  # ionoscloud_lan.app will be created
  # ionoscloud_lan.db will be created
  # ionoscloud_nic.api_app will be created
  # ionoscloud_vcpu_server.worker will be replaced, as requested

Step 3: Add the NAT gateway and rules

Add ionoscloud_ipblock.nat, ionoscloud_natgateway.egress and both SNAT rules from Section 3.1, then apply:

terraform apply -replace=ionoscloud_vcpu_server.worker -auto-approve | tail -n 1

Expected output:

Apply complete! Resources: ... added, ... changed, ... destroyed.

Step 4: Check the NAT gateway through the API

DC=$(terraform output -raw datacenter_id)
curl -s -H "Authorization: Bearer $IONOS_TOKEN" \
  "https://api.ionos.com/cloudapi/v6/datacenters/$DC/natgateways?depth=2" \
  | jq '.items[0].properties | {name, publicIps, lans}'

Expected output:

{
  "name": "taskboard-nat",
  "publicIps": ["<nat IP>"],
  "lans": [ { "id": <app LAN id>, "gatewayIps": ["10.10.1.4"] }, { "id": <db LAN id>, "gatewayIps": ["10.10.2.4"] } ]
}

Step 5: Reach the worker over the app LAN

ssh -J root@"$(terraform output -raw api_public_ip)" root@10.10.1.21 'hostname; ip route show default'

Expected output:

taskboard-worker-01
default via 10.10.1.4 dev ...

Step 6: Test outbound access from the private worker

ssh -J root@"$(terraform output -raw api_public_ip)" root@10.10.1.21 \
  'curl -sI --max-time 10 https://api.ionos.com/cloudapi/v6/ | head -n 1'

Expected output:

HTTP/... <status code>

Any HTTP status line proves that the private worker reached the internet through the NAT gateway; a timeout means the route or the SNAT rule is missing.

Validation Checklist:

  • [ ] Three LANs exist: one public, two private with the CIDR blocks you set
  • [ ] The worker has no public IP and is reachable only through the API server
  • [ ] The worker's default route points to 10.10.1.4
  • [ ] The worker reaches the internet through the NAT gateway's public IP

Cleanup:

terraform destroy -auto-approve

Common Pitfalls

Developer mistakes to avoid with this unit's topic:

  1. NAT gateway created, but private servers have no internet

    • Problem: curl from a private server times out although the NAT gateway and rules exist.
    • Why it happens: The gateway does not inject a default route. The server still has no route to the gateway IP.
    • Fix: Set gateway_ips explicitly and add ip route replace default via <gateway ip> in cloud-init (Section 3.2). If name resolution fails, check that SNAT rules cover UDP.
  2. Static gateway address collides with DHCP

    • Problem: A VPN or NAT gateway address conflicts with a server, and traffic goes to the wrong host.
    • Why it happens: The VPN gateway's interface is not DHCP aware, and you picked an address DHCP may assign.
    • Fix: Use addresses from the reserved managed-services range .2 to .9 (Section 1.3), and give servers addresses from .10 upwards.
  3. DNS resources fail with basic authentication

    • Problem: ionoscloud_dns_zone fails to authenticate in a pipeline that uses IONOS_USERNAME and IONOS_PASSWORD.
    • Why it happens: Only tokens are accepted for authorization in the DNS resources.
    • Fix: Generate a token, store it as a CI secret and export it as IONOS_TOKEN.

Summary

You can now describe TaskBoard's network as code. Public and private LANs separate the tiers with explicit RFC 1918 blocks, servers join several LANs through inline and separate NICs, and a Managed NAT Gateway gives private servers outbound access once their routes point to it. An IPSec VPN gateway connects the office with static routes, and Cloud DNS publishes a stable name for the API.

Key Points:

  • Private LAN blocks must be RFC 1918, /23 to /28 and aligned; omitted blocks get a /23 from 10.0.0.0/8
  • Give managed services LAN addresses from the reserved .2 to .9 range
  • The NAT gateway is SNAT only, connects up to six private LANs, and needs a route on each server
  • The VPN gateway uses static routing only, IKEv2 with PSK for IPSec, and a regional API endpoint
  • DNS resources accept tokens only; delegate the domain to the four Cloud DNS name servers

Important Terminology:

  • Private LAN: A LAN with public = false whose NICs get private addresses and no internet exposure
  • SNAT rule: A NAT gateway rule that masks the source address of outgoing packets with a public IP
  • Gateway IP: The NAT or VPN gateway's own address in a private LAN, used as the route target
  • Pre-Shared Key (PSK): The shared secret that authenticates both ends of an IPSec tunnel
  • Delegation: Pointing a domain's name servers at Cloud DNS so that the zone answers public queries

Next Steps

Continue Learning: Unit 2.3: Load Balancing and Security as Code

Related Topics: