1

I am almost there, the "$i" is where I am having trouble. I have tried ${i}, "$i", $i. I am sure someone with more experience can help me here I have been working on this for 1 full day. Driving me nuts.

session_name="Some-sesh_name"
profile_name="ephemeral-${account_id}-${profile_path}-`date +%Y%m%d%H%M%S`"
roles=( "arn:aws:iam::11111111111111:role/role_name" "arn:aws:iam::222222222222:role/role_name" )

sts=( $(
    aws sts assume-role \
    --role-arn "$i" \
    --role-session-name "$session_name" \
    --query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]' \
    --output text
) )

for i in "${roles[@]}";
do $sts ; done

aws configure set aws_access_key_id ${sts[0]} --profile ${profile_name}
aws configure set aws_secret_access_key ${sts[1]} --profile ${profile_name}
aws configure set aws_session_token ${sts[2]} --profile ${profile_name}
2
  • But $i is not defined before usage in --role-arn "$i" \ Commented Jul 18, 2017 at 13:03
  • Haven't tested your script - but at first glance I think you need to escape the $i in the sts definition: "\$i". Otherwise $i is evaluated when sts is defined. If you want it evaluated inside the loop it needs to be escaped. Commented Jul 18, 2017 at 13:04

1 Answer 1

5

That $i is expanded at the moment you define the sts array. After that, it doesn't exist.

To make that aws command reusable, use a function:

roles=( 
    "arn:aws:iam::11111111111111:role/role_name" 
    "arn:aws:iam::222222222222:role/role_name" 
)

sts() {
    aws sts assume-role \
    --role-arn "$1" \
    --role-session-name "$session_name" \
    --query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]' \
    --output text
}

for role in "${roles[@]}"; do
    sts "$role"
done

Note the use of $1 in the function, to retrieve the first argument. The global variable $session_name is still OK


I don't understand what you're thinking with the sts array. In the for loop you want to call it as a command, but the configure commands take elements of the array? After all the roles have been assumed? Are you wanting to use the returned data instead?

Do you want:

for role in "${roles[@]}"; do
    data=( $(sts "$role") )
    aws configure set aws_access_key_id     "${data[0]}" --profile "$profile_name"
    aws configure set aws_secret_access_key "${data[1]}" --profile "$profile_name"
    aws configure set aws_session_token     "${data[2]}" --profile "$profile_name"
done

?

Sign up to request clarification or add additional context in comments.

1 Comment

The answer was precisely the need. I am not a trained developer, but I make do with what I need. You guys certainly helped! Sts shouldn't have been an array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.