将 Amazon CLI 与 Bash 脚本结合使用的 Amazon STS 示例 - Amazon Command Line Interface
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

本文档仅适用于 Amazon CLI 版本 1。有关 Amazon CLI 版本 2 的相关文档,请参阅版本 2 用户指南

将 Amazon CLI 与 Bash 脚本结合使用的 Amazon STS 示例

以下代码示例显示了如何通过 Amazon STS 将 Amazon Command Line Interface 与 Bash 脚本一起使用来执行操作和实现常见场景。

操作是大型程序的代码摘录,必须在上下文中运行。虽然操作向您展示了如何调用单个服务函数,但您可以在其相关场景和跨服务示例中查看操作的上下文。

场景是展示如何通过在同一服务中调用多个函数来完成特定任务的代码示例。

每个示例都包含一个指向 GitHub 的链接,其中包含了有关如何在上下文中设置和运行代码的说明。

主题

操作

以下代码示例演示了如何通过 Amazon STS 代入角色。

Amazon CLI 及 Bash 脚本
注意

在 GitHub 上查看更多内容。在 Amazon 代码示例存储库 中查找完整示例,了解如何进行设置和运行。

############################################################################### # function iecho # # This function enables the script to display the specified text only if # the global variable $VERBOSE is set to true. ############################################################################### function iecho() { if [[ $VERBOSE == true ]]; then echo "$@" fi } ############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################### # function sts_assume_role # # This function assumes a role in the AWS account and returns the temporary # credentials. # # Parameters: # -n role_session_name -- The name of the session. # -r role_arn -- The ARN of the role to assume. # # Returns: # [access_key_id, secret_access_key, session_token] # And: # 0 - If successful. # 1 - If an error occurred. ############################################################################### function sts_assume_role() { local role_session_name role_arn response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function sts_assume_role" echo "Assumes a role in the AWS account and returns the temporary credentials:" echo " -n role_session_name -- The name of the session." echo " -r role_arn -- The ARN of the role to assume." echo "" } while getopts n:r:h option; do case "${option}" in n) role_session_name=${OPTARG} ;; r) role_arn=${OPTARG} ;; h) usage return 0 ;; \?) ech o"Invalid parameter" usage return 1 ;; esac done response=$(aws sts assume-role \ --role-session-name "$role_session_name" \ --role-arn "$role_arn" \ --output text \ --query "Credentials.[AccessKeyId, SecretAccessKey, SessionToken]") local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports create-role operation failed.\n$response" return 1 fi echo "$response" return 0 }
  • 有关 API 详细信息,请参阅《Amazon CLI Command Reference》中的 AssumeRole