Michael Niemand
Michael Niemand

Reputation: 1754

Terraform: create data source only when var is set?

I am writing a module to set up some servers on Hetzner and I want to enable the user to either

my variables.tf looks like this:

variable "ssh_key" {
  # create new key from local file
  default = "~/.ssh/id_rsa.pub"
}

variable "ssh_key_existing_fingerprint" {
  # if there's already a key on Hetzner, use it via it's fingerprint
  type = string
  default = null
}

my main.tf:

# Obtain ssh key data 
data "hcloud_ssh_key" "existing" {
  fingerprint = var.ssh_key_existing_fingerprint
}

resource "hcloud_ssh_key" "default" {
  name       = "servers default ssh key"
  public_key = file("${var.ssh_key}")
}

resource "hcloud_server" "server" {
  name          = "${var.server_name}"
  server_type   = "${var.server_flavor}"
  image         = "${var.server_image}"
  location      = "${var.server_location}"


  ssh_keys      = [var.ssh_key_existing_fingerprint ? data.hcloud_ssh_key.existing.id : hcloud_ssh_key.default.id]

The idea was to only obtain the data source ssh key if the fingerprint is not empty and then add either the key from the data source or the local key as fallback.

However, it doesn't work like this: The data source fails because an empty identifier is not allowed:

data.hcloud_ssh_key.existing: Reading...
╷
│ Error: please specify a id, a name, a fingerprint or a selector to lookup the sshkey
│ 
│   with data.hcloud_ssh_key.existing,
│   on main.tf line 11, in data "hcloud_ssh_key" "existing":
│   11: data "hcloud_ssh_key" "existing" {

How would one accomplish such a behavior?

Upvotes: 0

Views: 983

Answers (1)

Marcin
Marcin

Reputation: 238111

in this case it's null

It can't be null. Null by default eliminates the fingerprint attribute. Thus you are literally executing hcloud_ssh_key without any attributes, explaining why you get your error:

# this is what you are effectively calling
data "hcloud_ssh_key" "existing" {
}

Either ensure that you have always non-null value, or provide id, name as alternatives when fingerprint is null.

update

Make it optional:

data "hcloud_ssh_key" "existing" {
  count = var.ssh_key_existing_fingerprint == null ? 0 : 1
  fingerprint = var.ssh_key_existing_fingerprint
}

Upvotes: 2

Related Questions