Search code examples
typescriptamazon-web-servicesterraformdevopscdktf

Inject CDKTF multiline token value


Context:

  • TLS provider: SelfSignedCert
  • AWS provider: ECS Fargate task
    const cert = new SelfSignedCert(this.stack, `${certName}-sscert`, {
      keyAlgorithm: 'RSA',
      privateKeyPem: privateKey.privateKeyPem,
      subject: [{
        commonName,
        organization
      }],
      validityPeriodHours,
      allowedUses
    });

    const containerDefinitionConfig = {
      path: {
        path: ecsJsonTaskDefPath,
      },
      args: {
        ...
        'certPem': cert.certPem,
        ...
      }
    };

If I try to run it like that, I get the following error:

Error: ECS Task Definition container_definitions is invalid: Error decoding JSON: invalid character '\n' in string literal

I tried using:

  • cert.certPem.replace(/\n/g', '\\n') directly on the value -- pointless because it's a token and the replace function only applies to the token ref, not the value itself. So I get the same error from above.
  • Fn.replace(cert.certPem, '/\n/', '\\n') but it's complaining with Error: '\n' can not be used as value directly since it has unescaped double quotes in it. To safely use the value please use Fn.rawString on your string.
  • Fn.rawString(cert.certPem) doesn't fail but sets the env var as "${tls_self_signed_cert.seb-alice-sscert.cert_pem}"

Versions:

"cdktf": "^0.9.0",

  "terraformProviders": [
    "aws@~> 3.74.0",
    "random@~> 3.1.0",
    "tls@~> 3.1.0"
  ],

Solution

  • I believe it's complains about the first \n in the replace function: Fn.replace(cert.certPem, Fn.rawString('/\n/'), Fn.rawString('\\n'))