# aws-export-credentials
**Get AWS credentials from a profile to inject into other programs**
> :warning: The AWS CLI now includes a command [`aws configure export-credentials`](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configure/export-credentials.html) that covers the `--json`, `--env`, and `--env-export` options of `aws-export-credentials`, as well as providing env options for Windows.
>
> If you want to inject refreshable credentials into a locally-run container, [`imds-credential-server`](https://github.com/benkehoe/imds-credential-server) is a more focused solution for that.
There are a number of other projects that extract AWS credentials and/or inject them into programs, but all the ones I've seen use the CLI's cache files directly, rather than leveraging boto3's ability to retrieve and refresh credentials.
So I wrote this to do that.
[boto3 (the AWS Python SDK)](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) has added support for loading credentials cached by [`aws sso login`](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sso/login.html) as of [botocore version 1.17.0](https://github.com/boto/botocore/blob/develop/CHANGELOG.rst#1170).
`aws-export-credentials` now requires boto3 >= 1.14.0, and so supports AWS SSO credentials as well.
If all you want is AWS SSO support for an SDK other than Python, Go, or JavaScript (v3), take a look at [aws-sso-util](https://github.com/benkehoe/aws-sso-util#adding-aws-sso-support-to-aws-sdks), which can help you configure your profiles with a [credential process](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sourcing-external.html) that doesn't require the credential injection process that `aws-export-credentials` does.
## Quickstart
I recommend you install [`pipx`](https://pipxproject.github.io/pipx/), which installs the tool in an isolated virtualenv while linking the script you need.
```bash
# with pipx
pipx install aws-export-credentials
# without pipx
python3 -m pip install --user aws-export-credentials
# run it
aws-export-credentials
{
"Version": 1,
"AccessKeyId": "<your access key here>",
"SecretAccessKey": "<shhh it's your secret key>",
"SessionToken": "<do you ever wonder what's inside the session token?>"
}
```
You can also download the Python file directly [here](https://raw.githubusercontent.com/benkehoe/aws-export-credentials/stable/aws_export_credentials/aws_export_credentials.py).
## Usage
### Profile
Profiles work like in the AWS CLI (since it uses boto3); it will pick up the `AWS_PROFILE`
or `AWS_DEFAULT_PROFILE` env vars, but the `--profile` argument takes precedence.
### JSON
```
aws-export-credentials --profile my-profile --json [--pretty]
```
Print the credentials to stdout as a JSON object compatible with the `credential_process`
spec. If `--pretty` is added, it'll be pretty-printed.
### Env vars
```
aws-export-credentials --profile my-profile --env
export $(aws-export-credentials --profile my-profile --env)
eval $(aws-export-credentials --profile my-profile --env-export)
```
Print the credentials as environment variables. With `--env-export`, the lines are prefixed
by "`export `".
### Exec wrapper
```
aws-export-credentials --profile my-profile --exec echo 'my access key id is $AWS_ACCESS_KEY_ID'
```
Execute the arguments after `--exec` using `os.system()`, injecting the credentials through
environment variables.
### `~/.aws/credentials`
```
aws-export-credentials --profile my-profile --credentials-file-profile my-exported-profile
aws-export-credentials --profile my-profile -c my-exported-profile
```
Put the credentials in the given profile in your [shared credentials file](https://ben11kehoe.medium.com/aws-configuration-files-explained-9a7ea7a5b42e), which is typically `~/.aws/credentials` but can be controlled using the environment variable [`AWS_SHARED_CREDENTIALS_FILE`](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html).
### Credential-serving options
There are two credential-serving options, `--imds` for a server presenting the EC2 IMDSv2 interface, and `--container` for a server presenting the ECS container metadata credentials interface.
> :warning: If you want to inject refreshable credentials into a locally-run container, [imds-credential-server](https://github.com/benkehoe/imds-credential-server) is a more focused solution for that.
#### IMDS
You can use `--imds` to start a server, compliant with [the EC2 IMDSv2 endpoint](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html), that exports your credentials, and this can be used with containers.
You provide `--imds` with a port (you can optionally provide the host part as well).
If you're using docker, map the port from the host to the container, and set the environment variable `AWS_EC2_METADATA_SERVICE_ENDPOINT` to `http://host.docker.internal:MAPPED_PORT/` with the approporiate port and **remember to include the trailing slash.**
AWS SDKs run inside the container should just work.
```bash
# in one terminal
$ aws-export-credentials --imds 8081
# in a separate terminal
$ docker run --rm -p 8081:8081 -e AWS_EC2_METADATA_SERVICE_ENDPOINT=http://host.docker.internal:8081/
amazon/aws-cli sts get-caller-identity
{
"UserId": "AROAXXXXXXXXXXXXXXXXX:SessionName",
"Account": "123456789012",
"Arn": "arn:aws:sts::123456789012:assumed-role/SomeRole/SessionName"
}
```
#### ECS
> :warning: This method of providing credentials to containers doesn't work well. It only works on Linux using `--network host`. [On Mac](https://docs.docker.com/desktop/mac/networking/#use-cases-and-workarounds) and [Windows](https://docs.docker.com/desktop/windows/networking/#use-cases-and-workarounds), `--network host` is not available, the docker network is always separate. On all three, without `--network host` the host cannot be referenced as `localhost`, only as `host.docker.internal`, which is [not an allowed host the AWS SDKs](https://github.com/aws/aws-sdk/issues/562).
You can use `--container` to start a server, compliant with the ECS metadata server, that exports your credentials, suitable for use with containers.
You provide `--container` with a port (you can optionally provide the host part as well) and an authorization token.
On your container, map the port from the server, set the `AWS_CONTAINER_CREDENTIALS_FULL_URI` environment variable to the URL as accessed inside the container, and set the `AWS_CONTAINER_AUTHORIZATION_TOKEN` environment variable to the same value you provided the server.
You can use any value for the authorization, but it's best use a random value.
```bash
# Generate token. For example, on Linux:
AWS_CONTAINER_AUTHORIZATION_TOKEN=$(/proc/sys/kernel/random/uuid)
# start the server in the background
aws-export-credentials --profile my-profile --container 8081 $AWS_CONTAINER_AUTHORIZATION_TOKEN &
# run your container
docker run --network host -e AWS_CONTAINER_CREDENTIALS_FULL_URI=http://localhost:8081 -e AWS_CONTAINER_AUTHORIZATION_TOKEN=$AWS_CONTAINER_AUTHORIZATION_TOKEN amazon/aws-cli sts get-caller-identity
```
## Caching
To avoid retrieving credentials every time when using `aws-export-credentials` with the same identity, you can cache the credentials in a file using the `--cache-file` argument.
**Note `aws-export-credentials` does not distinguish in the cache between different identities. Different identities should use different cache files.**
If you do not account for this, credentials may be loaded from the cache and exported that do not correspond to the credentials that would be exported without the cache.
An example of a way to address this would be using a cache file named after the config profile you are exporting.
Cache loading and saving fails silently, to ensure caching does not interrupt usage.
If caching is not working, you can see the details with `--debug`.
By default, cached credentials are considered expired if their expiration is less than 10 minutes in the future.
You can change this value using the `--cache-expiration-buffer` argument, which takes a number of minutes.
You can force the cache to refresh using `--refresh`.
## Temporary credentials
IAM Users and the account root have long-term credentials, which carry higher risk than temporary credentials.
The [STS.GetSessionToken](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetSessionToken.html) API call exists to provide temporary credentials based on these long-term credentials.
If you pass the `--ensure-temporary` flag, it will use this API to get temporary credentials to export for an IAM User or account root.
This process is always used for `--imds` and `--container`.
# Role assumption
In general, it's better to do role assumption by using profiles in `~/.aws/config` like this:
```ini
# this is a pre-existing profile you already have
[profile profile-to-call-assume-role-with]
# maybe it's IAM User credentials
# or AWS SSO config
# or whatever else you may have
[profile my-assumed-role]
role_arn = arn:aws:iam::123456789012:role/MyRole
# optional: role_session_name = MyRoleSessionName
source_profile = profile-to-call-assume-role-with
# or instead of source_profile, you can tell it to
# use external credentials. one of:
# credential_source = Environment
# credential_source = Ec2InstanceMetadata
# credential_source = EcsContainer
```
You can then use `my-assumed-role` like any other profile.
It uses the AWS SDKs' built-in support for role assumption, rather than relying on third party code.
It also gets you credential refreshing from the SDKs, where getting the credentials in the manner below cannot refresh them when they expire.
You can then, if needed, export the assumed role credentials with `aws-export-credentials --profile my-assumed-role`.
But if you absolutely must have ad hoc role assumption on the command line, you can accomplish that through [`aws-assume-role-lib`](https://github.com/benkehoe/aws-assume-role-lib#command-line-use).
Raw data
{
"_id": null,
"home_page": "https://github.com/benkehoe/aws-export-credentials",
"name": "aws-export-credentials",
"maintainer": "",
"docs_url": null,
"requires_python": ">=3.7,<4.0",
"maintainer_email": "",
"keywords": "",
"author": "Ben Kehoe",
"author_email": "ben@kehoe.io",
"download_url": "https://files.pythonhosted.org/packages/48/9b/0b5ad086bd7bf6fbbd01bf4e46f5a860b7ff63b2dfb9eb6add2750909f51/aws_export_credentials-0.18.0.tar.gz",
"platform": null,
"description": "# aws-export-credentials\n**Get AWS credentials from a profile to inject into other programs**\n\n> :warning: The AWS CLI now includes a command [`aws configure export-credentials`](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/configure/export-credentials.html) that covers the `--json`, `--env`, and `--env-export` options of `aws-export-credentials`, as well as providing env options for Windows.\n> \n> If you want to inject refreshable credentials into a locally-run container, [`imds-credential-server`](https://github.com/benkehoe/imds-credential-server) is a more focused solution for that.\n\nThere are a number of other projects that extract AWS credentials and/or inject them into programs, but all the ones I've seen use the CLI's cache files directly, rather than leveraging boto3's ability to retrieve and refresh credentials.\nSo I wrote this to do that.\n\n[boto3 (the AWS Python SDK)](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) has added support for loading credentials cached by [`aws sso login`](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/sso/login.html) as of [botocore version 1.17.0](https://github.com/boto/botocore/blob/develop/CHANGELOG.rst#1170).\n`aws-export-credentials` now requires boto3 >= 1.14.0, and so supports AWS SSO credentials as well.\nIf all you want is AWS SSO support for an SDK other than Python, Go, or JavaScript (v3), take a look at [aws-sso-util](https://github.com/benkehoe/aws-sso-util#adding-aws-sso-support-to-aws-sdks), which can help you configure your profiles with a [credential process](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sourcing-external.html) that doesn't require the credential injection process that `aws-export-credentials` does.\n\n## Quickstart\n\nI recommend you install [`pipx`](https://pipxproject.github.io/pipx/), which installs the tool in an isolated virtualenv while linking the script you need.\n\n```bash\n# with pipx\npipx install aws-export-credentials\n\n# without pipx\npython3 -m pip install --user aws-export-credentials\n\n# run it\naws-export-credentials\n{\n \"Version\": 1,\n \"AccessKeyId\": \"<your access key here>\",\n \"SecretAccessKey\": \"<shhh it's your secret key>\",\n \"SessionToken\": \"<do you ever wonder what's inside the session token?>\"\n}\n```\n\nYou can also download the Python file directly [here](https://raw.githubusercontent.com/benkehoe/aws-export-credentials/stable/aws_export_credentials/aws_export_credentials.py).\n\n## Usage\n### Profile\nProfiles work like in the AWS CLI (since it uses boto3); it will pick up the `AWS_PROFILE`\nor `AWS_DEFAULT_PROFILE` env vars, but the `--profile` argument takes precedence.\n\n### JSON\n```\naws-export-credentials --profile my-profile --json [--pretty]\n```\nPrint the credentials to stdout as a JSON object compatible with the `credential_process`\nspec. If `--pretty` is added, it'll be pretty-printed.\n\n### Env vars\n```\naws-export-credentials --profile my-profile --env\nexport $(aws-export-credentials --profile my-profile --env)\neval $(aws-export-credentials --profile my-profile --env-export)\n```\nPrint the credentials as environment variables. With `--env-export`, the lines are prefixed\nby \"`export `\".\n\n### Exec wrapper\n```\naws-export-credentials --profile my-profile --exec echo 'my access key id is $AWS_ACCESS_KEY_ID'\n```\nExecute the arguments after `--exec` using `os.system()`, injecting the credentials through\nenvironment variables.\n\n### `~/.aws/credentials`\n```\naws-export-credentials --profile my-profile --credentials-file-profile my-exported-profile\naws-export-credentials --profile my-profile -c my-exported-profile\n```\nPut the credentials in the given profile in your [shared credentials file](https://ben11kehoe.medium.com/aws-configuration-files-explained-9a7ea7a5b42e), which is typically `~/.aws/credentials` but can be controlled using the environment variable [`AWS_SHARED_CREDENTIALS_FILE`](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-envvars.html).\n\n### Credential-serving options\nThere are two credential-serving options, `--imds` for a server presenting the EC2 IMDSv2 interface, and `--container` for a server presenting the ECS container metadata credentials interface.\n\n> :warning: If you want to inject refreshable credentials into a locally-run container, [imds-credential-server](https://github.com/benkehoe/imds-credential-server) is a more focused solution for that.\n\n#### IMDS\nYou can use `--imds` to start a server, compliant with [the EC2 IMDSv2 endpoint](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html), that exports your credentials, and this can be used with containers.\n\nYou provide `--imds` with a port (you can optionally provide the host part as well).\n\nIf you're using docker, map the port from the host to the container, and set the environment variable `AWS_EC2_METADATA_SERVICE_ENDPOINT` to `http://host.docker.internal:MAPPED_PORT/` with the approporiate port and **remember to include the trailing slash.**\n\nAWS SDKs run inside the container should just work.\n```bash\n# in one terminal\n$ aws-export-credentials --imds 8081\n\n# in a separate terminal\n$ docker run --rm -p 8081:8081 -e AWS_EC2_METADATA_SERVICE_ENDPOINT=http://host.docker.internal:8081/\namazon/aws-cli sts get-caller-identity\n{\n \"UserId\": \"AROAXXXXXXXXXXXXXXXXX:SessionName\",\n \"Account\": \"123456789012\",\n \"Arn\": \"arn:aws:sts::123456789012:assumed-role/SomeRole/SessionName\"\n}\n```\n\n#### ECS\n> :warning: This method of providing credentials to containers doesn't work well. It only works on Linux using `--network host`. [On Mac](https://docs.docker.com/desktop/mac/networking/#use-cases-and-workarounds) and [Windows](https://docs.docker.com/desktop/windows/networking/#use-cases-and-workarounds), `--network host` is not available, the docker network is always separate. On all three, without `--network host` the host cannot be referenced as `localhost`, only as `host.docker.internal`, which is [not an allowed host the AWS SDKs](https://github.com/aws/aws-sdk/issues/562).\n\nYou can use `--container` to start a server, compliant with the ECS metadata server, that exports your credentials, suitable for use with containers.\n\nYou provide `--container` with a port (you can optionally provide the host part as well) and an authorization token.\nOn your container, map the port from the server, set the `AWS_CONTAINER_CREDENTIALS_FULL_URI` environment variable to the URL as accessed inside the container, and set the `AWS_CONTAINER_AUTHORIZATION_TOKEN` environment variable to the same value you provided the server.\n\nYou can use any value for the authorization, but it's best use a random value.\n\n```bash\n# Generate token. For example, on Linux:\nAWS_CONTAINER_AUTHORIZATION_TOKEN=$(/proc/sys/kernel/random/uuid)\n\n# start the server in the background\naws-export-credentials --profile my-profile --container 8081 $AWS_CONTAINER_AUTHORIZATION_TOKEN &\n\n# run your container\ndocker run --network host -e AWS_CONTAINER_CREDENTIALS_FULL_URI=http://localhost:8081 -e AWS_CONTAINER_AUTHORIZATION_TOKEN=$AWS_CONTAINER_AUTHORIZATION_TOKEN amazon/aws-cli sts get-caller-identity\n```\n\n## Caching\nTo avoid retrieving credentials every time when using `aws-export-credentials` with the same identity, you can cache the credentials in a file using the `--cache-file` argument.\n**Note `aws-export-credentials` does not distinguish in the cache between different identities. Different identities should use different cache files.**\nIf you do not account for this, credentials may be loaded from the cache and exported that do not correspond to the credentials that would be exported without the cache.\nAn example of a way to address this would be using a cache file named after the config profile you are exporting.\n\nCache loading and saving fails silently, to ensure caching does not interrupt usage.\nIf caching is not working, you can see the details with `--debug`.\n\nBy default, cached credentials are considered expired if their expiration is less than 10 minutes in the future.\nYou can change this value using the `--cache-expiration-buffer` argument, which takes a number of minutes.\n\nYou can force the cache to refresh using `--refresh`.\n\n## Temporary credentials\nIAM Users and the account root have long-term credentials, which carry higher risk than temporary credentials.\nThe [STS.GetSessionToken](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetSessionToken.html) API call exists to provide temporary credentials based on these long-term credentials.\nIf you pass the `--ensure-temporary` flag, it will use this API to get temporary credentials to export for an IAM User or account root.\nThis process is always used for `--imds` and `--container`.\n\n# Role assumption\nIn general, it's better to do role assumption by using profiles in `~/.aws/config` like this:\n\n```ini\n# this is a pre-existing profile you already have\n[profile profile-to-call-assume-role-with]\n# maybe it's IAM User credentials\n# or AWS SSO config\n# or whatever else you may have\n\n[profile my-assumed-role]\nrole_arn = arn:aws:iam::123456789012:role/MyRole\n# optional: role_session_name = MyRoleSessionName\n\nsource_profile = profile-to-call-assume-role-with\n# or instead of source_profile, you can tell it to\n# use external credentials. one of:\n# credential_source = Environment\n# credential_source = Ec2InstanceMetadata\n# credential_source = EcsContainer\n```\n\nYou can then use `my-assumed-role` like any other profile.\nIt uses the AWS SDKs' built-in support for role assumption, rather than relying on third party code.\nIt also gets you credential refreshing from the SDKs, where getting the credentials in the manner below cannot refresh them when they expire.\n\nYou can then, if needed, export the assumed role credentials with `aws-export-credentials --profile my-assumed-role`.\n\nBut if you absolutely must have ad hoc role assumption on the command line, you can accomplish that through [`aws-assume-role-lib`](https://github.com/benkehoe/aws-assume-role-lib#command-line-use).\n\n",
"bugtrack_url": null,
"license": "Apache-2.0",
"summary": "Get AWS credentials from a profile to inject into other programs",
"version": "0.18.0",
"project_urls": {
"Homepage": "https://github.com/benkehoe/aws-export-credentials",
"Repository": "https://github.com/benkehoe/aws-export-credentials"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "a88cc2bb1f88dfa05fc261fc2bdc84d054e03e4b89558d1c7d8b69b0b0e9fc65",
"md5": "54420edb15b46a1e58e4cc8b83b437d6",
"sha256": "040d77ed17f6e346db60e798b5b735c2fec4ecea4e5ed18e242dc4c743b78839"
},
"downloads": -1,
"filename": "aws_export_credentials-0.18.0-py3-none-any.whl",
"has_sig": false,
"md5_digest": "54420edb15b46a1e58e4cc8b83b437d6",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.7,<4.0",
"size": 18457,
"upload_time": "2023-07-26T21:41:25",
"upload_time_iso_8601": "2023-07-26T21:41:25.101776Z",
"url": "https://files.pythonhosted.org/packages/a8/8c/c2bb1f88dfa05fc261fc2bdc84d054e03e4b89558d1c7d8b69b0b0e9fc65/aws_export_credentials-0.18.0-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "489b0b5ad086bd7bf6fbbd01bf4e46f5a860b7ff63b2dfb9eb6add2750909f51",
"md5": "52184feda3389c5c2a9ebb6c0dd00a1b",
"sha256": "e977a1dee61c26653349cf15408f52128ff6722b3de0194add24d74477f9a0cf"
},
"downloads": -1,
"filename": "aws_export_credentials-0.18.0.tar.gz",
"has_sig": false,
"md5_digest": "52184feda3389c5c2a9ebb6c0dd00a1b",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.7,<4.0",
"size": 19204,
"upload_time": "2023-07-26T21:41:26",
"upload_time_iso_8601": "2023-07-26T21:41:26.655088Z",
"url": "https://files.pythonhosted.org/packages/48/9b/0b5ad086bd7bf6fbbd01bf4e46f5a860b7ff63b2dfb9eb6add2750909f51/aws_export_credentials-0.18.0.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2023-07-26 21:41:26",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "benkehoe",
"github_project": "aws-export-credentials",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "aws-export-credentials"
}