Last active
August 28, 2018 02:53
-
-
Save jtroberts83/18e992d383cd3b4d0f2514dcfd0c94c2 to your computer and use it in GitHub Desktop.
Multi-Account Lambda To Build CSV of All Customer Owned KMS Key ARNs. For use with Cloud Custodian policies
This file contains hidden or 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
import boto3 | |
from botocore.client import Config | |
import json | |
bucket = 'your-s3-bucket' | |
bucketregion = 'us-east-1' | |
KeyArnKey = 'MyKMSArns.csv' | |
AccountsS3Key = 'AWSAccountNumbers.csv' # A CSV containing all the AWS Accounts you want to run this script against. | |
roleNameToAssume = 'Cloud_Custodian_Role' | |
regionArray = ['us-east-1','us-west-1','eu-west-1','eu-central-1'] | |
def lambda_handler(event, context): | |
s3resource = boto3.resource('s3', config=Config(signature_version='s3v4'), region_name=bucketregion) | |
thisaccount = context.invoked_function_arn.split(":")[4] | |
RoleArn = 'arn:aws:iam::' + thisaccount + ':role/' + roleNameToAssume | |
s3resource.meta.client.download_file(bucket, AccountsS3Key, '/tmp/accounts.csv') | |
f = open('/tmp/accounts.csv', 'r') | |
accounts = f.read() | |
accounts = json.loads(accounts) | |
stsClient = boto3.client('sts') | |
KeyArnList = [] | |
for Account in accounts: | |
print(Account) | |
RoleArn = 'arn:aws:iam::' + Account + ':role/Cloud_Custodian_Role' | |
Creds = stsClient.assume_role( | |
RoleArn=RoleArn, | |
RoleSessionName='Gather-KMS-Keys', | |
DurationSeconds=900, | |
) | |
AccessKey = "" | |
AccessKey = Creds['Credentials']['AccessKeyId'] | |
SecretAccessKey = "" | |
SecretAccessKey = Creds['Credentials']['SecretAccessKey'] | |
SessionToken = "" | |
SessionToken = Creds['Credentials']['SessionToken'] | |
for region in regionArray: | |
KMSClient = boto3.client('kms', aws_access_key_id=AccessKey, aws_secret_access_key=SecretAccessKey, aws_session_token=SessionToken, region_name=region) | |
AllKMSKeys = KMSClient.list_keys() | |
for key in AllKMSKeys['Keys']: | |
KeyARN = key['KeyArn'] | |
KeyArnList.append(KeyARN) | |
locals3Client = boto3.client('s3', | |
config=Config(signature_version='s3v4'), | |
region_name="us-east-1" | |
) | |
KeyArnList = (json.dumps(KeyArnList)).replace("[","") | |
KeyArnList = KeyArnList.replace("]","") | |
KeyArnList = KeyArnList.replace(" ","") | |
response = locals3Client.put_object( | |
Body=KeyArnList, | |
Bucket=bucket, | |
Key=KeyArnKey, | |
ContentEncoding='ascii' | |
) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment