Skip to content
Advertisement

Iterate Variables of array into command which itself is a variable bash

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}

Advertisement

Answer

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

?

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement