如何将模板文件函数传递给 Terraform 0.12 中 EC2 资源的 user_data 参数?
How to pass the templatefile function to user_data argument of EC2 resource in Terraform 0.12?
我需要将下面的 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"
}
}
因为 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
,那么将其内联,如我在上面的第一个示例中那样,将使事情变得更简单,因此希望将来的 reader 和维护者更容易理解。
我需要将下面的 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"
}
}
因为 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
,那么将其内联,如我在上面的第一个示例中那样,将使事情变得更简单,因此希望将来的 reader 和维护者更容易理解。