title: Verify AWS Credentials with boto3
body: <p>I'm trying to write Python code that uses a number of different AWS keys, some of which may have expired. I need, given an AWS key pair as strings, to check whether the given key pair is valid using boto3. I would prefer not to have to do anything like using os.system to run </p>
  
  <pre><code>echo "$aws_key_id
  $aws_secret_key\n\n" | aws configure
  </code></pre>
  
  <p>and then reading the response of <code>aws list-buckets.</code></p>
  
  <p>The answer should look something like </p>
  
  <pre><code>def check_aws_validity(key_id, secret):
      pass
  </code></pre>
  
  <p>where <code>key_id</code> and <code>secret</code> are strings.</p>
  
  <p>Note that this is not a repeat of <a href="https://stackoverflow.com/questions/47056628/verifying-s3-credentials-w-o-get-or-put-using-boto3">Verifying S3 credentials w/o GET or PUT using boto3</a>, as I do not have the keys in boto3.profile.</p>
  
  <p>Thanks in advance!</p>
  
  <p><strong>EDIT</strong>
  From John Rotenstein's answer, I got the following function to work.</p>
  
  <pre><code>def check_aws_validity(key_id, secret):
      try:
          client = boto3.client('s3', aws_access_key_id=key_id, aws_secret_access_key=secret)
          response = client.list_buckets()
          return true
  
      except Exception as e:
          if str(e)!="An error occurred (InvalidAccessKeyId) when calling the ListBuckets operation: The AWS Access Key Id you provided does not exist in our records.":
              return true
          return false
  </code></pre>