使用 Amazon 开发工具包从角色分离 IAM policy - Amazon Identity and Access Management
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

使用 Amazon 开发工具包从角色分离 IAM policy

以下代码示例显示如何从角色分离 IAM policy。

.NET
Amazon SDK for .NET
注意

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

/// <summary> /// Delete the user, and other resources created for this example. /// </summary> /// <param name="client">The initialized client object.</param> /// <param name=accessKeyId">The Id of the user's access key.</param>" /// <param name="userName">The user name of the user to delete.</param> /// <param name="policyName">The name of the policy to delete.</param> /// <param name="policyArn">The Amazon Resource Name ARN of the Policy to delete.</param> /// <param name="roleName">The name of the role that will be deleted.</param> public static async Task DeleteResourcesAsync( AmazonIdentityManagementServiceClient client, string accessKeyId, string userName, string policyArn, string roleName) { var detachPolicyResponse = await client.DetachRolePolicyAsync(new DetachRolePolicyRequest { PolicyArn = policyArn, RoleName = roleName, }); var delPolicyResponse = await client.DeletePolicyAsync(new DeletePolicyRequest { PolicyArn = policyArn, }); var delRoleResponse = await client.DeleteRoleAsync(new DeleteRoleRequest { RoleName = roleName, }); var delAccessKey = await client.DeleteAccessKeyAsync(new DeleteAccessKeyRequest { AccessKeyId = accessKeyId, UserName = userName, }); var delUserResponse = await client.DeleteUserAsync(new DeleteUserRequest { UserName = userName, }); }
  • 有关 API 详细信息,请参阅《Amazon SDK for .NET API 参考》中的 DetachRolePolicy

C++
SDK for C++
注意

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

Aws::IAM::IAMClient iam(clientConfig); Aws::IAM::Model::DetachRolePolicyRequest detachRequest; detachRequest.SetRoleName(roleName); detachRequest.SetPolicyArn(policyArn); auto detachOutcome = iam.DetachRolePolicy(detachRequest); if (!detachOutcome.IsSuccess()) { std::cerr << "Failed to detach policy " << policyArn << " from role " << roleName << ": " << detachOutcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully detached policy " << policyArn << " from role " << roleName << std::endl; } return detachOutcome.IsSuccess();
  • 有关 API 详细信息,请参阅《Amazon SDK for C++ API 参考》中的 DetachRolePolicy

Java
SDK for Java 2.x
注意

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

public static void detachPolicy(IamClient iam, String roleName, String policyArn ) { try { DetachRolePolicyRequest request = DetachRolePolicyRequest.builder() .roleName(roleName) .policyArn(policyArn) .build(); iam.detachRolePolicy(request); System.out.println("Successfully detached policy " + policyArn + " from role " + roleName); } catch (IamException e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 DetachRolePolicy

JavaScript
SDK for JavaScript V3
注意

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

创建客户端。

import { IAMClient } from "@aws-sdk/client-iam"; // Set the AWS Region. const REGION = "REGION"; // For example, "us-east-1". // Create an IAM service client object. const iamClient = new IAMClient({ region: REGION }); export { iamClient };

分离策略。

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import { ListAttachedRolePoliciesCommand, DetachRolePolicyCommand, } from "@aws-sdk/client-iam"; // Set the parameters. export const params = { RoleName: "ROLE_NAME" }; //ROLE_NAME export const run = async () => { try { const data = await iamClient.send( new ListAttachedRolePoliciesCommand(params) ); const myRolePolicies = data.AttachedPolicies; myRolePolicies.forEach(function (_val, index) { if (myRolePolicies[index].PolicyName === "AmazonDynamoDBFullAccess") { try { await iamClient.send( new DetachRolePolicyCommand(paramsRoleList) ); console.log("Policy detached from role successfully"); process.exit(); } catch (err) { console.log("Unable to detach policy from role", err); } } else { } }); return data; } catch (err) { console.log("User " + "USER_NAME" + " does not exist."); } }; run();
SDK for JavaScript V2
注意

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

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create the IAM service object var iam = new AWS.IAM({apiVersion: '2010-05-08'}); var paramsRoleList = { RoleName: process.argv[2] }; iam.listAttachedRolePolicies(paramsRoleList, function(err, data) { if (err) { console.log("Error", err); } else { var myRolePolicies = data.AttachedPolicies; myRolePolicies.forEach(function (val, index, array) { if (myRolePolicies[index].PolicyName === 'AmazonDynamoDBFullAccess') { var params = { PolicyArn: 'arn:aws:iam::aws:policy/AmazonDynamoDBFullAccess', RoleName: process.argv[2] }; iam.detachRolePolicy(params, function(err, data) { if (err) { console.log("Unable to detach policy from role", err); } else { console.log("Policy detached from role successfully"); process.exit(); } }); } }); } });
Kotlin
SDK for Kotlin
注意

这是适用于预览版中功能的预发行文档。本文档随时可能更改。

注意

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

suspend fun detachPolicy(roleNameVal: String, policyArnVal: String) { val request = DetachRolePolicyRequest { roleName = roleNameVal policyArn = policyArnVal } IamClient { region = "AWS_GLOBAL" }.use { iamClient -> iamClient.detachRolePolicy(request) println("Successfully detached policy $policyArnVal from role $roleNameVal") } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 DetachRolePolicy

Python
适用于 Python (Boto3) 的 SDK
注意

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

使用 Boto3 策略对象从角色分离策略。

def detach_from_role(role_name, policy_arn): """ Detaches a policy from a role. :param role_name: The name of the role. **Note** this is the name, not the ARN. :param policy_arn: The ARN of the policy. """ try: iam.Policy(policy_arn).detach_role(RoleName=role_name) logger.info("Detached policy %s from role %s.", policy_arn, role_name) except ClientError: logger.exception( "Couldn't detach policy %s from role %s.", policy_arn, role_name) raise

使用 Boto3 角色对象从角色分离策略。

def detach_policy(role_name, policy_arn): """ Detaches a policy from a role. :param role_name: The name of the role. **Note** this is the name, not the ARN. :param policy_arn: The ARN of the policy. """ try: iam.Role(role_name).detach_policy(PolicyArn=policy_arn) logger.info("Detached policy %s from role %s.", policy_arn, role_name) except ClientError: logger.exception( "Couldn't detach policy %s from role %s.", policy_arn, role_name) raise
  • 有关 API 详细信息,请参阅《Amazon SDK for Python(Boto3)API 参考》中的 DetachRolePolicy

Ruby
SDK for Ruby
注意

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

# Deletes a role. If the role has policies attached, they are detached and # deleted before the role is deleted. # # @param role [Aws::IAM::Role] The role to delete. def delete_role(role) role.attached_policies.each do |policy| name = policy.policy_name policy.detach_role(role_name: role.name) policy.delete puts("Deleted policy #{name}.") end name = role.name role.delete puts("Deleted role #{name}.") rescue Aws::Errors::ServiceError => e puts("Couldn't detach policies and delete role #{role.name}. Here's why:") puts("\t#{e.code}: #{e.message}") raise end
  • 有关 API 详细信息,请参阅《Amazon SDK for Ruby API 参考》中的 DetachRolePolicy

Rust
SDK for Rust
注意

本文档适用于预览版中的软件开发工具包。软件开发工具包可能随时发生变化,不应在生产环境中使用。

注意

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

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

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