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

How to set environment variable for ec2 user_data with terraform templatefile


I'd like to run myscript.sh with terraform templatefile. I set the variable password as environment variable in EC2. But, the script doesn't work well as I start the instance.

Here is files I wrote. Is is correct way to pass the environment variable under user_data?

  • myscript.sh
#! /bin/bash
echo $password
# Continue to some procedures
  • My terraform template
resource "aws_instance" "web" {
  ami           = data.aws_ssm_parameter.amzn2_ami.value
  instance_type = "t2.micro"
  key_name      = aws_key_pair.key_pair.key_name
  user_data     = templatefile("./scripts/myscript.sh", {
    password = "********"
  })
}

Solution

  • Your myscript.sh is missing #!/bin/bash and to refer to passed variables yo should use ${password}. So it should be:

    #!/bin/bash
    echo ${password} > /tmp/test.txt
    

    Also its better to test it by saving the echo into, for example, /tmp/test.txt. Otherwise you want see any output. But with the /tmp/test.txt you can login to the instance and check if /tmp/test.txt exists.

    Also the script does not set any env variables.