Lambdaでてきとうに試しただけなので勘弁してください。
lambda_function.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import boto3 import traceback import logging from test import TestAttachRole from aws_iam import Iam from logging import getLogger, INFO logger = getLogger(__file__) logger.setLevel(INFO) def lambda_handler(event, context): """ type: rtype: """ logger.info( { "message": "" }) iam = Iam() iam_users = iam.get_iam_users() user_and_properties = iam.get_user_and_properties(iam_users) try: if 'test' == event['cron']: m = TestAttachRole() m.add_users_to_group(m.get_users_will_attach_role(user_and_properties)) else: logger.error( { "message": "" }) except Exception as e: logger.exception( { "message":"{s}".format(s=e), }) return
test.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json import traceback import boto3 import logging from logging import getLogger, INFO logger = getLogger(__file__) logger.setLevel(INFO) class TestAttachRole: """ """ def get_users_will_attach_role(self, user_and_properties): """ type: rtype: """ users_will_attach_role = [ item["User"] for item in user_and_properties if not "will_attach_role" in item["Groups"]] return users_will_attach_role def add_users_to_group(self, users_will_attach_role): """ type: rtype: """ iam = boto3.client('iam') for i in range(len(users_will_attach_role)): r = iam.add_user_to_group( GroupName='will_attach_role', UserName=users_will_attach_role[i]) print(r)
aws_iam.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import boto3 import botocore.client import logging from logging import getLogger, INFO logger = getLogger(__file__) logger.setLevel(INFO) class Iam: """ AWS IAM access class """ def __init__(self): """ Constructor """ self.iam = self.connect() def connect(self): """ Connect to iam. """ try: iam = boto3.client('iam') return iam except Exception as e: logger.exception( { "message":"{s}".format(s=e), }) return def get_iam_users(self): """ type: rtype: """ try: iam_users = self.iam.list_users() return iam_users except Exception as e: logger.exception( { "message":"{s}".format(s=e), }) return def get_user_and_properties(self, iam_users): """ type: rtype: """ user_list = [] try: for user in iam_users['Users']: groups = [] result = {} # user name result['User'] = user['UserName'] # user group user_groups = self.iam.list_groups_for_user(UserName=user['UserName']) for user_group in user_groups['Groups']: groups.append(user_group['GroupName']) result['Groups'] = groups return user_list except Exception as e: logger.exception( { "message":"{s}".format(s=e), }) return