使用 AWS 开发工具包将 IAM policy 附加到用户 - AWS SDK 代码示例

文档 AWS SDK 示例 GitHub 存储库中还有更多 S AWS DK 示例

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

使用 AWS 开发工具包将 IAM policy 附加到用户

以下代码示例演示如何将 IAM 策略附加到用户。

警告

为了避免安全风险,在开发专用软件或处理真实数据时,请勿使用 IAM 用户进行身份验证。而是使用与身份提供商的联合身份验证,例如 AWS IAM Identity Center

操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:

CLI
AWS CLI

要将托管策略附加到 IAM 用户

以下 attach-user-policy 命令可将名为 AdministratorAccess 的 AWS 托管策略附加到名为 Alice 的 IAM 用户。

aws iam attach-user-policy \ --policy-arn arn:aws:iam::aws:policy/AdministratorAccess \ --user-name Alice

此命令不生成任何输出。

有关更多信息,请参阅《AWS IAM 用户指南》中的托管策略和内联策略

  • 有关 API 的详细信息,请参阅AWS CLI命令参考AttachUserPolicy中的。

Python
适用于 Python (Boto3) 的 SDK
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

def attach_policy(user_name, policy_arn): """ Attaches a policy to a user. :param user_name: The name of the user. :param policy_arn: The Amazon Resource Name (ARN) of the policy. """ try: iam.User(user_name).attach_policy(PolicyArn=policy_arn) logger.info("Attached policy %s to user %s.", policy_arn, user_name) except ClientError: logger.exception("Couldn't attach policy %s to user %s.", policy_arn, user_name) raise
  • 有关 API 的详细信息,请参阅适用AttachUserPolicyPython 的 AWS SDK (Boto3) API 参考

Ruby
适用于 Ruby 的 SDK
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

# Attaches a policy to a user # # @param user_name [String] The name of the user # @param policy_arn [String] The Amazon Resource Name (ARN) of the policy # @return [Boolean] true if successful, false otherwise def attach_policy_to_user(user_name, policy_arn) @iam_client.attach_user_policy( user_name: user_name, policy_arn: policy_arn ) true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error attaching policy to user: #{e.message}") false end
  • 有关 API 的详细信息,请参阅 AWS SDK for RubyAPI 参考AttachUserPolicy中的。

Rust
适用于 Rust 的 SDK
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整示例,了解如何进行设置和运行。

pub async fn attach_user_policy( client: &iamClient, user_name: &str, policy_arn: &str, ) -> Result<(), iamError> { client .attach_user_policy() .user_name(user_name) .policy_arn(policy_arn) .send() .await?; Ok(()) }
  • 有关 API 的详细信息,请参阅适用AttachUserPolicyRust 的 AWS SDK API 参考