Created
April 22, 2019 12:03
-
-
Save restump/516259a5ca6eee682a8cecd6e58dc554 to your computer and use it in GitHub Desktop.
Delete role on all accounts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import boto3 | |
import pprint | |
import argparse | |
import csv | |
from multiprocessing import Process | |
from botocore.exceptions import ProfileNotFound, ClientError | |
parser = argparse.ArgumentParser(description="Parallel, multi-account execution") | |
parser.add_argument('--role', | |
type=str ) | |
parser.add_argument('--assume_role', | |
type=str, | |
default="CloudCoreAdmin" ) | |
parser.add_argument('--organization_owner_id', | |
type=str, help="Organization OwnerId", | |
default="1234567890" ) | |
pargs = parser.parse_args() | |
def getSessionWithAssumeRole(OwnerId=None,RoleName=None): | |
arn = "arn:aws:iam::{0}:role/{1}".format(OwnerId,RoleName) | |
response = boto3.client('sts').assume_role(RoleArn=arn, RoleSessionName="mySession") | |
session = boto3.Session( | |
aws_access_key_id = response['Credentials']['AccessKeyId'], | |
aws_secret_access_key = response['Credentials']['SecretAccessKey'], | |
aws_session_token = response['Credentials']['SessionToken'] ) | |
return session | |
def getAccountList(OwnerId=None,RoleName=None): | |
session = getSessionWithAssumeRole(OwnerId=OwnerId,RoleName=RoleName) | |
accounts = [] | |
response = session.client('organizations').list_accounts() | |
while True: | |
for item in response['Accounts']: | |
if item['Status'] == 'ACTIVE': | |
accounts.append(item['Id']) | |
if 'NextToken' not in response: | |
break | |
response = session.client('organizations').list_accounts(NextToken=response['NextToken']) | |
return accounts | |
def getItemsWithMaxItems(Session=None,MethodName=None,ClientName=None,ItemListKey=None,**kwargs): | |
function = getattr(Session.client(ClientName), MethodName) | |
items = [] | |
response = function(**kwargs) | |
while True: | |
for item in response[ItemListKey]: | |
items.append(item) | |
if response['IsTruncated'] == False: | |
break | |
response = function(Marker=response['Marker'],**kwargs) | |
return items | |
def delete_role(Session=None,OwnerId=None,RoleName=None): | |
try: | |
response = Session.client('iam').get_role(RoleName=RoleName) | |
except: | |
print "[{1}] role {0} not found".format(RoleName, OwnerId) | |
return | |
attached_policies = getItemsWithMaxItems(Session, | |
"list_attached_role_policies", | |
"iam", | |
"AttachedPolicies", | |
**{"RoleName": RoleName} ) | |
inline_policies = getItemsWithMaxItems(Session, | |
"list_role_policies", | |
"iam", | |
"PolicyNames", | |
**{"RoleName": RoleName} ) | |
for policy in attached_policies: | |
print "[{2}] detaching policy {0} on role {1}...".format(policy['PolicyName'],RoleName,OwnerId) | |
response = Session.client('iam').detach_role_policy(RoleName=RoleName,PolicyArn=policy['PolicyArn']) | |
print "[{1}] deleting role {0}...".format(RoleName,OwnerId) | |
for policy in inline_policies: | |
print "[{2}] detaching inline policy {0} on role {1}...".format(policy,RoleName,OwnerId) | |
response = Session.client('iam').delete_role_policy(RoleName=RoleName,PolicyName=policy) | |
print "[{1}] deleting role {0}...".format(RoleName,OwnerId) | |
Session.client('iam').delete_role(RoleName=RoleName) | |
if __name__ == '__main__': | |
accounts = getAccountList(OwnerId=pargs.organization_owner_id,RoleName=pargs.assume_role) | |
procs = [] | |
for account in accounts: | |
session = getSessionWithAssumeRole(OwnerId=account,RoleName=pargs.assume_role) | |
proc = Process(target=delete_role, args=(session, account, pargs.role,)) | |
procs.append(proc) | |
proc.start() | |
for proc in procs: | |
proc.join() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment