Terraform在定义新资源时会破坏资源

时间:2019-09-04 08:28:00

标签: terraform

我正在使用upcloud provider插件和terraform 0.12.7创建服务器的新实例。不幸的是,插件不在TF的主要站点https://github.com/UpCloudLtd/terraform-provider-upcloud中,因此必须使用go语言进行安装,但这部分工作正常。

    provider "upcloud" {
    # Your UpCloud credentials are read from the environment variables
    # export UPCLOUD_USERNAME="Username for Upcloud API user"
    # export UPCLOUD_PASSWORD="Password for Upcloud API user"
}

resource "upcloud_server" "test" {
    # System hostname
    hostname = "test.example.com"

    # Availability zone
    zone = "de-fra1"

    # Number of CPUs and memory in MB
    cpu = "4"
    mem = "8192"

    storage_devices {
          # OS root disk size
          size = "20"
          action = "clone"

          # Template Ubuntu 18.04
          storage = "01000000-0000-4000-8000-000030080200"
          tier = "maxiops"
    }

    # Include at least one public SSH key
    login {
        user = "root"
        keys = [
            # File module reads file as-is including trailing linefeed that breaks during terraform apply
            "${replace(file("${var.ssh_pubkey}"), "\n", "")}"
        ]
    }

    # Configuring connection details
    connection {
        host = "${self.ipv4_address}"
        type = "ssh"
        user = "root"
        private_key = "${file("${var.ssh_privkey}")}"
    }

    # Remotely executing a command on the server
    provisioner "remote-exec" {
        inline = [
            "echo 'Hello world!'"
        ]
    }
}

output "server_ip" {
    value = "${upcloud_server.test.ipv4_address}"
}

它成功创建了资源。现在,我将资源名称更改为“ test5”(也包括主机名和其他硬编码值),以运行terraform plan,然后它告诉我,即使在tf状态文件中定义了“ test”资源,它也想销毁它,而我没有要求删除它。我尝试定义terraform后端“本地”,始终保持工作空间不变,但是并没有改变。我做错了什么?如果我使用操作系统模板或快照卷ID,则其工作方式相同。

还有一种方法可以对此资源名称进行参数化(或在输出部分中,self在此处不起作用),因此我不必运行sed命令来保持名称一致?其他变量可以在地形计划中进行调整或应用-没问题。预先感谢您的回复

1 个答案:

答案 0 :(得分:0)

您不能像这样重命名资源...

如果这样做,terraform会在有关其状态文件的资源定义中识别以下两项更改:

  • 资源test应该删除(因为状态文件中存储的资源的定义已消失)
  • 资源test5应该创建(因为状态文件中不存在该资源)

如果要重命名资源,则必须相应地更新状态文件。检查我们的Terraform Command 'state mv'

在这种情况下,您需要运行terraform state mv upcloud_server.test upcloud_server.test5 在资源定义中重命名资源。

然后,定义将再次与状态文件匹配。

相关问题