搭DeletePolicy配 AWS SDK或使用 CLI - AWS SDK 程式碼範例

AWS 文檔 AWS SDK示例 GitHub 回購中有更多SDK示例

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

DeletePolicy配 AWS SDK或使用 CLI

下列程式碼範例會示範如何使用DeletePolicy

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
AWS SDK for .NET
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

/// <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細資訊,請參閱AWS SDK for .NET API參考DeletePolicy中的。

Bash
AWS CLI 與 Bash 腳本
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

############################################################################### # 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細資訊,請參閱AWS CLI 指令參考DeletePolicy中的。

C++
SDK對於 C ++
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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細資訊,請參閱AWS SDK for C++ API參考DeletePolicy中的。

CLI
AWS CLI

若要刪除IAM策略

此範例會刪除原ARN則arn:aws:iam::123456789012:policy/MySamplePolicy

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

此命令不會產生輸出。

如需詳細資訊,請參閱《AWS IAM使用指南》IAM中的「策略和權限」。

  • 如需詳API細資訊,請參閱AWS CLI 指令參考DeletePolicy中的。

Go
SDK對於轉到 V2
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

// 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(policyArn string) error { _, err := wrapper.IamClient.DeletePolicy(context.TODO(), &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細資訊,請參閱AWS SDK for Go API參考DeletePolicy中的。

Java
SDK對於爪哇 2.x
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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細資訊,請參閱AWS SDK for Java 2.x API參考DeletePolicy中的。

JavaScript
SDK對於 JavaScript (3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

刪除策略。

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細資訊,請參閱AWS SDK for JavaScript API參考DeletePolicy中的。

Kotlin
SDK對於科特林
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

suspend fun deleteIAMPolicy(policyARNVal: String?) { val request = DeletePolicyRequest { policyArn = policyARNVal } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> iamClient.deletePolicy(request) println("Successfully deleted $policyARNVal") } }
  • 有API關詳細資訊,請參閱DeletePolicyAWS SDK的以取得 Kotlin API 的參考資料

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 switch 參數。

$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細資訊,請參閱AWS Tools for PowerShell 指令程DeletePolicy式參考中的。

Python
SDK對於 Python(肉毒桿菌 3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

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細資訊,請參閱DeletePolicyAWS SDK的〈〉以取得 Python (Boto3) API 參考資料。

Rust
SDK對於銹
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

pub async fn delete_policy(client: &iamClient, policy: Policy) -> Result<(), iamError> { client .delete_policy() .policy_arn(policy.arn.unwrap()) .send() .await?; Ok(()) }
  • 如需詳API細資訊,請參閱DeletePolicyAWS SDK的以取得 Rust API 參考

Swift
SDK為斯威夫特
注意

這是預覽版的售前版說明文件。SDK內容可能變動。

注意

還有更多關於 GitHub。尋找完整範例,並了解如何在AWS 設定和執行程式碼範例儲存庫

public func deletePolicy(policy: IAMClientTypes.Policy) async throws { let input = DeletePolicyInput( policyArn: policy.arn ) do { _ = try await iamClient.deletePolicy(input: input) } catch { throw error } }
  • 有API關詳細信息,請參閱DeletePolicyAWS SDK的以獲取 Swift API 參考