Home > Back-end >  Programmatically Convert all AWS inline policies to Managed Policies of current IAM Roles
Programmatically Convert all AWS inline policies to Managed Policies of current IAM Roles

Time:11-15

Currently I have several hundred AWS IAM Roles with inline policies.

I would like to somehow convert these inline policies to managed policies.

While AWS Documentation has a way to do this via the Console, this will be very time consuming.

Does anyone know of a way, or have a script to do this via BOTO or AWS CLI...or direct me to some method that I can do this programmatically?

Thanks in advance

CodePudding user response:

boto3 code will be like this.

In this code, inline policies that are embedded in the specified IAM user will be copied to customer managed policies.

Note delete part is commented out.

import json

import boto3

user_name = 'xxxxxxx'

client = boto3.client("iam")

response = client.list_user_policies(UserName=user_name)


for policy_name in response["PolicyNames"]:

    response = client.get_user_policy(UserName=user_name, PolicyName=policy_name)
    policy_document = json.dumps(response["PolicyDocument"])

    response = client.create_policy(
        PolicyName=policy_name, PolicyDocument=policy_document_json
    )

    # response = client.delete_user_policy(
    #     UserName=user_name,
    #     PolicyName=policy_name
    # )

Updated:

For IAM roles, changing User to Role, user to role (case sensitive) above code works.

Besides, if you execute for multiple roles, use list_roles to get role_name.

response=client.list_roles()

for i in response['Roles']:
    role_name = i['RoleName']
    # print(role_name)

CodePudding user response:

with @shimo snippet, the following works with added error handling and attaching the newly created managed policy to the IAM role:

import json
import boto3
from botocore.exceptions import ClientError

role_name = 'xxxxxxxx'
account_id = '123456789'

client = boto3.client("iam")
resource = boto3.resource('iam')

response = client.list_role_policies(RoleName=role_name)

for policy_name in response["PolicyNames"]:
    response = client.get_role_policy(RoleName=role_name, PolicyName=policy_name)
    policy_document = json.dumps(response["PolicyDocument"])
    print(policy_document)
    try:
        response = client.create_policy(
            PolicyName=policy_name, PolicyDocument=policy_document
        )
        print(policy_name   'Policy Created')
    except ClientError as error:
        if error.response['Error']['Code'] == 'EntityAlreadyExists':
            print(policy_name   ' policy already exists')
        else:
            print("Unexpected error: %s" % error)

    policy_arn = f'arn:aws:iam::{account_id}:policy/{policy_name}'
    role = resource.Role(role_name)
    role.attach_policy(PolicyArn=policy_arn)

    response = client.delete_role_policy(
        RoleName=role_name,
        PolicyName=policy_name
    )
  • Related