52

When working with certain third-party tools like Terraform, it's not easily possible to specify an AWS CLI profile, and I like working with the environment variables better than the profiles.

Is there a way for me to have the AWS CLI simply export the current profile as AWS_ACCESS_KEY_ID and AWS_SECRET_KEY environment variables to my session?

Naftuli Kay
  • 87,710
  • 93
  • 269
  • 411

8 Answers8

61

you could use the following command to set your environment variable

aws configure get default.aws_access_key_id
aws configure get default.aws_secret_access_key

if you have another profile you can change, another way to write is

aws configure get aws_access_key_id --profile <new_profile>
aws configure get aws_secret_access_key --profile <new_profile>

so for example it would be

export TF_VAR_access_key=`aws configure get default.aws_access_key_id`
Frederic Henri
  • 51,761
  • 10
  • 113
  • 139
  • 2
    Was looking for the same. Bash/zsh script to do the same https://gist.github.com/mjul/f93ee7d144c5090e6e3c463f5f312587 Disclosure: not the author, just found it useful – Thomas Gratier Apr 02 '21 at 14:50
21

In Terraform

Terraform actually directly supports AWS CLI profiles: just set an appropriate profile attribute in the aws provider block.

Something like this should do the trick:

provider "aws" {
  profile = "my_profile"
}

Environment variables

If you are instead in a situation in which you have to use environment variables Frederic's suggestion can be used this way:

export AWS_ACCESS_KEY_ID=$(aws configure get my_profile.aws_access_key_id)
export AWS_SECRET_ACCESS_KEY=$(aws configure get my_profile.aws_secret_access_key)

If you want to pass environment vars to a script use:

AWS_ACCESS_KEY_ID=$(aws configure get my_profile.aws_access_key_id) \
AWS_SECRET_ACCESS_KEY=$(aws configure get my_profile.aws_secret_access_key) \
./script.sh

Environment variables with "assume role"

If you use profiles to assume a role specified in config field role_arn, then things get a little trickier as the credentials are generated on the fly (and expire after a while).

But it's still feasible:

read AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN <<< \
   $(aws sts assume-role                                           \
     --role-arn $(aws configure get my_profile.role_arn)           \
     --role-session-name my_profile_session --output text |        \
     awk '/^CREDENTIALS/ { print $2, $4, $5 }')
slm
  • 15,396
  • 12
  • 109
  • 124
Enrico Marchesin
  • 4,650
  • 2
  • 20
  • 15
12

There was no way previously, but there is now.

I wrote a script to do exactly this, aws-env:

usage: aws-env [-h] [-n] profile

Extract AWS credentials for a given profile as environment variables.

positional arguments:
  profile          The profile in ~/.aws/credentials to extract credentials
                   for.

optional arguments:
  -h, --help       show this help message and exit
  -n, --no-export  Do not use export on the variables.

If you trust the output of this program, you can use it within your shell session to export the variables of a given profile:

$ aws-env profile-name
export AWS_ACCESS_KEY_ID=...
export AWS_SECRET_ACCESS_KEY=...
$ aws-env -n profile-name
AWS_ACCESS_KEY_ID=...
AWS_SECRET_ACCESS_KEY=...

To export the variables into the current environment variables, execute the output as a command (again, once you have reviewed the source code ;]):

$ echo $AWS_ACCESS_KEY_ID

$ $(aws-env profile-name)
$ echo $AWS_ACCESS_KEY_ID
AKJHC...
Naftuli Kay
  • 87,710
  • 93
  • 269
  • 411
  • 3
    This is great & all, but seeing as you answered after the official API answer was posted by @Frederic, it should be mentioned that the CLI is the suggested & supported method. – wilco Apr 17 '17 at 19:49
12

This is now built-in functionality of the AWS CLI .

Simply call eval "$(aws configure export-credentials --profile your-profile-name --format env)" and you should be good to go.

Chrest
  • 776
  • 1
  • 9
  • 11
  • 1
    For other uses, there is also the `env-no-export` format. For instance, you can easily pass your credentials as environment variables to a docker container this way: `docker run --env-file <(aws configure export-credentials --profile your-profile-name --format env-no-export) ...` – Alex Grounds Mar 31 '23 at 13:50
11

For sts assume role case, based on Frederic's idea, I figured out a workable shell script as followings:

aws-env.sh:

#!/bin/bash
export AWS_ACCESS_KEY_ID=$(aws configure get default.aws_access_key_id)
export AWS_SECRET_ACCESS_KEY=$(aws configure get default.aws_secret_access_key)
export AWS_SESSION_TOKEN=$(aws configure get default.aws_session_token)

echo AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID
echo AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY
echo AWS_SESSION_TOKEN=$AWS_SESSION_TOKEN

bash -i

Hope this helps.

Tony Liang
  • 111
  • 1
  • 2
4

I like Kay's ideas of a script that exports the desired profile so I wrote one too:

PROFILES=$(awk -F"\\\]|\\\[" '/^\[/{print $2}' ~/.aws/credentials)

select PROFILE in $PROFILES; do
  export AWS_ACCESS_KEY_ID="$(aws configure get aws_access_key_id --profile $PROFILE)"
  export AWS_SECRET_ACCESS_KEY="$(aws configure get aws_secret_access_key --profile $PROFILE)"
  export AWS_DEFAULT_REGION="$(aws configure get region --profile $PROFILE)"
  break
done

echo AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID
echo AWS_SECRET_ACCESS_KEY=$(echo $AWS_SECRET_ACCESS_KEY|tr '[:print:]' '*')
echo AWS_DEFAULT_REGION=$AWS_DEFAULT_REGION

Just put it in a file and then source (.) it from your shell. Here links an updated version which grabs AWS _ TOKENS as well.

AXE Labs
  • 4,051
  • 4
  • 29
  • 29
1

None of these allow for role assumption in profiles (which I use heavily). I made the following very short script in python3 that uses boto3 to do the heavy lifting of role assumption and the like. It may be helpful.

#!/usr/bin/env python3

# export the AWS environment for a given profile

import boto3
import argparse

parser = argparse.ArgumentParser(prog="exportaws",
    description="Extract AWS credentials for a profile as env variables.")
parser.add_argument("profile", help="profile name in ~/.aws/config.")
args = parser.parse_args()
creds = boto3.session.Session(profile_name=args.profile).get_credentials()
print(f'export AWS_ACCESS_KEY={creds.access_key}')
print(f'export AWS_SECRET_ACCESS_KEY={creds.secret_key}')
print(f'export AWS_SESSION_TOKEN={creds.token}')
Tom Bortels
  • 88
  • 1
  • 6
1

For Zsh:

function aws-env {
    emulate -LR zsh
    profile=${1:-default}
    if [[ ${profile} == clear ]]; then
        unset AWS_ACCESS_KEY_ID
        unset AWS_SECRET_ACCESS_KEY
        unset AWS_SESSION_TOKEN
        unset AWS_SECRET_KEY
    else
        AWS_ACCESS_KEY_ID="$(aws configure get aws_access_key_id --profile ${profile})" || return 1
        AWS_SECRET_ACCESS_KEY="$(aws configure get aws_secret_access_key --profile ${profile})" || return 1
        AWS_SESSION_TOKEN="$(aws configure get aws_session_token --profile ${profile})" || return 1
        AWS_SECRET_KEY=${AWS_SECRET_ACCESS_KEY}
        export AWS_ACCESS_KEY_ID
        export AWS_SECRET_ACCESS_KEY
        export AWS_SESSION_TOKEN
        export AWS_SECRET_KEY
        env | grep AWS_ | sort
    fi
}