def lambda_handler(event, context): print('message received on function trigger: %s' % event) if octopus.validate_event_data(event): dynamodb_client = boto3.client('dynamodb') orgs_client = octopus.assume_role(event['payer_id'], 'octopus_svc', 'listlinkedaccounts', 'organizations', 'us-east-1') account = orgs_client.describe_account(AccountId=event['Id']) insert = dynamodb_client.put_item( TableName=environ['dynamoDbTable'], Item={ 'Id': { 'S': account['Account']['Id'] }, 'Name': { 'S': account['Account']['Name'] }, 'Email': { 'S': account['Account']['Email'] }, 'Arn': { 'S': account['Account']['Arn'] }, 'Status': { 'S': account['Account']['Status'] }, 'JoinedMethod': { 'S': account['Account']['JoinedMethod'] }, }, ReturnConsumedCapacity='TOTAL') print(insert) return insert
def lambda_handler(event, context): print('message received on function trigger: %s' % event) if octopus.validate_event_data(event): iam_client = octopus.assume_role(event['Id'], event['role_name'], event['session_name'], 'iam', 'us-east-1') key_pair = iam_client.create_access_key(UserName=event['username']) print(key_pair['ResponseMetadata']) return key_pair
def lambda_handler(event, context): print('message received on function trigger: %s' % event) if octopus.validate_event_data(event): iam_client = octopus.assume_role(event['Id'], event['role_name'], event['session_name'], 'iam', 'us-east-1') delete_key_pair = iam_client.delete_access_key( UserName=event['username'], AccessKeyId=event['access_key']) print(delete_key_pair)
def lambda_handler(event, context): print('message received on function trigger: %s' % event) if octopus.validate_event_data(event): iam_client = octopus.assume_role(event['Id'], event['role_name'], event['session_name'], 'iam', 'us-east-1') console_access = iam_client.create_login_profile( UserName=event['username'], Password=event['password'], PasswordResetRequired=True) print(console_access)
def lambda_handler(event, context): print('message received on function trigger: %s' % event) lambda_client = boto3.client('lambda') get_accounts = lambda_client.invoke(FunctionName='getLinkedAccounts', InvocationType='RequestResponse', LogType='Tail', Payload=dumps({ "payer_id": event['payer_id'], "role_name": environ['role_payer'] })) print(get_accounts) print() accounts = loads(get_accounts['Payload'].read().decode('utf-8')) print('Accounts type: %s' % type(accounts)) print('A total of %s Accounts retrived: %s' % (len(accounts), accounts)) print() active_accounts = 0 suspended_accounts = 0 for account in accounts: print('Account type: %s' % type(account)) print('Account: %s' % account) if account['Status'] == 'ACTIVE': active_accounts += 1 try: iam_client = assume_role(account['Id'], environ['role_name'], 'manageIamResources', 'iam', 'us-east-1') except Exception as err: print("Error: %s " % err) iam_client = None if iam_client != None: roles_list = iam_client.list_roles() found = 0 print(roles_list['Roles']) for role in roles_list['Roles']: if role['RoleName'] == 'cloudynRole': print() print() print('cloudyn role found in account %s -- %s -- %s' % (account['Id'], account['Email'], role['Arn'])) print() print() found += 1 if found == 0: print('Cloudyn role not found in list yet: %s' % roles_list['Roles']) print('Creating role in account %s...' % account['Id']) new_role = iam_client.create_role( RoleName='cloudynRole', AssumeRolePolicyDocument=assume_role_policy_document, Description= 'Role used by Cloudyn billing service. Responsibility of business ops team' ) if 'Role' in new_role and new_role['ResponseMetadata'][ 'HTTPStatusCode'] == 200: print('New role created: %s' % new_role['Role']['Arn']) print('Attaching readonly policy...') attach_policy = iam_client.attach_role_policy( RoleName='cloudynRole', PolicyArn='arn:aws:iam::aws:policy/ReadOnlyAccess') print(attach_policy) else: print('Role could not be created... %s' % new_role) else: print('Account %s - %s not Active! Current Status is %s ...' % (account['Id'], account['Email'], account['Status'])) if account['Status'] == 'SUSPENDED': suspended_accounts += 1 print('Accounts Status: %s ACTIVE and %s SUSPENDED' % (active_accounts, suspended_accounts))
def lambda_handler(event, context): accounts=event['accounts'] for account in accounts print(account) # Assumes linked account role with IAM service print('Setting up IAM Service...') try: iam_client = octopus.assume_role( account['Id'], 'octopusmngt', 'createrole', 'iam', 'us-east-1') print('IAM Service assumed...') except Exception as e: print('Could not assume IAM on account %s. Error: %s' % ( account['Id'], str(e)) ) continue # List users on account account['Users'] = list_resources( iam_client, 'Users', 'list_users' ) # Iterates through users listing policies print('Analysing users one by one...') for user in account['Users']: print(user) user['Policies'] = [] try: inline_user_policies = list_resources( iam_client, 'PolicyNames', 'list_user_policies', UserName=role['UserName'] ) except Exception as e: print('Could not list inline policies for user %s: %s' % ( str(user['UserName']), str(e)) ) for policy in inline_user_policies: try: inline_doc = iam_client.get_user_policy( UserName=role['UserName'], PolicyName=policy ) role['Policies'].extend( { 'PolicyName':policy, 'PolicyDocument':inline_doc['PolicyDocument'] } ) except Exception as e: print('Could not retrieve details for policy %s: %s' % ( str(policy), str(e)) ) try: attached_user_policies = list_resources( iam_client, 'AttachedPolicies', 'list_attached_user_policies', UserName=role['UserName'] ) except Exception as e: print('Could not list attached policies for user %s: %s ' % ( str(user['UserName']), str(e)) ) for i in attached_user_polices: try: policy_details = list_resources( iam_client, 'Versions', 'list_policy_versions', PolicyArn=i['PolicyArn'] ) except Exception as e: print('Could not list version of policies for user %s: %s' % ( str(user['UserName']), str(e)) ) try: for sub in policy_details: if sub['IsDefaultVersion']: document = iam_client.get_policy_version( PolicyArn=i['PolicyArn'], VersionId=sub['VersionId'] ) role['Policies'].append( { 'PolicyName':i['PolicyName'], 'PolicyDocument':document['PolicyVersion']['Document'], 'DocumentVersion':sub['VersionId'] } ) except Exception as e: print('Could not get document policy for user %s: %s' % ( str(user['UserName']), str(e)) ) try: user['AccessKeys'] = list_resources( iam_client, 'AccessKeyMetadata', 'list_access_keys', UserName=user['UserName'] ) except Exception as e: print('Could not list access_keys for user %s: %s' % ( user['UserName'], str(e)) ) try: user['Groups'] = list_resources( iam_client, 'Groups', 'list_groups_for_user', Username=user['UserName'] ) except Exception as e: print('Could not list groups for user %s: %s' % ( user['UserName'], str(e)) ) print(accounts)
def lambda_handler(event, context): print('message received on function trigger: %s' % event) lambda_client = boto3.client('lambda') get_accounts = lambda_client.invoke(FunctionName='getLinkedAccounts', InvocationType='RequestResponse', LogType='Tail', Payload=dumps({ "payer_id": event['payer_id'], "role_name": environ['role_payer'] })) print(get_accounts) print() accounts = loads(get_accounts['Payload'].read().decode('utf-8')) print('Accounts type: %s' % type(accounts)) print('A total of %s Accounts retrived: %s' % (len(accounts), accounts)) print() active_accounts = 0 suspended_accounts = 0 for account in accounts: print('Account type: %s' % type(account)) print('Account: %s' % account) if account['Status'] == 'ACTIVE': active_accounts += 1 try: iam_client = assume_role(account['Id'], environ['role_name'], 'manageIamResources', 'iam', 'us-east-1') except Exception as err: print("Error: %s " % err) iam_client = None if iam_client != None: roles_list = iam_client.list_roles() found = 0 print(roles_list['Roles']) for role in roles_list['Roles']: if role['RoleName'] == 'cloudability': print() print() print( 'cloudability_monitor role found in account %s -- %s -- %s' % (account['Id'], account['Email'], role['Arn'])) print() print() found += 1 list_role_policies = iam_client.list_attached_role_policies( RoleName='cloudability') print(list_role_policies) for policy in list_role_policies['AttachedPolicies']: print(policy) detach = iam_client.detach_role_policy( RoleName='cloudability', PolicyArn=policy['PolicyArn']) delete_role = iam_client.delete_role( RoleName='cloudability') print( 'cloudability_monitor role found and deleted: %s' % delete_role) if found == 0: print( 'cloudability_monitor role not found in list yet: %s' % roles_list['Roles']) else: print('Account %s - %s not Active! Current Status is %s ...' % (account['Id'], account['Email'], account['Status'])) if account['Status'] == 'SUSPENDED': suspended_accounts += 1 print('Accounts Status: %s ACTIVE and %s SUSPENDED' % (active_accounts, suspended_accounts))
def lambda_handler(event, context): print('message received on function trigger: %s' % event) if octopus.validate_event_data(event): var_list = [{'payerid':event['payer_id']}] lambda_client = boto3.client('lambda') s3_client = boto3.client('s3') iam_client = octopus.assume_role( event['payer_id'], 'octopus_svc', 'createroletonewaccount', 'iam', 'us-east-1') set_env = octopus.set_env_for_tf( event['Environment'], environ['terraform_config_bucket'], octopus.get_tf_files( event['Environment'], environ['table_name']), var_list) if set_env == True: # tf_environment = octopus.setup_terraform( # environ['backend_bucket'], # environ['dynamodb_table'], # environ['kms_key_id'], # event['Environment'], # environ['terraform_config_bucket']) # if tf_environment == True: if 1 == 1: print('New account %s created' % (event['Name'])) print('Searching terraform state file for new accountId..') tf_state = s3_client.get_object( Bucket=environ['backend_bucket'], Key='workspace/%s/backend' % (event['Environment']) ) print('Answer from get_object command: %s' % tf_state) content = loads(tf_state['Body'].read().decode('utf-8')) print('State File: %s' % content) account_id = content['modules'][0]\ ['resources']['aws_organizations_account.%s' \ % event['Name']]['primary']['id'] print('Account ID for the new account is: %s' % account_id) print('Saving data about new account on database...') insert_account = lambda_client.invoke( FunctionName=environ['insert_account_function'], InvocationType='RequestResponse', LogType='Tail', Payload=dumps({"Id":account_id,"payer_id":event['payer_id']}) ) print('''Answer from LambdaFunction to Insert Account: %s \ ''' % insert_account['Payload'].read()) print('Creating Cross Account Role for Octopus...') print('Creating temporary key...') create_key = iam_client.create_access_key( UserName='******' ) print('''Create Key Status: %s \ ''' % create_key['ResponseMetadata']) var_list = [ {"accesskey":create_key['AccessKey']['AccessKeyId']}, {"secretkey":create_key['AccessKey']['SecretAccessKey']}, {"id":account_id}, {"mngt_account_id":environ['mngt_account_id']}] set_env = octopus.set_env_for_tf( event['Name'], environ['terraform_config_bucket'], octopus.get_tf_files( 'new-account-conf', environ['table_name']), var_list) if set_env == True: octopus.init_terraform( environ['backend_bucket'], environ['dynamodb_table'], environ['kms_key_id'], event['Name'], environ['terraform_config_bucket']) print('Creating workspace for the new account...') print(popen('''cd /tmp/%s && /tmp/terraform workspace new %s \ ''' % (event['Name'],event['Name'])).read()) print('Workspace created...') tf_environment = octopus.setup_terraform( environ['backend_bucket'], environ['dynamodb_table'], environ['kms_key_id'], event['Name'], environ['terraform_config_bucket']) iam_client.delete_access_key( UserName='******', AccessKeyId=create_key['AccessKey']['AccessKeyId'] ) popen(' rm -rf /tmp/*').read() if tf_environment == True: print('setup completed...') else: print('Command unsuccessfull... please see output: ' + tf_environment)