Search code examples
terraformterraform-template-file

How can I variablize a template and text file in Terraform


I have this template named : email-passwordless.ar.html.ftl

Its content is as follows:

[#setting url_escaping_charset="UTF-8"]
[#assign url = "https://google.com/auth/prod/${code}" /]

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="ar" dir="rtl">
<head>

The resource using this template is :

resource "fusionauth_email" "passwrodless_template" {
  name                  = var.passwordless_email_template_name
  localized_subjects = {
    "ar" = var.email_passwordless_localized_subjects
  }
  localized_html_templates = {
    "ar" = file("${path.module}/email-templates/email-passwordless.ar.html.ftl")
  }
}

The template will be used across different environments and hence its URL will be different for each environment. How can I make the URL in the template as variable and pass its value in resource or something similar to it


Solution

  • You would use the templatefile function for this use case. You can create the email-passwordless.ar.html.tmpl file in the same path as your current file:

    [#setting url_escaping_charset="UTF-8"]
    [#assign url = "${url}" /]
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html lang="ar" dir="rtl">
    <head>
    

    where we replace your already named string type variable code with url for the entire url. After assigning a value to var.url in your Terraform config, its value can be passed to the template renderer through the templatefile function arguments:

    localized_html_templates = {
      "ar" = templatefile("${path.module}/email-templates/email-passwordless.ar.html.tmpl", { url = var.url })
    }