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

DeletePolicy 与 Amazon SDK 或 CLI 配合使用

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

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

.NET
Amazon SDK for .NET
注意

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

/// <summary> /// Delete an IAM policy. /// </summary> /// <param name="policyArn">The Amazon Resource Name (ARN) of the policy to /// delete.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> DeletePolicyAsync(string policyArn) { var response = await _IAMService.DeletePolicyAsync(new DeletePolicyRequest { PolicyArn = policyArn }); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; }
  • 有关 API 详细信息,请参阅《Amazon SDK for .NET API 参考》中的 DeletePolicy

Bash
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 iam_delete_policy # # This function deletes an IAM policy. # # Parameters: # -n policy_arn -- The name of the IAM policy arn. # # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################### function iam_delete_policy() { local policy_arn response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function iam_delete_policy" echo "Deletes an WS Identity and Access Management (IAM) policy" echo " -n policy_arn -- The name of the IAM policy arn." echo "" } # Retrieve the calling parameters. while getopts "n:h" option; do case "${option}" in n) policy_arn="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$policy_arn" ]]; then errecho "ERROR: You must provide a policy arn with the -n parameter." usage return 1 fi iecho "Parameters:\n" iecho " Policy arn: $policy_arn" iecho "" response=$(aws iam delete-policy \ --policy-arn "$policy_arn") local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports delete-policy operation failed.\n$response" return 1 fi iecho "delete-policy response:$response" iecho return 0 }
  • 有关 API 详细信息,请参阅《Amazon CLI Command Reference》中的 DeletePolicy

C++
SDK for C++
注意

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

bool AwsDoc::IAM::deletePolicy(const Aws::String &policyArn, const Aws::Client::ClientConfiguration &clientConfig) { Aws::IAM::IAMClient iam(clientConfig); Aws::IAM::Model::DeletePolicyRequest request; request.SetPolicyArn(policyArn); auto outcome = iam.DeletePolicy(request); if (!outcome.IsSuccess()) { std::cerr << "Error deleting policy with arn " << policyArn << ": " << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully deleted policy with arn " << policyArn << std::endl; } return outcome.IsSuccess(); }
  • 有关 API 详细信息,请参阅《Amazon SDK for C++ API 参考》中的 DeletePolicy

CLI
Amazon CLI

要删除 IAM policy

此示例删除了 ARN 为 arn:aws:iam::123456789012:policy/MySamplePolicy 的策略。

aws iam delete-policy \ --policy-arn arn:aws:iam::123456789012:policy/MySamplePolicy

此命令不生成任何输出。

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

  • 有关 API 详细信息,请参阅《Amazon CLI Command Reference》中的 DeletePolicy

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 } // DeletePolicy deletes a policy. func (wrapper PolicyWrapper) DeletePolicy(ctx context.Context, policyArn string) error { _, err := wrapper.IamClient.DeletePolicy(ctx, &iam.DeletePolicyInput{ PolicyArn: aws.String(policyArn), }) if err != nil { log.Printf("Couldn't delete policy %v. Here's why: %v\n", policyArn, err) } return err }
  • 有关 API 详细信息,请参阅《Amazon SDK for Go API 参考》中的 DeletePolicy

Java
SDK for Java 2.x
注意

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

import software.amazon.awssdk.services.iam.model.DeletePolicyRequest; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.iam.IamClient; import software.amazon.awssdk.services.iam.model.IamException; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DeletePolicy { public static void main(String[] args) { final String usage = """ Usage: <policyARN>\s Where: policyARN - A policy ARN value to delete.\s """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String policyARN = args[0]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() .region(region) .build(); deleteIAMPolicy(iam, policyARN); iam.close(); } public static void deleteIAMPolicy(IamClient iam, String policyARN) { try { DeletePolicyRequest request = DeletePolicyRequest.builder() .policyArn(policyARN) .build(); iam.deletePolicy(request); System.out.println("Successfully deleted the policy"); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } System.out.println("Done"); } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 DeletePolicy

JavaScript
SDK for JavaScript (v3)
注意

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

删除策略。

import { DeletePolicyCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} policyArn */ export const deletePolicy = (policyArn) => { const command = new DeletePolicyCommand({ PolicyArn: policyArn }); return client.send(command); };
  • 有关 API 详细信息,请参阅《Amazon SDK for JavaScript API 参考》中的 DeletePolicy

Kotlin
适用于 Kotlin 的 SDK
注意

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

suspend fun deleteIAMPolicy(policyARNVal: String?) { val request = DeletePolicyRequest { policyArn = policyARNVal } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> iamClient.deletePolicy(request) println("Successfully deleted $policyARNVal") } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 DeletePolicy

PowerShell
适用于 PowerShell 的工具

示例 1:此示例删除了 ARN 为 arn:aws:iam::123456789012:policy/MySamplePolicy 的策略。必须先通过运行 Remove-IAMPolicyVersion 删除默认版本除外的所有版本,然后才能删除该策略。您还必须将该策略与所有 IAM 用户、组或角色分离。

Remove-IAMPolicy -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy

示例 2:此示例通过先删除所有非默认策略版本,将其与所有附加的 IAM 实体分离,最后删除策略本身来删除策略。第一行检索策略对象。第二行检索集合中未标记为默认的所有策略版本,然后删除集合中的每个策略。第三行检索该策略附加到的所有 IAM 用户、组和角色。第四行到第六行将该策略与每个附加的实体分离。最后一行使用此命令删除托管策略,以及剩余的默认版本。该示例在需要抑制确认提示的所有行中都包含 -Force 开关参数。

$pol = Get-IAMPolicy -PolicyArn arn:aws:iam::123456789012:policy/MySamplePolicy Get-IAMPolicyVersions -PolicyArn $pol.Arn | where {-not $_.IsDefaultVersion} | Remove-IAMPolicyVersion -PolicyArn $pol.Arn -force $attached = Get-IAMEntitiesForPolicy -PolicyArn $pol.Arn $attached.PolicyGroups | Unregister-IAMGroupPolicy -PolicyArn $pol.arn $attached.PolicyRoles | Unregister-IAMRolePolicy -PolicyArn $pol.arn $attached.PolicyUsers | Unregister-IAMUserPolicy -PolicyArn $pol.arn Remove-IAMPolicy $pol.Arn -Force
  • 有关 API 详细信息,请参阅《Amazon Tools for PowerShell Cmdlet 参考》中的 DeletePolicy

Python
SDK for Python (Boto3)
注意

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

def delete_policy(policy_arn): """ Deletes a policy. :param policy_arn: The ARN of the policy to delete. """ try: iam.Policy(policy_arn).delete() logger.info("Deleted policy %s.", policy_arn) except ClientError: logger.exception("Couldn't delete policy %s.", policy_arn) raise
  • 有关 API 详细信息,请参阅《Amazon SDK for Python (Boto3) API 参考》中的 DeletePolicy

Rust
适用于 Rust 的 SDK
注意

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

pub async fn delete_policy(client: &iamClient, policy: Policy) -> Result<(), iamError> { client .delete_policy() .policy_arn(policy.arn.unwrap()) .send() .await?; Ok(()) }
  • 有关 API 详细信息,请参阅《Amazon SDK for Rust API 参考》中的 DeletePolicy

Swift
适用于 Swift 的 SDK
注意

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

import AWSIAM import AWSS3 public func deletePolicy(policy: IAMClientTypes.Policy) async throws { let input = DeletePolicyInput( policyArn: policy.arn ) do { _ = try await iamClient.deletePolicy(input: input) } catch { print("ERROR: deletePolicy:", dump(error)) throw error } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Swift API 参考》中的 DeletePolicy

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