AWS SDK 또는 CLI와 함께 DetachRolePolicy 사용 - AWS Identity and Access Management

AWS SDK 또는 CLI와 함께 DetachRolePolicy 사용

다음 코드 예제는 DetachRolePolicy의 사용 방법을 보여 줍니다.

작업 예시는 대규모 프로그램에서 발췌한 코드이며 컨텍스트에 맞춰 실행해야 합니다. 다음 코드 예제에서는 컨텍스트 내에서 이 작업을 확인할 수 있습니다.

.NET
AWS SDK for .NET
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

/// <summary> /// Detach an IAM policy from an IAM role. /// </summary> /// <param name="policyArn">The Amazon Resource Name (ARN) of the IAM policy.</param> /// <param name="roleName">The name of the IAM role.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> DetachRolePolicyAsync(string policyArn, string roleName) { var response = await _IAMService.DetachRolePolicyAsync(new DetachRolePolicyRequest { PolicyArn = policyArn, RoleName = roleName, }); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; }
  • API 세부 정보는 AWS SDK for .NET API 참조DetachRolePolicy를 참조하십시오.

Bash
Bash 스크립트와 함께 AWS CLI사용
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################### # function iam_detach_role_policy # # This function detaches an IAM policy to a tole. # # Parameters: # -n role_name -- The name of the IAM role. # -p policy_ARN -- The IAM policy document ARN.. # # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################### function iam_detach_role_policy() { local role_name policy_arn response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function iam_detach_role_policy" echo "Detaches an AWS Identity and Access Management (IAM) policy to an IAM role." echo " -n role_name The name of the IAM role." echo " -p policy_ARN -- The IAM policy document ARN." echo "" } # Retrieve the calling parameters. while getopts "n:p:h" option; do case "${option}" in n) role_name="${OPTARG}" ;; p) policy_arn="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$role_name" ]]; then errecho "ERROR: You must provide a role name with the -n parameter." usage return 1 fi if [[ -z "$policy_arn" ]]; then errecho "ERROR: You must provide a policy ARN with the -p parameter." usage return 1 fi response=$(aws iam detach-role-policy \ --role-name "$role_name" \ --policy-arn "$policy_arn") local error_code=${?} if [[ $error_code -ne 0 ]]; then aws_cli_error_log $error_code errecho "ERROR: AWS reports detach-role-policy operation failed.\n$response" return 1 fi echo "$response" return 0 }
  • API 세부 정보는 AWS CLI 명령 참조DetachRolePolicy를 참조하십시오.

C++
SDK for C++
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

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 세부 정보는 AWS SDK for C++ API 참조DetachRolePolicy를 참조하세요.

CLI
AWS CLI

역할에서 정책 분리

이 예제에서는 FedTesterRole을 호출한 역할에서 ARN이 arn:aws:iam::123456789012:policy/FederatedTesterAccessPolicy인 관리형 정책을 제거합니다.

aws iam detach-role-policy \ --role-name FedTesterRole \ --policy-arn arn:aws:iam::123456789012:policy/FederatedTesterAccessPolicy

이 명령은 출력을 생성하지 않습니다.

자세한 내용은 AWS IAM 사용 설명서의 역할 변경을 참조하세요.

  • API 세부 정보는 AWS CLI 명령 참조DetachRolePolicy를 참조하세요.

Go
SDK for Go V2
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// RoleWrapper encapsulates AWS Identity and Access Management (IAM) role actions // used in the examples. // It contains an IAM service client that is used to perform role actions. type RoleWrapper struct { IamClient *iam.Client } // DetachRolePolicy detaches a policy from a role. func (wrapper RoleWrapper) DetachRolePolicy(roleName string, policyArn string) error { _, err := wrapper.IamClient.DetachRolePolicy(context.TODO(), &iam.DetachRolePolicyInput{ PolicyArn: aws.String(policyArn), RoleName: aws.String(roleName), }) if err != nil { log.Printf("Couldn't detach policy from role %v. Here's why: %v\n", roleName, err) } return err }
  • API 세부 정보는 AWS SDK for Go API 참조DetachRolePolicy를 참조하십시오.

Java
SDK for Java 2.x
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

import software.amazon.awssdk.services.iam.model.DetachRolePolicyRequest; 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 DetachRolePolicy { public static void main(String[] args) { final String usage = """ Usage: <roleName> <policyArn>\s Where: roleName - A role name that you can obtain from the AWS Management Console.\s policyArn - A policy ARN that you can obtain from the AWS Management Console.\s """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String roleName = args[0]; String policyArn = args[1]; Region region = Region.AWS_GLOBAL; IamClient iam = IamClient.builder() .region(region) .build(); detachPolicy(iam, roleName, policyArn); System.out.println("Done"); iam.close(); } 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 세부 정보는 AWS SDK for Java 2.x API 참조DetachRolePolicy를 참조하십시오.

JavaScript
SDK for JavaScript (v3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

태그를 분리합니다.

import { DetachRolePolicyCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} policyArn * @param {string} roleName */ export const detachRolePolicy = (policyArn, roleName) => { const command = new DetachRolePolicyCommand({ PolicyArn: policyArn, RoleName: roleName, }); return client.send(command); };
SDK for JavaScript (v2)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

// 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에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

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 세부 정보는 AWS SDK for Kotlin API 참조DetachRolePolicy를 참조하십시오.

PowerShell
PowerShell용 도구

예제 1: 이 예제는 ARN이 arn:aws:iam::123456789012:policy/FederatedTesterAccessPolicy인 관리형 그룹 정책을 FedTesterRole라는 역할에서 분리합니다.

Unregister-IAMRolePolicy -RoleName FedTesterRole -PolicyArn arn:aws:iam::123456789012:policy/FederatedTesterAccessPolicy

예제 2: 이 예제는 FedTesterRole라는 역할에 연결된 모든 관리형 정책을 찾아 역할에서 분리합니다.

Get-IAMAttachedRolePolicyList -RoleName FedTesterRole | Unregister-IAMRolePolicy -Rolename FedTesterRole
  • API 세부 정보는 AWS Tools for PowerShell Cmdlet 참조의 DetachRolePolicy를 참조하세요.

Python
SDK for Python (Boto3)
참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

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 세부 정보는 AWSSDK for Python (Boto3) API 참조DetachRolePolicy를 참조하십시오.

Ruby
SDK for Ruby
참고

GitHub에 더 많은 내용이 있습니다. AWS코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

이 예시 모듈은 역할 정책을 나열, 생성, 연결 및 분리합니다.

# 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 세부 정보는 AWS SDK for Ruby API 참조DetachRolePolicy를 참조하세요.

Rust
SDK for Rust
참고

GitHub에 더 많은 내용이 있습니다. AWS코드 예시 리포지토리에서 전체 예시를 찾고 설정 및 실행하는 방법을 배워보세요.

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 세부 정보는 AWS SDK for Rust API 참조DetachRolePolicy을 참조하십시오.

Swift
SDK for Swift
참고

이 사전 릴리스 설명서는 평가판 버전 SDK에 관한 것입니다. 내용은 변경될 수 있습니다.

참고

GitHub에 더 많은 내용이 있습니다. AWS 코드 예제 리포지토리에서 전체 예제를 찾고 설정 및 실행하는 방법을 배워보세요.

public func detachRolePolicy(policy: IAMClientTypes.Policy, role: IAMClientTypes.Role) async throws { let input = DetachRolePolicyInput( policyArn: policy.arn, roleName: role.roleName ) do { _ = try await iamClient.detachRolePolicy(input: input) } catch { throw error } }
  • API 세부 정보는 Swift용 AWS SDK API 참조DetachRolePolicy를 참조하세요.

AWS SDK 개발자 가이드 및 코드 예시의 전체 목록은 AWS SDK와 함께 이 서비스 사용 단원을 참조하세요. 이 주제에는 시작하기에 대한 정보와 이전 SDK 버전에 대한 세부 정보도 포함되어 있습니다.