【问题标题】:How to add a resource using the same module?如何使用相同的模块添加资源?
【发布时间】:2019-09-28 14:27:03
【问题描述】:

Terraform 新手在这里。我有一个在 GCP 中创建实例的模块。我正在使用变量和 terraform.tfvars 来初始化它们。我成功创建了一个实例 - 比如说 instance-1。但是当我修改 .tfvars 文件以创建第二个实例(除了第一个)时,它说它必须销毁第一个实例。如何运行模块以“添加”实例,而不是“替换实例”?我知道创建的第一个实例是在 terraform.tfstate 中。但这并不能解释无法“添加”实例。

也许我错了,但我将“模块”(及其配置文件)视为函数——这样我就可以随时使用不同的参数调用它们。情况似乎并非如此。

【问题讨论】:

    标签: terraform terraform-provider-gcp


    【解决方案1】:

    Terraform 将尝试维护与您的资源定义匹配的已部署资源。 如果您同时需要两个实例,那么您应该在 .tf 文件中同时描述它们。

    例如。相同的实例,为您的定义添加计数

    resource "some_resource" "example" {
      count = 2
      name = "example-${count.index}"
    }
    

    例如。具有特定值的两种不同资源

    resource "some_resource" "example-1" {
      name = "example-1"
      size = "small"
    }
    resource "some_resource" "example-2" {
      name = "example-2"
      size = "big"
    }
    

    你可以为每个资源在 tfvars 中设置具体的值

    resource "some_resource" "example" {
      count = 2
      name = "example-${count.index}"
      size = ${vars.mysize[count.index]}
    }
    variable mysize {}
    

    使用 tfvars 文件:

    mysize = ["small", "big"]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      • 1970-01-01
      • 2022-10-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多