Env variables not persisting in parent shell

I have the following bash script that attempts to automate the assuming of an AWS role (I’ve obviously removed the various private settings):

#! /bin/bash
#
# Dependencies:
#   brew install jq
#
# Execute:
#   source aws-cli-assumerole.sh

unset AWS_SESSION_TOKEN
export AWS_ACCESS_KEY_ID=<user_access_key>
export AWS_SECRET_ACCESS_KEY=<user_secret_key>

temp_role=$(aws sts assume-role 
                    --role-arn "arn:aws:iam::<aws_account_number>:role/<role_name>" 
                    --role-session-name "<some_session_name>")

export AWS_ACCESS_KEY_ID=$(echo $temp_role | jq .Credentials.AccessKeyId)
export AWS_SECRET_ACCESS_KEY=$(echo $temp_role | jq .Credentials.SecretAccessKey)
export AWS_SESSION_TOKEN=$(echo $temp_role | jq .Credentials.SessionToken)

env | grep -i AWS_

I have to execute this script using source because otherwise if I use standard bash or sh the exported environment variables are not available within the parent shell executing this script.

The problem is, even when using source it doesn’t work; and by that I mean: the environment variables AND their correct/updated values are showing in the parent shell (if I execute env | grep AWS_ I can see the correct values).

If I then try to use the AWS CLI tools (e.g. aws s3 ls – to list all s3 buckets within the specific account I’ve assumed the role for) it’ll report back that the access key is invalid.

BUT, if I manually copy and paste the environment variable values and re-export them in the parent shell (effectively overwriting them with the exact same values that are already set), then the AWS CLI command will work – but I do not know why. What’s different?


Source: shell

Leave a Reply