├── .gitignore ├── pyproject.toml ├── README.md ├── aws_whoami.py └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | Pipfile.lock 3 | 4 | .DS_Store? 5 | ._* 6 | .Spotlight-V100 7 | .Trashes 8 | ehthumbs.db 9 | Thumbs.db 10 | *.swp 11 | 12 | .*project 13 | *.py[cxo] 14 | __pycache__ 15 | .venv 16 | .env 17 | 18 | .aws-sam 19 | samconfig.toml 20 | 21 | dist 22 | poetry.lock 23 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "aws-whoami" 3 | version = "1.2.0" 4 | description = "A tool and library for determining what AWS account and identity you're using" 5 | authors = ["Ben Kehoe "] 6 | license = "Apache-2.0" 7 | readme = "README.md" 8 | homepage = "https://github.com/benkehoe/aws-whoami" 9 | repository = "https://github.com/benkehoe/aws-whoami" 10 | classifiers = [ 11 | "Development Status :: 4 - Beta", 12 | "Intended Audience :: Developers", 13 | "Intended Audience :: System Administrators", 14 | "License :: OSI Approved :: Apache Software License", 15 | "Operating System :: OS Independent", 16 | "Topic :: Utilities", 17 | ] 18 | 19 | [tool.poetry.scripts] 20 | aws-whoami = 'aws_whoami:main' 21 | 22 | [tool.poetry.dependencies] 23 | python = ">=2.6, !=3.0.*, !=3.1.*, !=3.2.*" 24 | boto3 = "*" 25 | 26 | [tool.poetry.dev-dependencies] 27 | 28 | [build-system] 29 | requires = ["poetry>=0.12"] 30 | build-backend = "poetry.masonry.api" 31 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # aws-whoami 2 | **Show what AWS account and identity you're using** 3 | 4 | > :warning: The `aws-whoami` CLI tool is [now implemented in Go](https://github.com/benkehoe/aws-whoami-golang), and the Python version is unmaintained as a CLI tool. It can still be used as a library. 5 | 6 | You should know about [`aws sts get-caller-identity`](https://docs.aws.amazon.com/cli/latest/reference/sts/get-caller-identity.html), 7 | which sensibly returns the identity of the caller. But even with `--output table`, I find this a bit lacking. 8 | That ARN is a lot to visually parse, it doesn't tell you what region your credentials are configured for, 9 | and I am not very good at remembering AWS account numbers. `aws-whoami` makes it better. 10 | 11 | ``` 12 | $ aws-whoami 13 | Account: 123456789012 14 | my-account-alias 15 | Region: us-east-2 16 | AssumedRole: MY-ROLE 17 | RoleSessionName: ben 18 | UserId: SOMEOPAQUEID:ben 19 | Arn: arn:aws:sts::123456789012:assumed-role/MY-ROLE/ben 20 | ``` 21 | 22 | Note: if you don't have permissions to [iam:ListAccountAliases](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ListAccountAliases.html), 23 | your account alias won't appear. See below for disabling this check if getting a permission denied on this call raises flags in your organization. 24 | 25 | ## Install 26 | 27 | I recommend you install `aws-whoami` with [`pipx`](https://pipxproject.github.io/pipx/), which installs the tool in an isolated virtualenv while linking the script you need. 28 | 29 | ```bash 30 | # with pipx 31 | pipx install aws-whoami 32 | 33 | # without pipx 34 | python -m pip install --user aws-whoami 35 | ``` 36 | 37 | If you don't want to install it, the [`aws_whoami.py`](https://raw.githubusercontent.com/benkehoe/aws-whoami/master/aws_whoami.py) file can be used on its own, with only a dependency on `botocore` (which comes with `boto3`). 38 | 39 | ## Options 40 | 41 | `aws-whoami` uses [`boto3`](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html), so it'll pick up your credentials in [the normal ways](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-configure.html#config-settings-and-precedence), 42 | including with the `--profile` parameter. 43 | 44 | If you'd like the output as a JSON object, that's the `--json` flag. 45 | The output is the `WhoamiInfo` object (see below) as a JSON object. 46 | 47 | To full disable account alias checking, set the environment variable `AWS_WHOAMI_DISABLE_ACCOUNT_ALIAS` to `true`. 48 | To selectively disable it, you can also set it to a comma-separated list of values that will be matched against the following: 49 | * The beginning or end of the account number 50 | * The principal Name or ARN 51 | * The role session name 52 | 53 | ## As a library 54 | 55 | The library has a `whoami()` function, which optionally takes a `Session` (either `boto3` or `botocore`), and returns a `WhoamiInfo` namedtuple. 56 | 57 | The fields of `WhoamiInfo` are: 58 | * `Account` 59 | * `AccountAliases` (NOTE: this is a list) 60 | * `Arn` 61 | * `Type` 62 | * `Name` 63 | * `RoleSessionName` 64 | * `UserId` 65 | * `Region` 66 | * `SSOPermissionSet` 67 | 68 | `Type`, `Name`, and `RoleSessionName` (and `SSOPermissionSet`) are split from the ARN for convenience. 69 | `RoleSessionName` is `None` for IAM users. 70 | 71 | `SSOPermissionSet` is set if the assumed role name conforms to the format `AWSReservedSSO_{permission-set}_{random-tag}`. 72 | 73 | To disable the account alias check, pass `disable_account_alias=True` to `whoami()`. 74 | Note that the `AccountAliases` field will then be an empty list, not `None`. 75 | 76 | `format_whoami()` takes a `WhoamiInfo` object and returns the formatted string used for display. 77 | -------------------------------------------------------------------------------- /aws_whoami.py: -------------------------------------------------------------------------------- 1 | # Copyright 2020 Ben Kehoe 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | """Utility for determining what AWS account and identity you're using.""" 16 | 17 | from __future__ import print_function 18 | 19 | import argparse 20 | from collections import namedtuple 21 | import json 22 | import sys 23 | import os 24 | import traceback 25 | 26 | import botocore 27 | import botocore.session 28 | from botocore.exceptions import ClientError 29 | 30 | __version__ = '1.2.0' 31 | 32 | WhoamiInfo = namedtuple('WhoamiInfo', [ 33 | 'Account', 34 | 'AccountAliases', 35 | 'Arn', 36 | 'Type', 37 | 'Name', 38 | 'RoleSessionName', 39 | 'UserId', 40 | 'Region', 41 | 'SSOPermissionSet', 42 | ]) 43 | 44 | DESCRIPTION = """\ 45 | Show what AWS account and identity you're using. 46 | Formats the output of sts.GetCallerIdentity nicely, 47 | and also gets your account alias (if you're allowed) 48 | """ 49 | 50 | def main(): 51 | parser = argparse.ArgumentParser(description=DESCRIPTION) 52 | 53 | parser.add_argument('--profile', help="AWS profile to use") 54 | 55 | parser.add_argument('--json', action='store_true', help="Output as JSON") 56 | 57 | parser.add_argument('--version', action='store_true') 58 | 59 | parser.add_argument('--debug', action='store_true') 60 | 61 | args = parser.parse_args() 62 | 63 | if args.version: 64 | print(__version__) 65 | parser.exit() 66 | 67 | try: 68 | session = botocore.session.Session(profile=args.profile) 69 | 70 | disable_account_alias = os.environ.get('AWS_WHOAMI_DISABLE_ACCOUNT_ALIAS', '') 71 | if disable_account_alias.lower() in ['', '0', 'false']: 72 | disable_account_alias = False 73 | elif disable_account_alias.lower() in ['1', 'true']: 74 | disable_account_alias = True 75 | else: 76 | disable_account_alias = disable_account_alias.split(',') 77 | 78 | whoami_info = whoami(session=session, disable_account_alias=disable_account_alias) 79 | 80 | if args.json: 81 | print(json.dumps(whoami_info._asdict())) 82 | else: 83 | print(format_whoami(whoami_info)) 84 | except Exception as e: 85 | if args.debug: 86 | traceback.print_exc() 87 | err_cls = type(e) 88 | err_cls_str = err_cls.__name__ 89 | if err_cls.__module__ != 'builtins': 90 | err_cls_str = '{}.{}'.format(err_cls.__module__, err_cls_str) 91 | sys.stderr.write('ERROR [{}]: {}\n'.format(err_cls_str, e)) 92 | sys.exit(1) 93 | 94 | def format_whoami(whoami_info): 95 | lines = [] 96 | lines.append(('Account: ', whoami_info.Account)) 97 | for alias in whoami_info.AccountAliases: 98 | lines.append(('', alias)) 99 | lines.append(('Region: ', whoami_info.Region)) 100 | if whoami_info.SSOPermissionSet: 101 | lines.append(('AWS SSO: ', whoami_info.SSOPermissionSet)) 102 | else: 103 | type_str = ''.join(p[0].upper() + p[1:] for p in whoami_info.Type.split('-')) 104 | lines.append(('{}: '.format(type_str), whoami_info.Name)) 105 | if whoami_info.RoleSessionName: 106 | lines.append(('RoleSessionName: ', whoami_info.RoleSessionName)) 107 | lines.append(('UserId: ', whoami_info.UserId)) 108 | lines.append(('Arn: ', whoami_info.Arn)) 109 | max_len = max(len(l[0]) for l in lines) 110 | return '\n'.join("{}{}".format(l[0].ljust(max_len), l[1]) for l in lines) 111 | 112 | def whoami(session=None, disable_account_alias=False): 113 | """Return a WhoamiInfo namedtuple. 114 | 115 | Args: 116 | session: An optional boto3 or botocore Session 117 | disable_account_alias (bool): Disable checking the account alias 118 | 119 | Returns: 120 | WhoamiInfo: Data on the current IAM principal, account, and region. 121 | 122 | """ 123 | if session is None: 124 | session = botocore.session.get_session() 125 | elif hasattr(session, '_session'): # allow boto3 Session as well 126 | session = session._session 127 | 128 | data = {} 129 | data['Region'] = session.get_config_variable('region') 130 | 131 | response = session.create_client('sts').get_caller_identity() 132 | 133 | for field in ['Account', 'Arn', 'UserId']: 134 | data[field] = response[field] 135 | 136 | data['Type'], name = data['Arn'].rsplit(':', 1)[1].split('/',1) 137 | 138 | if data['Type'] == 'assumed-role': 139 | data['Name'], data['RoleSessionName'] = name.rsplit('/', 1) 140 | else: 141 | data['Name'] = name 142 | data['RoleSessionName'] = None 143 | 144 | if data['Type'] == 'assumed-role' and data['Name'].startswith('AWSReservedSSO'): 145 | try: 146 | # format is AWSReservedSSO_{permission-set}_{random-tag} 147 | data['SSOPermissionSet'] = data['Name'].split('_', 1)[1].rsplit('_', 1)[0] 148 | except Exception as e: 149 | data['SSOPermissionSet'] = None 150 | else: 151 | data['SSOPermissionSet'] = None 152 | 153 | data['AccountAliases'] = [] 154 | if not isinstance(disable_account_alias, bool): 155 | for value in disable_account_alias: 156 | if data['Account'].startswith(value) or data['Account'].endswith(value): 157 | disable_account_alias = True 158 | break 159 | fields = ['Name', 'Arn', 'RoleSessionName'] 160 | if any(value == data[field] for field in fields): 161 | disable_account_alias = True 162 | break 163 | if not disable_account_alias: 164 | try: 165 | #pedantry 166 | paginator = session.create_client('iam').get_paginator('list_account_aliases') 167 | for response in paginator.paginate(): 168 | data['AccountAliases'].extend(response['AccountAliases']) 169 | except ClientError as e: 170 | if e.response.get('Error', {}).get('Code') != 'AccessDenied': 171 | raise 172 | 173 | return WhoamiInfo(**data) 174 | 175 | if __name__ == '__main__': 176 | main() 177 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2020 Ben Kehoe 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | --------------------------------------------------------------------------------