How to set hostname in multiple Ubuntu VMs with Cloud-Init taken from VM name deployed with Terraform

53 Views Asked by At

I create multiple Ubuntu VMs with Terraform using the count operator. I want to set their hostnames according to the VMs' instance names.

This is the resource block creating the VM instances:

resource "ionoscloud_server" "server" {
    count                 = var.server_count
    name                  = "server${format("%02d", count.index + 1)}"
    datacenter_id         = ionoscloud_datacenter.ionosvdc.id
    availability_zone     = "AUTO"
    cores                 = var.cpu_cores
    ram                   = var.memory
    cpu_family            = var.cpu_family
    image_name            = var.image_name
    image_password        = "myPassword"
    type                  = "ENTERPRISE"
    ssh_keys              = ["/home/myuser/.ssh/id_ed25519.pub"]
    volume {
        name              = "OS"
        size              = var.disk_size
        disk_type         = var.disk_type
        user_data         = user_data = base64encode(templatefile("${path.module}/template/cloud-config.yaml"
    }
    nic {
        lan               = ionoscloud_lan.wan.id
        name              = "WAN_NIC"
        dhcp              = true
        firewall_active   = true
        firewall_type     = "INGRESS"
        ips               = [ ionoscloud_ipblock.pipblock.ips[count.index] ]
    }
}

The cloud-config file:

#cloud-config

bootcmd:
  - sed -i -e 's/XKBLAYOUT="us"/XKBLAYOUT="de"/g' /etc/default/keyboard

package_update: true
package_upgrade: true
package_reboot_if_required: true

packages:
  - openjdk-11-jdk
  - jmeter

hostname: ?

The hostname shall be the same as the respective instance name, i.e. server01, server02, etc. --> see resource block:

name                  = "server${format("%02d", count.index + 1)}"

How could I do that?

Thanks in advance!

I used the same expression in the Cloud-Init file, but it didn't work:

hostname: "server${format("%02d", count.index + 1)}"

I tried also to get the name from the resource, didn't work either:

hostname: resource.ionoscloud_server.server.name
0

There are 0 best solutions below