Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux script persist environment variable

Tags:

bash

shell

I am trying to persist keys fetched form key vault as environment variable for a given user on linux server. The script does not work. I am not even able to see the if the variable was set temporarily in the shell.

This is my script.

#!/usr/bin/env bash
  KEY_VAULT=$1

function fetch_secret_from_keyvault() {
    local SECRET_NAME=$1

    az keyvault secret show --vault-name "${KEY_VAULT}" --name "${SECRET_NAME}" --query "value"
}

function store_secret_from_keyvault() {
    local SECRET_VAR=$1
    local SECRET_NAME=$2

    local SECRET_VALUE=`fetch_secret_from_keyvault "${SECRET_NAME}"`
    store_secret "${SECRET_VAR}" "${SECRET_VALUE}"
}

function store_secret() {
    local SECRET_VAR=$1
    local SECRET_VALUE=$2

    echo "export ${SECRET_VAR}=${SECRET_VALUE}"
}

echo "# ----------------------- "
echo "# Fetched the following secret from ${KEY_VAULT} on "`date`

store_secret_from_keyvault "MONGO_URI" "local-dev-mongo-uri"

I have read that export only temporarily stores the variable.

The script runs, but the variables are not set at the end. I would like to see them when executing

printenv
like image 882
Nesan Mano Avatar asked Jun 07 '26 09:06

Nesan Mano


2 Answers

If you run a script to set variables, the variables will only be set in the context of that particular execution. To set variables, you have to source the file, not execute it.

Ex. setenv.bash

#!/bin/bash
export var1=value1
export var2=value2

If you do ./setenv.bash, var1 and var2 will only exist while the script is running.

If you do . ./setenv.bash or source ./setenv.bash, var1 and var2 will exist after the script is done.

like image 116
Nic3500 Avatar answered Jun 09 '26 06:06

Nic3500


Assumptions:

  • OP wants to dynamically populate and export a new variable such that ...
  • the new variable is available/exported in the current session

One idea using a nameref ...

function store_secret() {
    declare -n SECRET_VAR=${1}
    export SECRET_VAR=${2}
}

Running a test:

$ unset secret_var
$ secret_var=56
$ typeset -p secret_var
declare -- secret_var="56"                  # defined as a normal variable

$ unset secret_var
$ typeset -p secret_var
-bash: typeset: secret_var: not found       # variable is undefined

$ store_secret secret_var 47
$ typeset -p secret_var
declare -x secret_var="47"                  # defined as an exported variable
like image 39
markp-fuso Avatar answered Jun 09 '26 07:06

markp-fuso