Search code examples
jsonamazon-web-servicesamazon-ec2terraformuser-data

Handling JSON string in EC2 userdata


I am trying to provision an EC2 instance using terraform, passing a cloudinit configuration file as userdata to the instance.

As part of the cloudinit config I am setting environment variables and some of the variables are JSON strings.

The user data that is generated by terraform and passed to the instance looks correct, surrounded by single quotes, but when the environment variables are written to the file on the server the quotes are stripped which is causing issues

Here is an example snippet of the user data passed to the EC2 instance

#cloud-config

environment:
  var: '{"key": "value"}'

Then on the server the environment file (/etc/environment) looks like this

var={"key": "value"}

But I need to to still be surrounded by single quotes when in /etc/environment

var='{"key": "value"}'

Any ideas on how I do this? I tried escaping the quotes using \' but that is not valid YAML and so the user data fails with an error, any thoughts on this would be appreciated.


Solution

  • It seems you may want a block for your YAML value. You can do this using >.

    #cloud-config
    
    environment: 
      var: >
        '{"key": "value"}'