Tuesday, March 15, 2022

[SOLVED] Pass my local environment variables values to my ec2 user data

Issue

As simple as it sounds, I would like to pass my local environment variable value inside my ec2 user data script. So for instance I run this locally:

export PASSWORD=mypassword
printenv PASSWORD
mypassword

then once I ssh to my ec2 and run

printenv PASSWORD

I should see the same value mypassword. I haven't found a way to inject the right codes in my user data script. Please help if you can.

This is my user data, I am basically installing some packages then authenticate to my vault with the password value I would like to upload from my laptop to my ec2. I just don't want to hardcode mypassword in my user dat script. (not even sure if it's doable?)

 # User Data for ASG
  user_data = <<EOF
#!/usr/bin/env bash 

set -x -v

exec > >(tee -i user-data.log 2>/dev/console) 2>&1

# Install latest AWS cli
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install --update


# Install VAULT cli
sudo wget https://releases.hashicorp.com/vault/1.8.2/vault_1.8.2_linux_amd64.zip
sudo unzip vault_1.8.2_linux_amd64.zip 
sudo mv vault /usr/local/bin/vault
sudo chmod +x /usr/local/bin/vault
vault -v

# Vault env var
export VAULT_ADDR=https://myvault.test
export VAULT_SKIP_VERIFY=true
export VAULT_NAMESPACE=test

# Vault login (to authenticate to vault must export local value of $PASSWORD
export VAULT_PASSWORD=$PASSWORD
vault login -namespace=test -method=userpass username=myuser password=$VAULT_PASSWORD

Solution

I was able to make it work by setting up locally all variables for my sensitive data and defined them my variables.tf. Then on my user data field I just exported the TF var name. See below:

Local setup

export TF_VAR_password=password

TF code --> variables.tf

variable "password" {
  description = "my password"
  type        = string
  default     = ""
}

Now in my app user data script

export MYPASSWORD=${var.password}

VOILA :)

Here is the website as a point of reference --> https://learn.hashicorp.com/tutorials/terraform/sensitive-variables?in=terraform/0-14 ( look for Set values with environment variables)



Answered By - Karl Diji
Answer Checked By - Mildred Charles (WPSolving Admin)