【问题标题】:Reference multiple aws_instance in terraform for template output在 terraform 中引用多个 aws_instance 以进行模板输出
【发布时间】:2020-05-21 00:26:12
【问题描述】:

我们希望将服务部署到多个区域。 看起来因为aws 提供程序,我们不能只使用countfor_each,因为不能对提供程序进行插值。因此我需要手动设置:

resource "aws_instance" "app-us-west-1" {
   provider = aws.us-west-1
   #other stuff
}

resource "aws_instance" "app-us-east-1" {
  provider = aws.us-east-1
  #other stuff
}

我想在运行它时创建一个包含所有创建的 IP 的文件(用于 ansible 库存)。

我在看这个答案: https://stackoverflow.com/a/61788089/169252

并尝试根据我的情况对其进行调整:

resource "local_file" "app-hosts" {
   content = templatefile("${path.module}/templates/app_hosts.tpl",
     {
        hosts = aws_instance[*].public_ip
     }
   )
   filename = "app-hosts.cfg"
}

然后相应地设置模板。

但这失败了:

Error: Invalid reference

  on app.tf line 144, in resource "local_file" "app-hosts":
 122:        hosts = aws_instance[*].public_ip

A reference to a resource type must be followed by at least one attribute
access, specifying the resource name

我怀疑我不能像这样引用上面定义的所有aws_instance。也许要引用此文件中的所有aws_instance,我需要使用不同的语法。

或者我可能需要以某种方式使用模块。有人可以确认吗?

使用 terraform v0.12.24

编辑:提供程序定义使用别名,并且都在同一个 app.tf 中,我天真地假设可以使用 terraform apply 一次性申请(我是否提到我是 terraform 的初学者? ):

  provider "aws" {
     alias  = "us-east-1"
     region = "us-east-1"
   }

  provider "aws" {
    alias  = "us-west-1"
    region = "us-west-1"
  }

【问题讨论】:

  • 您如何为不同的提供商区域应用配置?这是否连续适用于不同的别名、具有不同根配置输入别名的多个模块声明等?
  • @MattSchuchard 感谢您的加入。我是 terraform 初学者。我正在使用别名。我将编辑问题以添加一些代码,认为这并不重要。

标签: terraform


【解决方案1】:

我目前的解决方法是不做join,而只是单独列出它们:

 {
   host1 = aws_instance.app-us-west-1.public_ip
   host2 = aws_instance.app-us-east-1.public_ip
   # more hosts
 }

【讨论】:

    猜你喜欢
    • 2022-11-07
    • 2021-07-16
    • 2018-07-09
    • 2019-06-28
    • 2017-05-26
    • 2021-12-10
    • 2021-03-21
    • 2019-12-12
    • 1970-01-01
    相关资源
    最近更新 更多