def list_all_environments(self, printable=True, with_project_prefix=True):
     validate_config_file()
     for env, details in self.all_projects_config.items():
         prefix = f"{details['project_name']}-" if with_project_prefix else ''
         if printable:
             print(
                 util.green_text(
                     f"- {prefix}{details['project_environment']}"))
Beispiel #2
0
def switch_to_session(session_name):
    if session_name:
        all_sessions = get_all_active_sessions()
        if session_name not in all_sessions:
            util.error_log(f'Session {session_name} unavailable')

        # replace the default profile in the AWS_CREDS file
        replace_config_section(config.AWS_CREDS_PATH, 'default',
                               all_sessions[session_name])
        print('INFO: Switched to => ' +
              util.green_text('{}'.format(session_name)))
 def list_project_environments(self, project_name, printable=True):
     validate_config_file()
     _pjt_envs = []
     for env, details in self.all_projects_config.items():
         if details.get('project_name'
                        ) and project_name == details['project_name']:
             _pjt_envs.append(details['project_environment'])
             if printable:
                 print(
                     util.green_text(f"- {details['project_environment']}"))
     return _pjt_envs
    def list_projects(self, printable=True, validate_configuration=True) -> []:
        if validate_configuration:
            validate_config_file()

        _pjts = []
        for env, details in self.all_projects_config.items():
            if details.get('project_name') not in _pjts:
                if printable:
                    print(util.green_text(f"- {details['project_name']}"))
                _pjts.append(details['project_name'])
        return _pjts
Beispiel #5
0
    def assume_role(self, project_name, environment, role):
        project_config = self.all_projects_config[
            f'{project_name}-{environment}']
        util.info_log(
            f"Attempting to assume role: \"{role}\" using ARN: \"{project_config['role_arn']}\" "
            f"on project: {project_name}")
        if project_config['mfa_required']:
            session_name = f"session-{project_name}-{environment}"
            mfa_token = config_collector.InputDialog(
                f"MFA TOKEN for device {project_config['mfa_device_arn']}"
            ).get_answer()
            session_creds = aws_client.get_sts_credentials(
                project_name, project_config, mfa_token, session_name)
            options = [
                ('aws_access_key_id', 'AccessKeyId'),
                ('aws_secret_access_key', 'SecretAccessKey'),
                ('aws_session_token', 'SessionToken'),
                ('aws_security_token', 'SessionToken'),
            ]

            new_session = {
                k: session_creds['Credentials'][v]
                for k, v in options
            }
            new_session.update({
                'expiration':
                session_creds['Credentials']['Expiration'].strftime(
                    config.EXPIRATION_TIMESTAMP_FORMAT)
            })
            config_parser_util.replace_config_section(
                config.AWS_ASSUME_CONFIG_PATH, session_name, new_session)

            # replace the default profile in the AWS_CREDS file
            config_parser_util.replace_config_section(config.AWS_CREDS_PATH,
                                                      'default', new_session)
            print(util.green_text('- SUCCESS!'))
        else:
            print(
                util.red_text(
                    'ALL PROJECT CONFIGS ARE EXPECTED TO HAVE MFA ENABLED, AS OF THIS VERSION. !'
                ))
            sys.exit(1)
Beispiel #6
0
    def __init__(self) -> object:
        # MAIN Parser
        self.parent_parser = argparse.ArgumentParser(
            description=util.green_text("aws-sessions-switcher CLI"),
            add_help=True)
        self.parent_parser.add_argument(
            "-l",
            "--list",
            action='store_true',
            dest=config.ACTION_LIST_ASSUMPTIONS,
            help="Lists all the role assumptions that you can make")

        self.parent_parser.add_argument(
            "-v",
            "--version",
            action='version',
            version=util.green_text(
                f'aws-sessions-switcher {__version__.get_version()}'),
            help="Lists all the role assumptions that you can make")

        self.sub_parser = self.parent_parser.add_subparsers(
            title="sub-command",
            description="sub-command",
            dest=config.ACTION,
            required=False)

        # COMMAND => configure
        self.sub_parser.add_parser(config.sub_commands['CFGR'])

        # COMMAND => projects
        self.project_parser = self.sub_parser.add_parser(
            config.sub_commands['PRJ'])
        project_operations_subparser = self.project_parser.add_subparsers(
            title="project-operations", dest=config.SUB_ACTION)
        project_operations_subparser.add_parser(config.sub_commands['ADD'])
        delete_operation = project_operations_subparser.add_parser(
            config.sub_commands['DEL'])
        delete_operation.add_argument(config.SHORT_VAR_PROJECT_NAME,
                                      config.LONG_VAR_PROJECT_NAME,
                                      help="Name of the project to be deleted",
                                      required=True)

        # COMMAND => sessions
        self.sessions_parser = self.sub_parser.add_parser(
            config.sub_commands['SESSIONS'])
        self.sessions_sub_parser = self.sessions_parser.add_subparsers(
            title="session-operations", dest=config.SUB_ACTION)
        self.sessions_sub_parser.add_parser(config.sub_commands['SWT'])

        # COMMAND => environments
        self.environments_parser = self.sub_parser.add_parser(
            config.sub_commands['ENV'])
        configure_environments_parser(self.environments_parser)
        # COMMAND => env (same as the previous one, but short version)
        self.environments_parser_short = self.sub_parser.add_parser(
            config.sub_commands['SHORT_ENV'])
        configure_environments_parser(self.environments_parser_short)

        # COMMAND => reset (deletes all saved config)
        self.sub_parser.add_parser(config.sub_commands['RST'])

        # ENABLE AUTO COMPLETION OF COMMANDS
        argcomplete.autocomplete(self.parent_parser)

        # Instantiate the `aws-sessions-switcher` tool
        self.aws_assume = AwsAssume()

        # DYNAMIC => Now load already configured projects into the parser
        for project_name in self.aws_assume.list_projects(
                printable=False, validate_configuration=False):
            self.configured_projects.append(project_name)
            self.configured_projects_parsers[
                project_name] = self.sub_parser.add_parser(project_name)
            _sub = self.configured_projects_parsers[
                project_name].add_subparsers(title='project_environment',
                                             dest='project_environment',
                                             required=True)
            _envs = self.aws_assume.list_project_environments(project_name,
                                                              printable=False)
            for environment in _envs:
                env_parser = _sub.add_parser(environment)
                role_parser = env_parser.add_subparsers(title="iam_role",
                                                        dest='iam_role',
                                                        required=True)
                roles = self.aws_assume.list_roles(project_name,
                                                   environment,
                                                   printable=False)
                {r: role_parser.add_parser(r) for r in roles}

        self.args = self.parent_parser.parse_args().__dict__