Skip to content

Instantly share code, notes, and snippets.

@raajheshkannaa
Created February 17, 2023 22:35
Show Gist options
  • Save raajheshkannaa/0f53c32fb4f4ed60b2f3dec91f1a76ff to your computer and use it in GitHub Desktop.
Save raajheshkannaa/0f53c32fb4f4ed60b2f3dec91f1a76ff to your computer and use it in GitHub Desktop.
Use boto3 to automatically update `billing` and `security` alternate contacts for all AWS Accounts in an AWS Organization
"""
Automatically fetch all member accounts in an AWS Organization and
update `Billing` and `Security` Contact.
"""
import boto3
from botocore.exceptions import ClientError
def get_org_accounts(session):
org_client = session.client('organizations')
results = []
messages = []
paginator = org_client.get_paginator('list_accounts')
response_iterator = paginator.paginate()
for response in response_iterator:
results = results + response['Accounts']
for index in results:
messages = messages + (index['Id']).split()
messages.remove('123456789111') # Remove the Organization Master Account Id
return messages
def assume_role(session, aws_account_number, role_name):
resp = session.client('sts').assume_role(
RoleArn='arn:aws:iam::{}:role/{}'.format(aws_account_number,role_name),
RoleSessionName='UpdateAccountMetadata')
# Storing STS credentials
creds = boto3.Session(
aws_access_key_id = resp['Credentials']['AccessKeyId'],
aws_secret_access_key = resp['Credentials']['SecretAccessKey'],
aws_session_token = resp['Credentials']['SessionToken']
)
print("Assumed session for {}.".format(
aws_account_number
))
return creds
if __name__ == '__main__':
accounts = get_org_accounts(boto3.Session())
for account in accounts:
# Below role name could be changed to another role which is already setup such as `OrganizationAccountAccessRole`
session = assume_role(boto3.Session(), account, 'AWSControlTowerExecution') # Consider using any role which is setup in all accounts and is trusted by the Org Master account
client = session.client('account')
try:
# response = client.get_alternate_contact(
# AlternateContactType='BILLING'
# )['AlternateContact']
# print(response)
billing_contact_response = client.put_alternate_contact(
AlternateContactType='BILLING',
EmailAddress='[email protected]',
Name='Accounts Payable',
PhoneNumber='+1 666-444-2222',
Title='Billing Account Example'
)
security_contact_response = client.put_alternate_contact(
AlternateContactType='SECURITY',
EmailAddress='[email protected]',
Name='Example Admin',
PhoneNumber='+1 666-444-2222',
Title='Example Admin'
)
print("Success")
except ClientError as e:
print(e)
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment