【问题标题】:How to pass the templatefile function to user_data argument of EC2 resource in Terraform 0.12?如何将模板文件函数传递给 Terraform 0.12 中 EC2 资源的 user_data 参数?
【发布时间】:2021-10-27 09:02:15
【问题描述】:

我需要将下面的templatefile 函数传递给 EC2 资源中的user_data。谢谢

userdata.tf

templatefile("${path.module}/init.ps1", {
  environment = var.env
  hostnames   = {"dev":"devhost","test":"testhost","prod":"prodhost"}
})

ec2.tf

resource "aws_instance" "web" {
  ami           = "ami-xxxxxxxxxxxxxxxxx"
  instance_type = "t2.micro"
  # how do I pass the templatefile Funtion here
  user_data     = ...

  tags = {
    Name = "HelloWorld"
  }
}

【问题讨论】:

    标签: terraform terraform-provider-aws


    【解决方案1】:

    因为templatefile 是一个内置函数,您可以将call 直接包含在您希望为其赋值的参数中:

    resource "aws_instance" "web" {
      ami           = "ami-xxxxxxxxxxxxxxxxx"
      instance_type = "t2.micro"
      user_data     = templatefile("${path.module}/init.ps1", {
        environment = var.env
        hostnames   = {"dev":"devhost","test":"testhost","prod":"prodhost"}
      })
    
      tags = {
        Name = "HelloWorld"
      }
    }
    

    如果模板仅为一个目的而定义,则上述方法是一种很好的方法,就像这里的情况一样,并且您不会在其他任何地方使用该结果。如果您想在多个位置使用相同的模板结果,您可以使用 local value 为该结果命名,然后您可以在模块的其他地方使用该名称:

    locals {
      web_user_data = templatefile("${path.module}/init.ps1", {
        environment = var.env
        hostnames   = {"dev":"devhost","test":"testhost","prod":"prodhost"}
      })
    }
    
    resource "aws_instance" "web" {
      ami           = "ami-xxxxxxxxxxxxxxxxx"
      instance_type = "t2.micro"
      user_data     = local.web_user_data
    
      tags = {
        Name = "HelloWorld"
      }
    }
    

    定义了本地值web_user_data,您可以使用local.web_user_data 在同一模块的其他地方引用它,从而在多个位置使用模板结果。但是,我建议仅当您需要在多个位置使用结果时才这样做;如果模板结果仅适用于这个特定实例的user_data,那么像我上面的第一个示例那样将其内联将使事情变得更简单,因此希望未来的读者和维护者更容易理解。

    【讨论】:

    • 这是一个很好的答案。解释得很好,并提供了很好的内联和分隔声明示例。
    猜你喜欢
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    • 2016-09-15
    • 1970-01-01
    相关资源
    最近更新 更多