Built-in terraform replace function adding unwanted backslash

I have a PEM file that I read using the built-in terraform file() function. When I run ‘terraform plan’ I see this (PEM file contents modified here):

key = <<-EOT
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5P0Z4OUD5PSjri8xexGo
6eQ39NGyQbXamIgWAwvnAs/oDRVqEejE2nwDhnpykaCGLkuDEN0LPd2wF+vC2Cq3
-----END PUBLIC KEY-----
EOT

What I need to see is this:

key = “-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5P0Z4OUD5PSjri8xexGo\n6eQ39NGyQbXamIgWAwvnAs/oDRVqEejE2nwDhnpykaCGLkuDEN0LPd2wF+vC2Cq3\n-----END PUBLIC KEY-----\n”

In other words one long string with ‘\n’ in place of linefeed / newline.

I figured out that I can replace this from my .tf file…
key = file(“myKey.pem”)

…with this…
key = replace(file(“myKey.pem”), “\n”, “\\n”)

…and that ALMOST gets me what I want. Unfortunately what I see now when I run ‘terraform plan’ is this:

key = “-----BEGIN PUBLIC KEY-----\\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5P0Z4OUD5PSjri8xexGo\\n6eQ39NGyQbXamIgWAwvnAs/oDRVqEejE2nwDhnpykaCGLkuDEN0LPd2wF+vC2Cq3\\n-----END PUBLIC KEY-----\\n”

Meaning there is an unwanted EXTRA backslash preceding the ‘\n’. I have not figured out how to avoid getting this unwanted extra backslash. Does anyone know?

Thanks in advance!

Hi @asharma2,

According to your description, your first string was what you wanted. The following two outputs are exactly equivalent:

key = <<-EOT
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5P0Z4OUD5PSjri8xexGo
6eQ39NGyQbXamIgWAwvnAs/oDRVqEejE2nwDhnpykaCGLkuDEN0LPd2wF+vC2Cq3
-----END PUBLIC KEY-----
EOT
key = “-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5P0Z4OUD5PSjri8xexGo\n6eQ39NGyQbXamIgWAwvnAs/oDRVqEejE2nwDhnpykaCGLkuDEN0LPd2wF+vC2Cq3\n-----END PUBLIC KEY-----\n”

The only different is in their presentation, one using heredoc syntax and one being an escaped, double quoted string. If you were to put both of those literal values in your configuration they would output the same thing, and comparing them via == would return true.

Your replace did exactly what you asked, it replaced the actual newline character with an escaped backslash and the letter n, which I don’t think is what you really want.

1 Like

I see. Thanks for the explanation jbardin. So the problem with my script is somewhere else. I’ll keep looking. Thanks again!