如何将 templatefile 函数传递给 Terraform 0.12 中 EC2 资源的 user_data 参数?

2024-04-12

我需要通过以下templatefile功能为user_data在 EC2 资源中。谢谢

用户数据.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"
  }
}

Because templatefile是一个内置函数,您可以call https://www.terraform.io/docs/configuration/expressions.html#function-calls通过将其直接包含在您希望将值分配给的参数中:

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"
  }
}

如果模板仅出于一个目的而定义(就像此处的情况一样),并且您不会在其他任何地方使用该结果,则上述方法是一种好方法。如果您想在多个位置使用相同的模板结果,您可以使用本地价值 https://www.terraform.io/docs/configuration/locals.html为该结果指定一个名称,然后您可以在模块中的其他位置使用该名称:

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在同一模块的其他地方引用它,从而在多个位置使用模板结果。但是,我建议仅当您这样做时need在多个位置使用结果;如果模板结果仅适用于该特定实例user_data然后将其内联,如上面的第一个示例所示,将使事情变得更简单,从而希望未来的读者和维护者更容易理解。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何将 templatefile 函数传递给 Terraform 0.12 中 EC2 资源的 user_data 参数? 的相关文章

随机推荐