/bash/

Rotation of AWS IAM user access keys

2020-05-03 16:50:00

#!/usr/bin/env bash

valida_profile() {
    [[ $(aws configure get aws_access_key_id --profile ${1}) ]] && {
        return 0
    } || {
        return 1
    }
}

valida_number_of_keys() {
    [[ $(aws iam list-access-keys --profile ${1} --user-name ${2} | python -c 'import json,sys;print len(json.load(sys.stdin)["AccessKeyMetadata"])') -eq 1 ]] && {
        return 0
    } || {
        return 1
    }
}

get-user-name() {
    echo $(aws iam get-user --profile ${1} | python -c 'import json,sys;print json.load(sys.stdin)["User"]["UserName"]')
}

get-access-key(){
    echo $(aws iam list-access-keys --profile ${1} --user-name ${2} | python -c 'import json,sys;print json.load(sys.stdin)["AccessKeyMetadata"][0]["AccessKeyId"]')
}

create-access-key(){
    echo $(aws iam create-access-key --profile ${1} --user-name ${2})
}

get-access-key-id(){
    echo ${1} | python -c 'import json,sys;print json.load(sys.stdin)["AccessKey"]["AccessKeyId"]'
}

get-access-key-secret(){
    echo ${1} | python -c 'import json,sys;print json.load(sys.stdin)["AccessKey"]["SecretAccessKey"]'
}

delete-access-key(){
    echo "# Cleaning"
    sleep 6
    aws iam delete-access-key --profile ${1} --user-name ${2} --access-key-id ${3}
}

configure-profile(){
    echo "# Configuring ${1} profile with new key ${2}"
    aws configure set aws_access_key_id --profile ${1} ${2}
    aws configure set aws_secret_access_key --profile ${1} ${3}
}

rotate_aws_keys ()  {
    PROFILE=$1

    [[ ${1} ]] && {
        echo "# Init Reconfiguration for ${PROFILE} profile";
        $(valida_profile ${PROFILE}) && {
            echo "# Profile ${PROFILE} exist"
            USER_NAME=$(get-user-name ${PROFILE})

            $(valida_number_of_keys ${PROFILE} ${USER_NAME}) && {
                OLD_KEY_ID=$(get-access-key ${PROFILE} ${USER_NAME})

                RESPONSE=$(create-access-key ${PROFILE} ${USER_NAME})
                KEY_ID=$(get-access-key-id "${RESPONSE}")
                KEY_ACCESS=$(get-access-key-secret "${RESPONSE}")

                configure-profile ${PROFILE} ${KEY_ID} ${KEY_ACCESS}

                delete-access-key ${PROFILE} ${USER_NAME} ${OLD_KEY_ID}
            } || {
                echo "That user has 2 kay's. Not possible to generate new one"
            }
        } || {
            echo "Profile ${PROFILE} does not exist"
        }
        echo "# End"
    } || {
        echo "Profile parameter is required"
    }
}

rotate_aws_keys $1