# AWS SSO用户如何使用CLI

AWS SSO/IAM Identity Center用户需要使用CLI的时候可以通过以下任一方法设置环境变量：

## CLI配置

以mac为例，打开命令行工具，输入：

<pre><code><strong>aws configure sso
</strong></code></pre>

* SSO session name (Recommended):起一个名字，比如sso
* SSO start URL \[None]: 你的单点登录的开始页面，比如<https://example.awsapps.com/start>
* SSO region \[None]：你部署SSO的区域，也就是你创建IAM identity Center的时候在哪个区域创建的就写哪个区域
* SSO registration scopes \[sso:account:access]:使用默认的就可以，回车

之后会重定向到浏览器中，登录你的SSO。

每个账号的每一个权限集都可以创建出一个profile，使用不同账号不同的权限集时就需要指定profile。比如生成出来的配置文件如下(位于\~/.aws/config)：

```
[profile Admin]
sso_session = sso
sso_account_id = 123456789012
sso_role_name = AWSAdministratorAccess
region = us-east-1
output = json
[sso-session sso]
sso_start_url = https://example.awsapps.com/start
sso_region = us-east-1
sso_registration_scopes = sso:account:access
```

想要执行查询S3存储桶名称命令时需要指定使用的profile：

```
aws s3 ls --profile Admin
```

## aws-sso-util批量设置profile

如果你的账号和权限集有很多，有一个工具可以一次性帮你创建出所有账号所有权限集的profile。Github地址：<https://github.com/benkehoe/aws-sso-util/tree/master>。安装步骤如下：

Mac [and Linux](https://docs.brew.sh/Homebrew-on-Linux):

```
brew install pipx
pipx ensurepath
```

Other:

```
python3 -m pip install --user pipx
python3 -m pipx ensurepath
```

2. Install

```
pipx install aws-sso-util
```

打开\~/.aws/config文件，添加类似于下面的profile(去掉#及后面的备注，否则会报错)：

```
[profile my-sso-profile]
sso_start_url = https://example.awsapps.com/start
sso_region = us-east-1 # the region Identity Center is configured in
sso_account_id = 123456789012
sso_role_name = MyRoleName
region = us-east-2 # the region to use for AWS API calls
```

然后在命令行工具中执行以下命令，region替换为你常用的区域：

```
aws-sso-util configure populate --region us-east-1
```

执行完成后批量添加profile完成，需要使用哪个profile在写命令的时候就指定使用哪个的名称。

参考资料

[Never put AWS temporary credentials in the credentials file (or env vars)—there’s a better way](https://ben11kehoe.medium.com/never-put-aws-temporary-credentials-in-env-vars-or-credentials-files-theres-a-better-way-25ec45b4d73e)
