Score:1

Environment Variable Empty in Bash Script

pl flag

I have an EC2 instance that I am deploying on AWS.

I am using an Amazon Linux 2, and I am passing a user data to it as such:

userdata_file.write(
        f'''
        #!/bin/bash\n
        export PAGERDUTYAPIKEY='mykey'\n
        sudo yum install git -y\n
        chmod +x ./basic_test.sh \n
        echo $PAGERDUTYAPIKEY> /home/ec2-user/pagerdutyapikey1.txt\n
        sudo ./basic_test.sh
        '''.strip()
    )

basic_test.sh

#!/bin/bash

echo "s/enterpagerdutyapikey/${PAGERDUTYAPIKEY}/g" > path.txt

However, when i run it, in the path.txt it is echoing as such:

s/enterpagerdutyapikey//g

But when i ssh in the server and run the same bash script, it echos as such:

s/enterpagerdutyapikey/mykey/g

Any idea why the environment variable $PAGERDUTYAPIKEY is rendering empty when i run through the userdata ?

in flag
Crossposted to [StackOverflow](https://stackoverflow.com/q/70423727/1030675).
jp flag
As mentioned in comments on SO, `sudo` resets most of environment variables. Drop `sudo` from the user-data script, it runs as `root` anyway.
Mervin Hemaraju avatar
pl flag
Dropping sudo worked! Thanks
cn flag
@MervinHemaraju - if you post the answer as an answer here, you can mark this question as answered and save people the click through to SO!
Score:1
pl flag

Posting from the StackOverflow post https://stackoverflow.com/questions/70423727/environment-variable-empty-in-bash-script

As answered by @chepner sudo does not preserve arbitrary environment variables by default for security reasons. So dropping sudo from the command helped me.

in flag
Please don't cross post your questions. Either delete your question here or on SO. IMO SO is a better fit for the question.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.