1

I wrote a script to: 1) generate random password 2) create new IAM user 3) set up login profile for that user using the generated password. Below is my code in bash:

RANDOM_PASS=$(aws secretsmanager get-random-password --include-space --password-length 20 --require-each-included-type | jq '.RandomPassword' | tr -d '"')

aws iam create-user --user-name $USERID
aws iam create-login-profile --user-name $USERID --password $RANDOM_PASS --password-reset-required

as you can see, I used jq to get that specific password string and then truncated the " so I can put it in the create-login-profile. But it doesn't look very elegant and I feel there must be a better way to do this. Any suggestions?

2 Answers 2

3

You don't need JQ there at all in fact.

Instead of:

aws secretsmanager get-random-password --include-space --password-length 20 \
  --require-each-included-type | jq '.RandomPassword' | tr -d '"'

You just need:

aws secretsmanager get-random-password --include-space --password-length 20 \
  --require-each-included-type --output text

AWS CLI commands allow you to switch between JSON and text (and table) output by passing the --output switch.

As for general readability of your script, I also try to avoid long lines, so I would refactor as something like:

RANDOM_PASS=$(aws secretsmanager get-random-password \
  --require-each-included-type \
  --password-length 20 \
  --include-space \
  --output text)

aws iam create-user --user-name $USERID

aws iam create-login-profile \ 
  --user-name $USERID \
  --password $RANDOM_PASS \
  --password-reset-required

It's just a personal preference obviously.

2

Rewite this part:

jq '.RandomPassword' | tr -d '"')

To:

jq -r '.RandomPassword'

The -r means output raw without the quotes.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.