首页 > 解决方案 > 在 terraform 中引用多个 aws_instance 以进行模板输出

问题描述

我们希望将服务部署到多个区域。看起来因为aws提供者,我们不能只使用countor for_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此文件中的所有内容,我需要使用不同的语法。

或者也许我需要以某种方式使用模块。有人可以证实这一点吗?

使用地形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"
  }

标签: terraform

解决方案


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

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

推荐阅读