Unable to use templatefile() with user data

Hello Everyone,

I want to pass a file named app.sh to the user data in my launch template. However, getting following error:

Code Snippet:

resource "aws_launch_template" "LT_main" {
  instance_type          = "t2.micro"
  image_id               = data.aws_ami.LatestAMI.image_id
  vpc_security_group_ids = [var.ec2sg]
  user_data = file(templatefile("${path.module}/app.sh",{
    DB_HOST           = var.DB_HOST
    DB_USER           = var.DB_USER
    DB_PASSWORD_PARAM = var.DB_PASSWORD_PARAM
    DB_PORT           = var.DB_PORT
    DB_NAME           = var.DB_NAME
  }))
  depends_on = [var.DB_HOST]
}

Error:

Error: Invalid function argument
on module/Compute/main.tf line 27, in resource "aws_launch_template" "LT_main":
  user_data = file(templatefile("${path.module}/app.sh",{
    DB_HOST           = var.DB_HOST
    DB_USER           = var.DB_USER
    DB_PASSWORD_PARAM = var.DB_PASSWORD_PARAM
    DB_PORT           = var.DB_PORT
    DB_NAME           = var.DB_NAME
  }))
while calling file(path)
path.module is "module/Compute"
var.DB_HOST is "*********.rds.amazonaws.com:3306"
var.DB_NAME is "maindb"
var.DB_PORT is 3306
var.DB_USER is "*****"
Invalid value for "path" parameter: no file exists at (sensitive value); this function works only with files that are distributed as part of the configuration source code, so if this file will be created by a resource in this configuration you must instead obtain this result from an attribute of that resource.

However, it works fine if I do not provide any argument:

Working:

resource "aws_launch_template" "LT_main" {
  instance_type          = "t2.micro"
  image_id               = data.aws_ami.LatestAMI.image_id
  vpc_security_group_ids = [var.ec2sg]
  user_data = file("${path.module}/app.sh")
  depends_on = [var.DB_HOST]
}

OR
user_data = filebase64(“${path.module}/app.sh”) also works. templatefile() never works.

For entire code, please feel free to refer to the following repo:

Any Clue?

Hi @imsiddhant,

The templatefile function returns the contents of the file, not the path, so there’s no reason to wrap it in the file function. Wrapping that in the file function is trying to open a file with the name equal to the entire contents of the templatefile result.

1 Like

Thanks for the reply!

Looks like the following is working now:

 user_data = base64encode(templatefile("module/Compute/userdata/app.sh", {
    DB_HOST           = var.DB_HOST
    DB_USER           = var.DB_USER
    DB_PASSWORD_PARAM = var.DB_PASSWORD_PARAM
    DB_PORT           = var.DB_PORT
    DB_NAME           = var.DB_NAME
  }))

This topic was automatically closed 62 days after the last reply. New replies are no longer allowed.