How to AWS Assume Role and then revert to the previous role after
If you need to assume a role in AWS and then revert back to the previous role once complete, you can use the following snippet of code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 # Save original environment variables ORIGINAL_AWS_ACCESS_KEY_ID="$AWS_ACCESS_KEY_ID" ORIGINAL_AWS_SECRET_ACCESS_KEY="$AWS_SECRET_ACCESS_KEY" ORIGINAL_AWS_SESSION_TOKEN="$AWS_SESSION_TOKEN" # Assume the role and store the output in a variable assume_role_output=$(aws sts assume-role --role-arn arn:aws:iam::12345678912:role/YourCrossAccountAccessRole --role-session-name "AssumeRoleSession") # Extract temporary credentials from the assume role output using jq (JSON processor) export AWS_ACCESS_KEY_ID=$(echo "$assume_role_output" | jq -r '.