Ricordanza
2/27/2020 - 8:53 AM

Shell that automatically generates AWS CLI config from aws-vault

Shell that automatically generates AWS CLI config from aws-vault

#!/bin/sh

# Variables
readonly TARGET_HOME=$HOME/.aws
readonly TARGET_FILE=$TARGET_HOME/config
readonly REGION=ap-northeast-1
readonly OUTPUT=json

# Initialize .aws/config
if [ ! -e "$TARGET_HOME" ]; then
  echo Create a config form folder.
  mkdir -p "$TARGET_HOME"
fi

# Back up .aws/config
if [ -e "$TARGET_FILE" ]; then
  echo Back up config.
  cp -p "$TARGET_FILE" "$TARGET_FILE".`date "+%Y%m%d%H%M%S"`
fi

# Create default profile
echo Register default settings.
cat <<EOF > "$TARGET_FILE"
[default]
credential_process=/usr/local/bin/credential-selector.sh
region=$REGION
output=$OUTPUT
EOF

# Added settings for each credential
for credential in ` aws-vault ls | awk 'NR>2 {if ($2 != "-") print $2}'`
do
  echo Register profile [$credential].
  cat <<EOF >> "$TARGET_FILE"

[profile $credential]
credential_process=aws-vault exec -j $credential --no-session
region=$REGION
output=$OUTPUT
EOF

done