AttachUserPolicy与 AWS SDK 或 CLI 配合使用 - AWS SDK 代码示例

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

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

AttachUserPolicy与 AWS SDK 或 CLI 配合使用

以下代码示例演示如何使用 AttachUserPolicy

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

CLI
AWS CLI

将托管策略附加到 IAM 用户

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

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

此命令不生成任何输出。

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

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

PowerShell
适用于 PowerShell V4 的工具

示例 1:此示例将名为的 AWS 托管策略附加AmazonCognitoPowerUser到 IAM 用户Bob。用户会立即受到该策略最新版本中所定义权限的影响。

Register-IAMUserPolicy -UserName Bob -PolicyArn arn:aws:iam::aws:policy/AmazonCognitoPowerUser
  • 有关 API 的详细信息,请参阅 AWS Tools for PowerShell Cmdlet 参考 (V 4) AttachUserPolicy中的。

适用于 PowerShell V5 的工具

示例 1:此示例将名为的 AWS 托管策略附加AmazonCognitoPowerUser到 IAM 用户Bob。用户会立即受到该策略最新版本中所定义权限的影响。

Register-IAMUserPolicy -UserName Bob -PolicyArn arn:aws:iam::aws:policy/AmazonCognitoPowerUser
  • 有关 API 的详细信息,请参阅 AWS Tools for PowerShell Cmdlet 参考 (V 5) AttachUserPolicy中的。

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

还有更多相关信息 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 的详细信息,请参阅 适用于 Ruby 的 AWS SDK API 参考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 参考