Пример #1
0
def debug_mode(header, data_object, debug=False, halt=False):
    """ debug output """
    if debug:
        print('\n  ' + str(header) + '\n')
        try:
            if type(data_object) is dict:
                export_json_object(data_object)
            elif type(data_object) is str:
                stdout_message(
                    message=
                    f'{globals()[data_object]} parameter is {data_object}',
                    prefix='DEBUG')
        except Exception:
            print(data_object)
        if halt:
            sys.exit(0)
    return True
Пример #2
0
def format_text(json_object, debug=False):
    """
        Formats json object into text format

    Args:
        :json_object (json):  object with json schema

    Returns:
        text object | empty string upon failure

    """
    name = ''
    try:
        # AWS region code
        region = [x for x in json_object][0]

        if isinstance(json_object[region], str) and len([x for x in json_object]) == 1:
            # single region json, no metadata details
            return {"ImageId": json_object[region]}, region, None

        elif isinstance(json_object[region], str) and len([x for x in json_object]) > 1:
            # multiple region json, no metadata details
            regions = [x for x in json_object]
            image_ids = [x for x in json_object.values()]
            return {"ImageId": json_object[region]}, regions, None

        export_json_object(json_object) if debug else print('', end='')

        for k, v in json_object[region].items():
            # Extract ami human-readable name
            if k == 'Name':
                name = v
        json_object[region].pop('Name')

        metadata = UnwrapDict(json_object)

        for k, v in json_object.items():
            data, bddict = metadata.unwrap(v)

    except KeyError as e:
        logger.exception(
            '%s: json_object does not appear to be json structure. Error (%s)' %
            (inspect.stack()[0][3], str(e))
            )
        return ''
    return data.split('\n'), region, name, bddict
Пример #3
0
def init_cli():
    """
    Initializes commandline script
    """
    parser = argparse.ArgumentParser(add_help=False)

    try:

        args = options(parser)

    except Exception as e:
        stdout_message(str(e), 'ERROR')
        sys.exit(exit_codes['EX_OK']['Code'])

    if not precheck(args):
        sys.exit(exit_codes['E_DEPENDENCY']['Code'])

    elif len(sys.argv) == 1:
        help_menu()
        sys.exit(exit_codes['EX_OK']['Code'])

    elif args.help:
        help_menu()
        sys.exit(exit_codes['EX_OK']['Code'])

    elif args.version:
        package_version()

    elif ('--show' in sys.argv or '-s' in sys.argv) and args.show is None:
        stdout_message(
            'You must specify a value when using the --show option. Example: \
        \n\n\t\t$  %s  --show profiles' % (act + CALLER + rst))

    elif args.show:
        return show_information(args.show)

    elif args.profile:
        if authenticated(profile=parse_profiles(args.profile)):

            container = {}
            default_outputfile = get_account_identifier(
                parse_profiles(args.profile)) + '.profile'
            region = default_region(args.profile)

            # add aws account identifiers
            container['AccountId'] = get_account_identifier(parse_profiles(
                args.profile),
                                                            returnAlias=False)
            container['AccountAlias'] = get_account_identifier(
                parse_profiles(args.profile))

            # profile the account
            r_subnets = profile_subnets(profile=parse_profiles(args.profile))
            r_sgs = profile_securitygroups(
                profile=parse_profiles(args.profile))
            r_keypairs = profile_keypairs(profile=parse_profiles(args.profile))

            # assemble profile data into single json schema
            if r_subnets and r_sgs and r_keypairs:

                try:
                    for region in get_regions():
                        temp = {}
                        temp['Subnets'] = r_subnets[region]
                        temp['SecurityGroups'] = r_sgs[region]
                        temp['KeyPairs'] = r_keypairs[region]
                        container[region] = temp
                except KeyError as e:
                    raise e

                if args.outputfile:
                    export_json_object(container,
                                       FILE_PATH + '/' + default_outputfile)
                elif is_tty():
                    export_json_object(container, logging=False)
                    stdout_message('AWS Account profile complete')
        return True

    else:
        stdout_message('Unrecognized option. Exit')
    return False
Пример #4
0
def file_contents(content):
    with open(FILE_PATH + '/' + content) as f1:
        f2 = f1.read()
        f3 = json.loads(f2)
        export_json_object(f3, logging=False)
    return True
Пример #5
0
def docker_init(src, builddir, osimage, param_dict, debug):
    """
    Summary:
        Creates docker image and container
    Args:
    Returns:
        Container id (Name) | Failure (None)
    """
    imagename = osimage + ':' + param_dict['DockerImage']  # image name
    cname = param_dict['DockerContainer']  # container id
    host_mnt = VOLMNT  # host volume mount point
    container_mnt = CONTAINER_VOLMNT  # container volume internal mnt pt
    docker_user = '******'
    bash_cmd = '/bin/sleep 30'
    buildscript = 'docker-buildrpm.sh'

    # copy buildscript to directory where build files assembled
    copyfile(src + '/' + buildscript, builddir + '/' + buildscript)

    try:

        # create host mount for container volume
        if not os.path.exists(host_mnt):
            os.makedirs(host_mnt)
            stdout_message(
                f'Created host mount {host_mnt} for container volume')

        # if image rpmbuild not exist, create
        try:

            image = dclient.images.get(imagename)

            if image:
                stdout_message('Image already exists. Creating Container...')

        except Exception:
            # create new docker image
            os.chdir(src)
            cmd = 'docker build -t {} . '.format(imagename)
            subprocess.call([cmd], shell=True, cwd=src)
            stdout_message('Built image', prefix='OK')

        # start container detached
        container = dclient.containers.run(
            name=cname,
            image=imagename,
            command=bash_cmd,
            volumes={host_mnt: {
                'bind': container_mnt,
                'mode': 'rw'
            }},
            user=docker_user,
            detach=True)

        # verify container is running
        if not container_running(cname):
            stdout_message(f'Container {cname} not started - abort',
                           prefix='WARN')
            return False

        # copy build files to container
        stdout_message('Begin cp files into container')

        # copy files from temporary build directory to container
        os.chdir(builddir)

        buildfile_list = list(
            filter(
                lambda x: x.endswith('.tar.gz') or x.endswith('.spec') or x.
                endswith('.sh'), os.listdir('.')))

        if debug:
            print(f'buildfile_list contains:\n\n\t%s' %
                  export_json_object(buildfile_list))
            print(f'osimage is: {osimage}')
            print(f'imagename is: {imagename}')
            print(f'container name is: {container.name}')

        for file in buildfile_list:
            # local fs >> container:/home/builder
            cmd = f'docker cp {file} {container.name}:/home/builder/{file}'
            # status
            if not subprocess.getoutput(cmd):
                stdout_message(
                    f'{file} copied to container {container.name} successfully'
                )
            else:
                stdout_message(
                    f'Problem copying {file} to container {container.name}',
                    prefix='WARN')

        # exec rpmbuild script
        cmd = f'docker exec -i {container.name} sh -c \'cd /home/builder && bash {buildscript}\''
        stdout_message(subprocess.getoutput(cmd))

        if container_running(container.name):
            return container
    except OSError as e:
        logger.exception('%s: Problem while updating builddir contents: %s' %
                         (inspect.stack()[0][3], str(e)))
    return None
Пример #6
0
def main(profile, imagetype, format, details, debug, filename='', rgn=None):
    """
    Summary:
        Calls appropriate module function to identify the latest current amazon machine
        image for the specified OS type

    Returns:
        json (dict) | text (str)

    """
    try:
        if imagetype.startswith('amazonlinux1'):
            latest = amazonlinux1(
                        profile=profile,
                        region=rgn,
                        detailed=details,
                        debug=debug
                    )

        elif imagetype.startswith('amazonlinux2'):
            latest = amazonlinux2(
                        profile=profile,
                        region=rgn,
                        detailed=details,
                        debug=debug
                    )

        elif imagetype.startswith('centos'):
            latest = centos(
                        profile=profile,
                        os=os_version(imagetype),
                        region=rgn,
                        detailed=details,
                        debug=debug
                    )

        elif imagetype.startswith('fedora'):
            latest = fedora(
                        profile=profile,
                        os=os_version(imagetype),
                        region=rgn,
                        detailed=details,
                        debug=debug
                    )

        elif imagetype.startswith('redhat'):
            latest = redhat(
                        profile=profile,
                        os=os_version(imagetype),
                        region=rgn,
                        detailed=details,
                        debug=debug
                    )

        elif imagetype.startswith('ubuntu'):
            latest = ubuntu(
                        profile=profile,
                        os=os_version(imagetype),
                        region=rgn,
                        detailed=details,
                        debug=debug
                    )

        elif imagetype.startswith('windows'):
            latest = windows(
                        profile=profile,
                        os=os_version(imagetype),
                        region=rgn,
                        detailed=details,
                        debug=debug
                    )

        # return appropriate response format
        if format == 'json' and not filename:
            if is_tty():
                r = export_json_object(latest, logging=False)
            else:
                print(json.dumps(latest, indent=4))
                return True

        elif format == 'json' and filename:
            r = export_json_object(latest, filename=filename)

        elif format == 'text' and not filename and len([x for x in latest]) == 1:
            # single region
            print_data, regioncode, ami_title, bddict = format_text(latest)
            return print_text_stdout(ami_title, print_data, regioncode, bddict)

        elif format == 'text' and not filename and rgn is None:
            # all regions
            return print_text_allregions(latest)

        elif format == 'text' and filename:
            r = write_to_file(text=format_text(latest), file=filename)

    except Exception as e:
        logger.exception(
            '%s: Unknown problem retrieving data from AWS (%s)' %
            (inspect.stack()[0][3], str(e)))
        return False
    return r