1

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 ?

4
  • Crossposted to StackOverflow.
    – choroba
    Commented Dec 20, 2021 at 15:11
  • 1
    As mentioned in comments on SO, sudo resets most of environment variables. Drop sudo from the user-data script, it runs as root anyway.
    – AlexD
    Commented Dec 20, 2021 at 15:20
  • Dropping sudo worked! Thanks Commented Dec 20, 2021 at 15:23
  • 1
    @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!
    – shearn89
    Commented Jan 6, 2022 at 16:34

1 Answer 1

1

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.

1
  • Please don't cross post your questions. Either delete your question here or on SO. IMO SO is a better fit for the question. Commented Jan 9, 2022 at 11:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .