TIL

Calling aws-vault from Python

You probably don't want to do this. A much better solution is to run aws-vault exec <profile> -- python .... But if you had some strange use case for it, here's how you'd do it:

import os
import subprocess

def fetch_creds_from_aws_vault(profile, mfa_token=None):
    """Shell out to aws-vault and update AWS credentials in environment"""
    cmd = ["aws-vault", "exec", profile]
    if mfa_token:
        cmd.extend(["--mfa-token", mfa_token])
    cmd.extend(["--", "env"])
    envvars = subprocess.check_output(cmd).decode()
    for envline in envvars.splitlines():
        if not envline.startswith("AWS_"):
            continue
        k, v = envline.split("=", 1)
        os.environ[k] = v

Hat tip to rossigee.