获取 AWS 的 MFA API 凭证

Get MFA API credentials for AWS

假设我已经设置了一个 IAM 策略来对所有 AWS API 请求(例如此处描述的请求:)强制执行多重身份验证 (MFA)。我可以使用以下代码通过 sts get-session-token 获取和使用临时凭证:

# Get the serial number of your MFA device
aws --profile <PROFILE_NAME> iam list-mfa-devices --user-name <IAM_USER_NAME>

# Get temporary API keys that will pass MFA verification
aws --profile <PROFILE_NAME> sts get-session-token --serial-number <MFA_SERIAL_NUMBER> --token-code <MFA_TOKEN>

# Export the temporary credentials for use in subsequent calls
export AWS_ACCESS_KEY_ID=<KEY>
export AWS_SECRET_ACCESS_KEY=<SECRET>
export AWS_SESSION_TOKEN=<SESSION_TOKEN>

但是,此代码需要几个步骤,并且仅适用于终端 window 我在其中执行此操作。如何使用一个命令来保存凭据直到它们过期?

有一个名为 iam-mfa 的命令行工具可以为您执行此操作:https://github.com/zagaran/iam-mfa。 (免责声明:我是该工具的主要作者。)

关键是使用命名配置文件。一个配置文件(source_profile)将保存您用来调用 sts get-session-token 的凭据。另一个配置文件(dest_profile)将是您保存从 sts 获得的会话令牌的地方,并且是您用来执行所有后续 API 调用的配置文件。

您可以使用 pip install iam-mfa 安装它。

然后您可以调用它:

iam-mfa <source_profile> <dest_profile> <iam_username>

当您 运行 脚本时,它会提示您输入 MFA 代码。