tailscale / terraform-provider-tailscale

Terraform provider for Tailscale
https://registry.terraform.io/providers/tailscale/tailscale
MIT License
256 stars 47 forks source link

FR: Add ability to create device-specific auth key #232

Open NiklasRosenstein opened 1 year ago

NiklasRosenstein commented 1 year ago

Is your feature request related to a problem? Please describe.

I'm trying to set up a Tailscale connector with cloud-init. I need to pass a Tailscale auth key into the cloud-config.yml. There are two issues with that

The issue with recreation is that the old Tailscale device stays in the machine list, unconnected, and using up the host name that the recreated server should reuse.

It would be nice if a pre-authorized auth key dedicated for a singular device could be added.

resource "tailscale_device_auth_key" "main" {
  name = "my-tailscale-connector"
}

resource "hcloud_server" "main" {
  name= tailscale_device_auth_key.main.name
  # ...
  user_data = yamlencode({
    # ...
    "runcmd": [
      # ...
      "tailscale up --auth-key \"${tailscale_device_auth_key.main.key}\"",
    ]
  })
mlangenberg commented 1 year ago

Coincidentally I am also tinkering with Terraform, Tailscale and Hetzner, trying to create new server instances that are by default only reachable via the tailnet. I ran into the same issues as you did.

The tailscale_tailnet_key resource does allow the creation of a single-use auth-key. Since it ends up in a plain text cloud-config file on the new host, it might be better to use this with a short TTL. Could that work for you?

For the cloud-config.yml, I am using a templatefile and with the tailscale_key as a variable. I wish I could tell Terraform to ignore this particular variable in the state, but as far as I know, this is not possible.

We can do this for the whole cloud config:

resource "hcloud_server" "main" {
   user_data = templatefile("cloud-config.yml.tftpl", {
    tailscale_key = var.tailscale_key
  })

  lifecycle {
    ignore_changes = [
      user_data
    }
   }
}

At least this does not replace the server every time the tailscale key expires. It does mean that you manually have to run terraform apply -replace=“hcloud_server.main” for other changes to the cloud config which is acceptable to me.

In https://github.com/tailscale/terraform-provider-tailscale/issues/68#issuecomment-1314966145 there is a workaround for manually calling the Tailscale API to delete a device by hostname, before creating a new one. I think I would prefer calling the Tailscale API from the machine running Terraform with local-exec if that is possible.

evilhamsterman commented 10 months ago

@mlangenberg TTL doesn't even need to be that short lived, since once the key is used it's not longer valid