Search code examples
amazon-web-servicesaws-cliaws-config

How to Check if AWS Named Configure profile exists


How do I check if a named profile exists before I attempt to use it ?

aws cli will throw an ugly error if I attempt to use a non-existent profile, so I'd like to do something like this :

  $(awsConfigurationExists "${profile_name}") && aws iam list-users --profile "${profile_name}" || echo "can't do it!"

Solution

  • Method 1 - Check entries in the .aws/config file

    function awsConfigurationExists() {
    
        local profile_name="${1}"
        local profile_name_check=$(cat $HOME/.aws/config | grep "\[profile ${profile_name}]")
    
        if [ -z "${profile_name_check}" ]; then
            return 1
        else
            return 0
        fi
    
    }
    

    Method 2 - Check results of aws configure list , see aws-cli issue #819

    function awsConfigurationExists() {
    
    
        local profile_name="${1}"
        local profile_status=$( (aws configure --profile ${1} list) 2>&1)
    
        if [[ $profile_status = *'could not be found'* ]]; then
            return 1
        else
            return 0
        fi
    
    }
    

    usage


    $(awsConfigurationExists "my-aws-profile") && echo "does exist" || echo "does not exist"
    

    or

    if $(awsConfigurationExists "my-aws-profile"); then
        echo "does exist"
      else
        echo "does not exist"
      fi