How to pass the templatefile function to user_data argument of EC2 resource in Terraform 0.12?

mel*_*ous 3 terraform terraform-provider-aws

I need to pass the below templatefile function to user_data in EC2 resource. Thank you

userdata.tf

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

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"
  }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ins 11

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

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"
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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"
  }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 这是一个很好的答案。解释得非常好,并提供了内联和分离声明的良好示例。 (3认同)