Skip to content

Instantly share code, notes, and snippets.

@tom-butler
Created June 20, 2017 04:49
Show Gist options
  • Save tom-butler/aadb50a94e9eaa121ce525e223ddbe64 to your computer and use it in GitHub Desktop.
Save tom-butler/aadb50a94e9eaa121ce525e223ddbe64 to your computer and use it in GitHub Desktop.
Boto3: Add All Org Accounts To IAM Policy
#!/usr/bin/env python3
import boto3
import json
central_logging = '<insert your central logging account id here>'
# Variables for the grafana monitoring server
role_name = 'monitoring_prodcloudwatch_access_role'
policy_arn = 'arn:aws:iam::<insert your central logging account id here>:policy/monitor-assumerole'
role_policy = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AssumeRoleInstanceProfile",
"Effect": "Allow",
"Action": [
"sts:AssumeRole"
],
"Resource": []
}
]
}
def get_account_list():
"""
Get list of accounts
return: List of account Ids
"""
account_list=[]
# Get a list of accounts in our org
client = boto3.client('organizations')
response = client.list_accounts(
MaxResults=10
)
# We expect there to be at least 10 accounts
while 'NextToken' in response:
for account in response['Accounts']:
account_list.append(account['Id'])
response = client.list_accounts(
MaxResults=10,
NextToken=response['NextToken']
)
return account_list
def update_monitoring_iam_policy(account_list):
"""
Update the IAM Policy to have all account in your organisation
:param account_list: A list of Account Ids
"""
# Switch roles to new account
sts_client = boto3.client('sts')
assumedRoleObject = sts_client.assume_role(
RoleArn="arn:aws:iam::" + central_logging + ":role/OrganizationAccountAccessRole",
RoleSessionName="AssumeRoleSession1"
)
credentials = assumedRoleObject['Credentials']
#Create an iam client in the new account
iam_client = boto3.client(
'iam',
aws_access_key_id = credentials['AccessKeyId'],
aws_secret_access_key = credentials['SecretAccessKey'],
aws_session_token = credentials['SessionToken']
)
# Insert the account ids into the role policy
for Id in account_list:
arn = 'arn:aws:iam::' + Id + ':role/central-logging-monitor'
role_policy['Statement'][0]['Resource'].append(arn)
# Convert the policy to a JSON string
policy_string = json.dumps(role_policy)
# Put the new role_policy
response = iam_client.create_policy_version(
PolicyArn=policy_arn,
PolicyDocument=policy_string,
SetAsDefault=True
)
# Delete any old policy versions, versions have a default max of 5,
# We want to clean it up to ensure we don't hit this limit in the future
response = iam_client.list_policy_versions(
PolicyArn=policy_arn,
)
for version in response['Versions']:
if version['IsDefaultVersion'] is False:
delete = iam_client.delete_policy_version(
PolicyArn=policy_arn,
VersionId=version['VersionId']
)
print('Updated central monitoring policy to view new org accounts')
def main():
"""
Update monitoring IAM policy
"""
account_list = get_account_list()
update_monitoring_iam_policy(account_list)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment