0

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!"
AndrewD
  • 4,924
  • 3
  • 30
  • 32

2 Answers2

1

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
AndrewD
  • 4,924
  • 3
  • 30
  • 32
0

I was stuck with the same problem and the proposed answer did not work for me.

Here is my solution with aws-cli/2.8.5 Python/3.9.11 Darwin/21.6.0 exe/x86_64 prompt/off:

export AWS_PROFILE=localstack
aws configure list-profiles | grep -q "${AWS_PROFILE}"
if [ $? -eq 0 ]; then
  echo "AWS Profile [$AWS_PROFILE] already exists"
else
  echo "Creating AWS Profile [$AWS_PROFILE]"
  aws configure --profile $AWS_PROFILE set aws_access_key_id test
  aws configure --profile $AWS_PROFILE set aws_secret_access_key test
fi
Manuel Spigolon
  • 11,003
  • 5
  • 50
  • 73