将 ListPolicies 与 Amazon SDK 或命令行工具配合使用 - Amazon Identity and Access Management
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

ListPolicies 与 Amazon SDK 或命令行工具配合使用

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

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

.NET
Amazon SDK for .NET
注意

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

/// <summary> /// List IAM policies. /// </summary> /// <returns>A list of the IAM policies.</returns> public async Task<List<ManagedPolicy>> ListPoliciesAsync() { var listPoliciesPaginator = _IAMService.Paginators.ListPolicies(new ListPoliciesRequest()); var policies = new List<ManagedPolicy>(); await foreach (var response in listPoliciesPaginator.Responses) { policies.AddRange(response.Policies); } return policies; }
  • 有关 API 的详细信息,请参阅 Amazon SDK for .NET API 参考中的 ListPolicies

C++
SDK for C++
注意

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

bool AwsDoc::IAM::listPolicies(const Aws::Client::ClientConfiguration &clientConfig) { const Aws::String DATE_FORMAT("%Y-%m-%d"); Aws::IAM::IAMClient iam(clientConfig); Aws::IAM::Model::ListPoliciesRequest request; bool done = false; bool header = false; while (!done) { auto outcome = iam.ListPolicies(request); if (!outcome.IsSuccess()) { std::cerr << "Failed to list iam policies: " << outcome.GetError().GetMessage() << std::endl; return false; } if (!header) { std::cout << std::left << std::setw(55) << "Name" << std::setw(30) << "ID" << std::setw(80) << "Arn" << std::setw(64) << "Description" << std::setw(12) << "CreateDate" << std::endl; header = true; } const auto &policies = outcome.GetResult().GetPolicies(); for (const auto &policy: policies) { std::cout << std::left << std::setw(55) << policy.GetPolicyName() << std::setw(30) << policy.GetPolicyId() << std::setw(80) << policy.GetArn() << std::setw(64) << policy.GetDescription() << std::setw(12) << policy.GetCreateDate().ToGmtString(DATE_FORMAT.c_str()) << std::endl; } if (outcome.GetResult().GetIsTruncated()) { request.SetMarker(outcome.GetResult().GetMarker()); } else { done = true; } } return true; }
  • 有关 API 的详细信息,请参阅 Amazon SDK for C++ API 参考中的 ListPolicies

CLI
Amazon CLI

要列出 Amazon 账户可用的托管策略

此示例将返回当前 Amazon 账户中可用的前两个托管策略的集合。

aws iam list-policies \ --max-items 3

输出:

{ "Policies": [ { "PolicyName": "AWSCloudTrailAccessPolicy", "PolicyId": "ANPAXQE2B5PJ7YEXAMPLE", "Arn": "arn:aws:iam::123456789012:policy/AWSCloudTrailAccessPolicy", "Path": "/", "DefaultVersionId": "v1", "AttachmentCount": 0, "PermissionsBoundaryUsageCount": 0, "IsAttachable": true, "CreateDate": "2019-09-04T17:43:42+00:00", "UpdateDate": "2019-09-04T17:43:42+00:00" }, { "PolicyName": "AdministratorAccess", "PolicyId": "ANPAIWMBCKSKIEE64ZLYK", "Arn": "arn:aws:iam::aws:policy/AdministratorAccess", "Path": "/", "DefaultVersionId": "v1", "AttachmentCount": 6, "PermissionsBoundaryUsageCount": 0, "IsAttachable": true, "CreateDate": "2015-02-06T18:39:46+00:00", "UpdateDate": "2015-02-06T18:39:46+00:00" }, { "PolicyName": "PowerUserAccess", "PolicyId": "ANPAJYRXTHIB4FOVS3ZXS", "Arn": "arn:aws:iam::aws:policy/PowerUserAccess", "Path": "/", "DefaultVersionId": "v5", "AttachmentCount": 1, "PermissionsBoundaryUsageCount": 0, "IsAttachable": true, "CreateDate": "2015-02-06T18:39:47+00:00", "UpdateDate": "2023-07-06T22:04:00+00:00" } ], "NextToken": "EXAMPLErZXIiOiBudWxsLCAiYm90b190cnVuY2F0ZV9hbW91bnQiOiA4fQ==" }

有关更多信息,请参阅《Amazon IAM 用户指南》中的 IAM 中的策略和权限

  • 有关 API 详细信息,请参阅《Amazon CLI 命令参考》中的 ListPolicies

Go
适用于 Go V2 的 SDK
注意

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

// PolicyWrapper encapsulates AWS Identity and Access Management (IAM) policy actions // used in the examples. // It contains an IAM service client that is used to perform policy actions. type PolicyWrapper struct { IamClient *iam.Client } // ListPolicies gets up to maxPolicies policies. func (wrapper PolicyWrapper) ListPolicies(maxPolicies int32) ([]types.Policy, error) { var policies []types.Policy result, err := wrapper.IamClient.ListPolicies(context.TODO(), &iam.ListPoliciesInput{ MaxItems: aws.Int32(maxPolicies), }) if err != nil { log.Printf("Couldn't list policies. Here's why: %v\n", err) } else { policies = result.Policies } return policies, err }
  • 有关 API 详细信息,请参阅《Amazon SDK for Go API 参考》中的 ListPolicies

JavaScript
SDK for JavaScript (v3)
注意

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

列出策略。

import { ListPoliciesCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * A generator function that handles paginated results. * The AWS SDK for JavaScript (v3) provides {@link https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/index.html#paginators | paginator} functions to simplify this. * */ export async function* listPolicies() { const command = new ListPoliciesCommand({ MaxItems: 10, OnlyAttached: false, // List only the customer managed policies in your Amazon Web Services account. Scope: "Local", }); let response = await client.send(command); while (response.Policies?.length) { for (const policy of response.Policies) { yield policy; } if (response.IsTruncated) { response = await client.send( new ListPoliciesCommand({ Marker: response.Marker, MaxItems: 10, OnlyAttached: false, Scope: "Local", }), ); } else { break; } } }
  • 有关 API 详细信息,请参阅《Amazon SDK for JavaScript API 参考》中的 ListPolicies

PHP
适用于 PHP 的 SDK
注意

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

$uuid = uniqid(); $service = new IAMService(); public function listPolicies($pathPrefix = "", $marker = "", $maxItems = 0) { $listPoliciesArguments = []; if ($pathPrefix) { $listPoliciesArguments["PathPrefix"] = $pathPrefix; } if ($marker) { $listPoliciesArguments["Marker"] = $marker; } if ($maxItems) { $listPoliciesArguments["MaxItems"] = $maxItems; } return $this->iamClient->listPolicies($listPoliciesArguments); }
  • 有关 API 的详细信息,请参阅 Amazon SDK for PHP API 参考中的 ListPolicies

PowerShell
适用于 PowerShell 的工具

示例 1:此示例将返回当前 Amazon 账户中可用的前三个托管策略的集合。由于 -scope 未指定,因此其默认为 all,并包含 Amazon 托管策略和客户管理型策略。

Get-IAMPolicyList -MaxItem 3

输出:

Arn : arn:aws:iam::aws:policy/AWSDirectConnectReadOnlyAccess AttachmentCount : 0 CreateDate : 2/6/2015 10:40:08 AM DefaultVersionId : v1 Description : IsAttachable : True Path : / PolicyId : Z27SI6FQMGNQ2EXAMPLE1 PolicyName : AWSDirectConnectReadOnlyAccess UpdateDate : 2/6/2015 10:40:08 AM Arn : arn:aws:iam::aws:policy/AmazonGlacierReadOnlyAccess AttachmentCount : 0 CreateDate : 2/6/2015 10:40:27 AM DefaultVersionId : v1 Description : IsAttachable : True Path : / PolicyId : NJKMU274MET4EEXAMPLE2 PolicyName : AmazonGlacierReadOnlyAccess UpdateDate : 2/6/2015 10:40:27 AM Arn : arn:aws:iam::aws:policy/AWSMarketplaceFullAccess AttachmentCount : 0 CreateDate : 2/11/2015 9:21:45 AM DefaultVersionId : v1 Description : IsAttachable : True Path : / PolicyId : 5ULJSO2FYVPYGEXAMPLE3 PolicyName : AWSMarketplaceFullAccess UpdateDate : 2/11/2015 9:21:45 AM

示例 2:此示例将返回当前 Amazon 账户中可用的前两个客户管理型策略的集合。其使用 -Scope local 将输出限制为仅限客户管理型策略。

Get-IAMPolicyList -Scope local -MaxItem 2

输出:

Arn : arn:aws:iam::123456789012:policy/MyLocalPolicy AttachmentCount : 0 CreateDate : 2/12/2015 9:39:09 AM DefaultVersionId : v2 Description : IsAttachable : True Path : / PolicyId : SQVCBLC4VAOUCEXAMPLE4 PolicyName : MyLocalPolicy UpdateDate : 2/12/2015 9:39:53 AM Arn : arn:aws:iam::123456789012:policy/policyforec2instancerole AttachmentCount : 1 CreateDate : 2/17/2015 2:51:38 PM DefaultVersionId : v11 Description : IsAttachable : True Path : / PolicyId : X5JPBLJH2Z2SOEXAMPLE5 PolicyName : policyforec2instancerole UpdateDate : 2/18/2015 8:52:31 AM
  • 有关 API 详细信息,请参阅《Amazon Tools for PowerShell Cmdlet 参考》中的 ListPolicies

Python
SDK for Python(Boto3)
注意

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

def list_policies(scope): """ Lists the policies in the current account. :param scope: Limits the kinds of policies that are returned. For example, 'Local' specifies that only locally managed policies are returned. :return: The list of policies. """ try: policies = list(iam.policies.filter(Scope=scope)) logger.info("Got %s policies in scope '%s'.", len(policies), scope) except ClientError: logger.exception("Couldn't get policies for scope '%s'.", scope) raise else: return policies
  • 有关 API 详细信息,请参阅《Amazon SDK for Python(Boto3)API 参考》中的 ListPolicies

Ruby
适用于 Ruby 的 SDK
注意

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

此示例模块会列出、创建、附加和分离角色策略。

# Manages policies in AWS Identity and Access Management (IAM) class RolePolicyManager # Initialize with an AWS IAM client # # @param iam_client [Aws::IAM::Client] An initialized IAM client def initialize(iam_client, logger: Logger.new($stdout)) @iam_client = iam_client @logger = logger @logger.progname = "PolicyManager" end # Creates a policy # # @param policy_name [String] The name of the policy # @param policy_document [Hash] The policy document # @return [String] The policy ARN if successful, otherwise nil def create_policy(policy_name, policy_document) response = @iam_client.create_policy( policy_name: policy_name, policy_document: policy_document.to_json ) response.policy.arn rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error creating policy: #{e.message}") nil end # Fetches an IAM policy by its ARN # @param policy_arn [String] the ARN of the IAM policy to retrieve # @return [Aws::IAM::Types::GetPolicyResponse] the policy object if found def get_policy(policy_arn) response = @iam_client.get_policy(policy_arn: policy_arn) policy = response.policy @logger.info("Got policy '#{policy.policy_name}'. Its ID is: #{policy.policy_id}.") policy rescue Aws::IAM::Errors::NoSuchEntity @logger.error("Couldn't get policy '#{policy_arn}'. The policy does not exist.") raise rescue Aws::IAM::Errors::ServiceError => e @logger.error("Couldn't get policy '#{policy_arn}'. Here's why: #{e.code}: #{e.message}") raise end # Attaches a policy to a role # # @param role_name [String] The name of the role # @param policy_arn [String] The policy ARN # @return [Boolean] true if successful, false otherwise def attach_policy_to_role(role_name, policy_arn) @iam_client.attach_role_policy( role_name: role_name, policy_arn: policy_arn ) true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error attaching policy to role: #{e.message}") false end # Lists policy ARNs attached to a role # # @param role_name [String] The name of the role # @return [Array<String>] List of policy ARNs def list_attached_policy_arns(role_name) response = @iam_client.list_attached_role_policies(role_name: role_name) response.attached_policies.map(&:policy_arn) rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error listing policies attached to role: #{e.message}") [] end # Detaches a policy from a role # # @param role_name [String] The name of the role # @param policy_arn [String] The policy ARN # @return [Boolean] true if successful, false otherwise def detach_policy_from_role(role_name, policy_arn) @iam_client.detach_role_policy( role_name: role_name, policy_arn: policy_arn ) true rescue Aws::IAM::Errors::ServiceError => e @logger.error("Error detaching policy from role: #{e.message}") false end end
  • 有关 API 详细信息,请参阅《Amazon SDK for Ruby API 参考》中的 ListPolicies

Rust
适用于 Rust 的 SDK
注意

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

pub async fn list_policies( client: iamClient, path_prefix: String, ) -> Result<Vec<String>, SdkError<ListPoliciesError>> { let list_policies = client .list_policies() .path_prefix(path_prefix) .scope(PolicyScopeType::Local) .into_paginator() .items() .send() .try_collect() .await?; let policy_names = list_policies .into_iter() .map(|p| { let name = p .policy_name .unwrap_or_else(|| "Missing Policy Name".to_string()); println!("{}", name); name }) .collect(); Ok(policy_names) }
  • 有关 API 详细信息,请参阅《Amazon SDK for Rust API 参考》中的 ListPolicies

Swift
SDK for Swift
注意

这是预览版 SDK 的预发布文档。本文档随时可能更改。

注意

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

public func listPolicies() async throws -> [MyPolicyRecord] { var policyList: [MyPolicyRecord] = [] var marker: String? = nil var isTruncated: Bool repeat { let input = ListPoliciesInput(marker: marker) let output = try await client.listPolicies(input: input) guard let policies = output.policies else { return policyList } for policy in policies { guard let name = policy.policyName, let id = policy.policyId, let arn = policy.arn else { throw ServiceHandlerError.noSuchPolicy } policyList.append(MyPolicyRecord(name: name, id: id, arn: arn)) } marker = output.marker isTruncated = output.isTruncated } while isTruncated == true return policyList }
  • 有关 API 详细信息,请参阅 Amazon SDK for Swift API 参考中的 ListPolicies

有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 将 IAM 与 Amazon 开发工具包配合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。