2

I'm writing a bash script that takes a user name from user input, and displays their AWS access keys and creation dates.

I use jq to parse the output of the command.

The output looks like this:

Enter a user name: 
ralph
User ralph keys:
AKIAJS7KPHZCQRQ5FJWA
2016-08-31T15:38:18Z
AKIAICDOHVTMEAB6RM5Q
2018-02-08T03:55:51Z

How can I split that output so that the access key is listed next to the date?

I want the output to look like this:

AKIAJS7KPHZCQRQ5FJWA : 2016-08-31T15:38:18Z
AKIAICDOHVTMEAB6RM5Q : 2018-02-08T03:55:51Z

This is my code so far:

echo "Enter a user name: "
   read -r user_name

   keys=( $(aws iam list-access-keys --profile=prod  | jq -r '.AccessKeyMetadata[] | (.AccessKeyId, .CreateDate)') )

   echo "User $user_name keys:"
   for key in "${keys[@]}"
     do
       echo "$key"
   done

2 Answers 2

2

(note that I changed the aws iam command just a bit.)

$ aws iam list-access-keys  | jq -r '.AccessKeyMetadata[] | (.AccessKeyId, .CreateDate)' | awk 'NR%2{k=$0;next}{print k " : " $0}'
AKIAIXXXXXXXXX : 2014-10-07T14:56:12Z
AKIAIYYYYYYYYY : 2015-01-10T12:18:01Z

In other words, get rid of the loop:

echo "Enter a user name: "
read -r user_name
echo "User $user_name keys:"

aws iam list-access-keys --profile=kpmg-prod  \ 
| jq -r '.AccessKeyMetadata[] | (.AccessKeyId, .CreateDate)') \
| awk 'NR%2{k=$0;next}{print k " : " $0}'

If you are doing something else in that loop:

n=0
for i in $(aws iam list-access-keys  | jq -r '.AccessKeyMetadata[] | (.AccessKeyId, .CreateDate)')
do
  if [ $n -eq 0 ]; then
    id="$i"
    let n=1+$n
  else
    n=0
    date="$i"
    echo "$id : $date"
  fi
done
Sign up to request clarification or add additional context in comments.

1 Comment

Shell arrays always confuse me so I try to avoid.
1

You can try to use tr '\n' ':' that I guess will replace newline caracter by ':' within keys variable

1 Comment

Thanks, that got me part of the way there. That replaces the newline with the :, but the output is all on one line.

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.