我正在编写一个模块,用于在Hetzner上设置一些服务器,并且我希望使用户能够
的情况下以变量的形式提供它的路径来添加新的ssh键
我的variables.tf看起来是这样的:
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
}我的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]其想法是,只有在指纹不是空的情况下才能获得数据源ssh密钥,然后添加数据源的密钥或本地密钥作为后盾。
但是,它不像这样工作:数据源失败是因为不允许空标识符:
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" {怎样才能做到这样的行为呢?
发布于 2022-08-24 10:58:03
在本例中为空
不可能是空的。默认情况下,Null将消除fingerprint属性。因此,您实际上是在没有任何属性的情况下执行hcloud_ssh_key,从而解释了为什么会出现错误:
# this is what you are effectively calling
data "hcloud_ssh_key" "existing" {
}要么确保始终具有非空值,要么在id、name为null时提供fingerprint作为替代方案。
更新
使之可选:
data "hcloud_ssh_key" "existing" {
count = var.ssh_key_existing_fingerprint == null ? 0 : 1
fingerprint = var.ssh_key_existing_fingerprint
}https://stackoverflow.com/questions/73470688
复制相似问题