Jonesie
Jonesie

Reputation: 7285

Cant remove role due to attached policy

Im dynamically creating a role with an attached policy.

var pr = new CreateRoleRequest
{
  RoleName = roleName,
  AssumeRolePolicyDocument = asspoly.ToJson(),
};
var resp = await _iamService.CreateRoleAsync(pr);

if (resp == null || resp.HttpStatusCode != HttpStatusCode.OK)
{
  throw new Exception($"Could not create role: {resp.HttpStatusCode}");
}

var gresp = await _iamService.AttachRolePolicyAsync(new AttachRolePolicyRequest { RoleName = roleName, PolicyArn = GetPolicyARN(MakeRolePolicyName(agentID)) });
if (gresp == null || gresp.HttpStatusCode != HttpStatusCode.OK)
{
  throw new Exception($"Could not attach policy to role: {resp.HttpStatusCode}");
}

This seems to work fine, but I also need to remove this role. To remove the role I need to detach the policies first.

var allpolys = await _iamService.ListRolePoliciesAsync(new ListRolePoliciesRequest { RoleName = roleName, MaxItems = 10 });
foreach (var poly in allpolys.PolicyNames)
{
  var polyArn = GetPolicyARN(poly);

  var dresp = await _iamService.DetachRolePolicyAsync(new DetachRolePolicyRequest { RoleName = roleName, PolicyArn = polyArn });
  if (dresp == null || dresp.HttpStatusCode != HttpStatusCode.OK)
  {
    throw new Exception($"Could not detach role policy: {poly}");
  }
}

Problem is, ListRolePolicies returns an empty list (from c# and cli) - and yet, the console shows the policy is indeed attached.

enter image description here

What am I missing here?

Upvotes: 2

Views: 303

Answers (1)

Mike Patrick
Mike Patrick

Reputation: 11006

The list-role-policies API returns inline policies. To query for attached policies, use the list-attached-role-policies API instead.

One could certainly argue that list-inline-role-policies would be a less confusing name for the former.


Note on AWS Docs and IAM terminology:

It wasn't obvious to me at first that "attached" and "managed" essentially mean the same thing. An attached policy is either "AWS managed", or "Customer managed". More details here.

Upvotes: 4

Related Questions