Gunakan DeletePolicy dengan AWS SDK atau CLI - AWS SDKContoh Kode

Ada lebih banyak AWS SDK contoh yang tersedia di GitHub repo SDKContoh AWS Dokumen.

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

Gunakan DeletePolicy dengan AWS SDK atau CLI

Contoh kode berikut menunjukkan cara menggunakanDeletePolicy.

Contoh tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Anda dapat melihat tindakan ini dalam konteks dalam contoh kode berikut:

.NET
AWS SDK for .NET
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

/// <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; }
  • Untuk API detailnya, lihat DeletePolicydi AWS SDK for .NET APIReferensi.

Bash
AWS CLI dengan skrip Bash
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

############################################################################### # 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 }
  • Untuk API detailnya, lihat DeletePolicydi Referensi AWS CLI Perintah.

C++
SDKuntuk C ++
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

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(); }
  • Untuk API detailnya, lihat DeletePolicydi AWS SDK for C++ APIReferensi.

CLI
AWS CLI

Untuk menghapus IAM kebijakan

Contoh ini menghapus kebijakan yang ARN adaarn:aws:iam::123456789012:policy/MySamplePolicy.

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

Perintah ini tidak menghasilkan output.

Untuk informasi selengkapnya, lihat Kebijakan dan izin IAM di Panduan AWS IAM Pengguna.

  • Untuk API detailnya, lihat DeletePolicydi Referensi AWS CLI Perintah.

Go
SDKuntuk Go V2
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

// 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 }
  • Untuk API detailnya, lihat DeletePolicydi AWS SDK for Go APIReferensi.

Java
SDKuntuk Java 2.x
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

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"); } }
  • Untuk API detailnya, lihat DeletePolicydi AWS SDK for Java 2.x APIReferensi.

JavaScript
SDKuntuk JavaScript (v3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

Hapus kebijakan.

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); };
  • Untuk API detailnya, lihat DeletePolicydi AWS SDK for JavaScript APIReferensi.

Kotlin
SDKuntuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

suspend fun deleteIAMPolicy(policyARNVal: String?) { val request = DeletePolicyRequest { policyArn = policyARNVal } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> iamClient.deletePolicy(request) println("Successfully deleted $policyARNVal") } }
PowerShell
Alat untuk PowerShell

Contoh 1: Contoh ini menghapus kebijakan yang ARN adaarn:aws:iam::123456789012:policy/MySamplePolicy. Sebelum Anda dapat menghapus kebijakan, Anda harus terlebih dahulu menghapus semua versi kecuali default dengan menjalankanRemove-IAMPolicyVersion. Anda juga harus melepaskan kebijakan dari IAM pengguna, grup, atau peran apa pun.

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

Contoh 2: Contoh ini menghapus kebijakan dengan terlebih dahulu menghapus semua versi kebijakan non-default, melepaskannya dari semua IAM entitas terlampir, dan akhirnya menghapus kebijakan itu sendiri. Baris pertama mengambil objek kebijakan. Baris kedua mengambil semua versi kebijakan yang tidak ditandai sebagai versi default ke dalam koleksi dan kemudian menghapus setiap kebijakan dalam koleksi. Baris ketiga mengambil semua IAM pengguna, grup, dan peran yang dilampirkan kebijakan. Baris empat hingga enam melepaskan kebijakan dari setiap entitas terlampir. Baris terakhir menggunakan perintah ini untuk menghapus kebijakan terkelola serta versi default yang tersisa. Contohnya termasuk parameter -Force sakelar pada baris apa pun yang membutuhkannya untuk menekan permintaan konfirmasi.

$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
  • Untuk API detailnya, lihat DeletePolicydi AWS Tools for PowerShell Referensi Cmdlet.

Python
SDKuntuk Python (Boto3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

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
Rust
SDKuntuk Rust
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

pub async fn delete_policy(client: &iamClient, policy: Policy) -> Result<(), iamError> { client .delete_policy() .policy_arn(policy.arn.unwrap()) .send() .await?; Ok(()) }
Swift
SDKuntuk Swift
catatan

Ini adalah dokumentasi prarilis untuk rilis SDK dalam pratinjau. Dokumentasi ini dapat berubah.

catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

public func deletePolicy(policy: IAMClientTypes.Policy) async throws { let input = DeletePolicyInput( policyArn: policy.arn ) do { _ = try await iamClient.deletePolicy(input: input) } catch { throw error } }