List policies attached to an IAM role using an AWS SDK - AWS SDK Code Examples

There are more AWS SDK examples available in the AWS Doc SDK Examples GitHub repo.

List policies attached to an IAM role using an AWS SDK

The following code examples show how to list policies attached to an IAM role.

.NET
AWS SDK for .NET
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

using System; using Amazon.IdentityManagement; using Amazon.IdentityManagement.Model; var client = new AmazonIdentityManagementServiceClient(); var request = new ListAttachedRolePoliciesRequest { MaxItems = 10, RoleName = "testAssumeRole", }; var response = await client.ListAttachedRolePoliciesAsync(request); do { response.AttachedPolicies.ForEach(policy => { Console.WriteLine($"{policy.PolicyName} with ARN: {policy.PolicyArn}"); }); if (response.IsTruncated) { request.Marker = response.Marker; response = await client.ListAttachedRolePoliciesAsync(request); } } while (response.IsTruncated);
Go
SDK for Go V2
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

// 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 } // ListAttachedRolePolicies lists the policies that are attached to the specified role. func (wrapper RoleWrapper) ListAttachedRolePolicies(roleName string) ([]types.AttachedPolicy, error) { var policies []types.AttachedPolicy result, err := wrapper.IamClient.ListAttachedRolePolicies(context.TODO(), &iam.ListAttachedRolePoliciesInput{ RoleName: aws.String(roleName), }) if err != nil { log.Printf("Couldn't list attached policies for role %v. Here's why: %v\n", roleName, err) } else { policies = result.AttachedPolicies } return policies, err }
JavaScript
SDK for JavaScript V3
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

Create the client.

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 };

List the policies that are attached to a role.

// Import required AWS SDK clients and commands for Node.js. import { iamClient } from "./libs/iamClient.js"; import {ListAttachedRolePoliciesCommand} from "@aws-sdk/client-iam"; // Set the parameters. export const params = { RoleName: 'ROLE_NAME' /* required */ }; export const run = async () => { try { const data = await iamClient.send(new ListAttachedRolePoliciesCommand(params)); console.log("Success", data.AttachedPolicies); } catch (err) { console.log("Error", err); } } run();
PHP
SDK for PHP
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

$uuid = uniqid(); $service = new IamService(); public function listAttachedRolePolicies($roleName, $pathPrefix = "", $marker = "", $maxItems = 0) { $listAttachRolePoliciesArguments = ['RoleName' => $roleName]; if ($pathPrefix) { $listAttachRolePoliciesArguments['PathPrefix'] = $pathPrefix; } if ($marker) { $listAttachRolePoliciesArguments['Marker'] = $marker; } if ($maxItems) { $listAttachRolePoliciesArguments['MaxItems'] = $maxItems; } return $this->iamClient->listAttachedRolePolicies($listAttachRolePoliciesArguments); }
Python
SDK for Python (Boto3)
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

def list_attached_policies(role_name): """ Lists policies attached to a role. :param role_name: The name of the role to query. """ try: role = iam.Role(role_name) for policy in role.attached_policies.all(): logger.info("Got policy %s.", policy.arn) except ClientError: logger.exception("Couldn't list attached policies for %s.", role_name) raise
Ruby
SDK for Ruby
Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

# 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
Rust
SDK for Rust
Note

This documentation is for an SDK in preview release. The SDK is subject to change and should not be used in production.

Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

pub async fn list_attached_role_policies( client: &iamClient, role_name: String, path_prefix: Option<String>, marker: Option<String>, max_items: Option<i32>, ) -> Result<ListAttachedRolePoliciesOutput, SdkError<ListAttachedRolePoliciesError>> { let response = client .list_attached_role_policies() .role_name(role_name) .set_path_prefix(path_prefix) .set_marker(marker) .set_max_items(max_items) .send() .await?; Ok(response) }
Swift
SDK for Swift
Note

This is prerelease documentation for an SDK in preview release. It is subject to change.

Note

There's more on GitHub. Find the complete example and learn how to set up and run in the AWS Code Examples Repository.

/// Returns a list of AWS Identity and Access Management (IAM) policies /// that are attached to the role. /// /// - Parameter role: The IAM role to return the policy list for. /// /// - Returns: An array of `IamClientTypes.AttachedPolicy` objects /// describing each managed policy that's attached to the role. public func listAttachedRolePolicies(role: String) async throws -> [IamClientTypes.AttachedPolicy] { var policyList: [IamClientTypes.AttachedPolicy] = [] var marker: String? = nil var isTruncated: Bool repeat { let input = ListAttachedRolePoliciesInput( marker: marker, roleName: role ) let output = try await client.listAttachedRolePolicies(input: input) guard let attachedPolicies = output.attachedPolicies else { return policyList } for attachedPolicy in attachedPolicies { policyList.append(attachedPolicy) } marker = output.marker isTruncated = output.isTruncated } while isTruncated == true return policyList }