Environment Variable Empty in Bash Script

amazon-linux-2amazon-web-servicesbashlinux

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 ?

Best Answer

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.