Jinja templating not working in cloud config

I am trying to read instance metadata using Jinja in a cloud-init config as per the docs here: Instance metadata - cloud-init 23.4 documentation, but the interpolation is not happening. Any insight into why?


data "cloudinit_config" "i" {
  part {
    content_type = "text/cloud-config"
    content      = templatefile("${path.module}/templates/cloudconfig.tftpl", var.cloud_config_vars)

resource "aws_instance" "i" {
  ami                         = var.ami
  instance_type               = var.instance_type
  subnet_id = var.subnet
  user_data                   = data.cloudinit_config.i.rendered


## template: jinja

  - https://s3.us-west-2.amazonaws.com/amazon-ssm-us-west-2/latest/linux_{{- 'arm64' if v1.machine == 'aarch64' else 'amd64' -}}/amazon-ssm-agent.rpm

My Jinja syntax seems to be fine. I tested it as follows.
I created test-templating.yaml as follows:

  - https://s3.us-west-2.amazonaws.com/amazon-ssm-us-west-2/latest/linux_{{- 'arm64' if v1.machine == 'aarch64' else 'amd64' -}}/amazon-ssm-agent.rpm

Then run:

cloud-init query --format="$(cat test-templating.yaml )"

It produced the output I was looking for:

  - https://s3.us-west-2.amazonaws.com/amazon-ssm-us-west-2/latest/linux_amd64/amazon-ssm-agent.rpm

Terraform details

Terraform v1.5.5
on linux_arm64
+ provider registry.terraform.io/hashicorp/aws v5.13.1
+ provider registry.terraform.io/hashicorp/cloudinit v2.3.2

Target system details

Platform: Red Hat Enterprise Linux release 9.2 (Plow)
Architecture:  aarch64
Hyperscaler: AWS
Cloud-init version: 22.1-10.el9_2

When trying to use jinja to use variables from IMDSv2 I also encountered this problem.

I think there is a mime type/multipart problem. In my case, having a simple template, I worked around using the templatefile function.


user_data = base64encode(templatefile("userdata.tftpl", {
  aws_network_interface_id = aws_network_interface.this.id


## template: jinja
package_update: true
package_upgrade: true

- aws ec2 attach-network-interface --instance-id {{v1.instance_id}} --network-interface-id ${aws_network_interface_id} --device-index 1 --region {{v1.region}}