AttachUserPolicy 搭配 AWS SDK 或 CLI 使用 - AWS Identity and Access Management

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

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
Tools for PowerShell

範例 1:此範例會將名為 AmazonCognitoPowerUser的 AWS 受管政策連接至 IAM 使用者 Bob。該最新版本政策中所定義的許可會立即影響使用者。

Register-IAMUserPolicy -UserName Bob -PolicyArn arn:aws:iam::aws:policy/AmazonCognitoPowerUser
  • 如需 API 詳細資訊,請參閱 AWS Tools for PowerShell Cmdlet Reference 中的 AttachUserPolicy

Python
SDK for Python (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 詳細資訊,請參閱 AWS SDK for Python (Boto3) API Reference 中的 AttachUserPolicy

Ruby
SDK for Ruby
注意

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 Ruby API Reference 中的 AttachUserPolicy

Rust
SDK for Rust
注意

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 詳細資訊,請參閱 AWS SDK for Rust API reference 中的 AttachUserPolicy

如需 AWS SDK 開發人員指南和程式碼範例的完整清單,請參閱 將此服務與 AWS SDK 搭配使用。此主題也包含有關入門的資訊和舊版 SDK 的詳細資訊。