Exemplo n.º 1
0
def main():
    module = AssibleModule(argument_spec=dict(), supports_check_mode=True)
    module.run_command_environ_update = dict(LANG="C", LC_ALL="C")
    service_modules = (ServiceScanService, SystemctlScanService,
                       AIXScanService)
    all_services = {}
    incomplete_warning = False
    for svc_module in service_modules:
        svcmod = svc_module(module)
        svc = svcmod.gather_services()
        if svc is not None:
            all_services.update(svc)
            if svcmod.incomplete_warning:
                incomplete_warning = True
    if len(all_services) == 0:
        results = dict(
            skipped=True,
            msg=
            "Failed to find any services. Sometimes this is due to insufficient privileges."
        )
    else:
        results = dict(assible_facts=dict(services=all_services))
        if incomplete_warning:
            results[
                'msg'] = "WARNING: Could not find status for all services. Sometimes this is due to insufficient privileges."
    module.exit_json(**results)
Exemplo n.º 2
0
def main():
    module = AssibleModule(
        argument_spec=dict(
            dest=dict(type='path'),
            repo=dict(type='str', required=True, aliases=['name', 'repository']),
            revision=dict(type='str', default='HEAD', aliases=['rev', 'version']),
            force=dict(type='bool', default=False),
            username=dict(type='str'),
            password=dict(type='str', no_log=True),
            executable=dict(type='path'),
            export=dict(type='bool', default=False),
            checkout=dict(type='bool', default=True),
            update=dict(type='bool', default=True),
            switch=dict(type='bool', default=True),
            in_place=dict(type='bool', default=False),
            validate_certs=dict(type='bool', default=False),
        ),
        supports_check_mode=True,
    )

    dest = module.params['dest']
    repo = module.params['repo']
    revision = module.params['revision']
    force = module.params['force']
    username = module.params['username']
    password = module.params['password']
    svn_path = module.params['executable'] or module.get_bin_path('svn', True)
    export = module.params['export']
    switch = module.params['switch']
    checkout = module.params['checkout']
    update = module.params['update']
    in_place = module.params['in_place']
    validate_certs = module.params['validate_certs']

    # We screenscrape a huge amount of svn commands so use C locale anytime we
    # call run_command()
    module.run_command_environ_update = dict(LANG='C', LC_MESSAGES='C')

    if not dest and (checkout or update or export):
        module.fail_json(msg="the destination directory must be specified unless checkout=no, update=no, and export=no")

    svn = Subversion(module, dest, repo, revision, username, password, svn_path, validate_certs)

    if not export and not update and not checkout:
        module.exit_json(changed=False, after=svn.get_remote_revision())
    if export or not os.path.exists(dest):
        before = None
        local_mods = False
        if module.check_mode:
            module.exit_json(changed=True)
        elif not export and not checkout:
            module.exit_json(changed=False)
        if not export and checkout:
            svn.checkout()
            files_changed = True
        else:
            svn.export(force=force)
            files_changed = True
    elif svn.is_svn_repo():
        # Order matters. Need to get local mods before switch to avoid false
        # positives. Need to switch before revert to ensure we are reverting to
        # correct repo.
        if not update:
            module.exit_json(changed=False)
        if module.check_mode:
            if svn.has_local_mods() and not force:
                module.fail_json(msg="ERROR: modified files exist in the repository.")
            check, before, after = svn.needs_update()
            module.exit_json(changed=check, before=before, after=after)
        files_changed = False
        before = svn.get_revision()
        local_mods = svn.has_local_mods()
        if switch:
            files_changed = svn.switch() or files_changed
        if local_mods:
            if force:
                files_changed = svn.revert() or files_changed
            else:
                module.fail_json(msg="ERROR: modified files exist in the repository.")
        files_changed = svn.update() or files_changed
    elif in_place:
        before = None
        svn.checkout(force=True)
        files_changed = True
        local_mods = svn.has_local_mods()
        if local_mods and force:
            svn.revert()
    else:
        module.fail_json(msg="ERROR: %s folder already exists, but its not a subversion repository." % (dest,))

    if export:
        module.exit_json(changed=True)
    else:
        after = svn.get_revision()
        changed = files_changed or local_mods
        module.exit_json(changed=changed, before=before, after=after)
Exemplo n.º 3
0
def main():
    module = AssibleModule(
        argument_spec=dict(
            state=dict(
                type='str',
                default='present',
                choices=['absent', 'build-dep', 'fixed', 'latest', 'present']),
            update_cache=dict(type='bool', aliases=['update-cache']),
            update_cache_retries=dict(type='int', default=5),
            update_cache_retry_max_delay=dict(type='int', default=12),
            cache_valid_time=dict(type='int', default=0),
            purge=dict(type='bool', default=False),
            package=dict(type='list', elements='str', aliases=['pkg', 'name']),
            deb=dict(type='path'),
            default_release=dict(type='str', aliases=['default-release']),
            install_recommends=dict(type='bool',
                                    aliases=['install-recommends']),
            force=dict(type='bool', default=False),
            upgrade=dict(type='str',
                         choices=['dist', 'full', 'no', 'safe', 'yes'],
                         default='no'),
            dpkg_options=dict(type='str', default=DPKG_OPTIONS),
            autoremove=dict(type='bool', default=False),
            autoclean=dict(type='bool', default=False),
            fail_on_autoremove=dict(type='bool', default=False),
            policy_rc_d=dict(type='int', default=None),
            only_upgrade=dict(type='bool', default=False),
            force_apt_get=dict(type='bool', default=False),
            allow_unauthenticated=dict(type='bool',
                                       default=False,
                                       aliases=['allow-unauthenticated']),
        ),
        mutually_exclusive=[['deb', 'package', 'upgrade']],
        required_one_of=[[
            'autoremove', 'deb', 'package', 'update_cache', 'upgrade'
        ]],
        supports_check_mode=True,
    )

    module.run_command_environ_update = APT_ENV_VARS

    if not HAS_PYTHON_APT:
        if module.check_mode:
            module.fail_json(
                msg="%s must be installed to use check mode. "
                "If run normally this module can auto-install it." %
                PYTHON_APT)
        try:
            # We skip cache update in auto install the dependency if the
            # user explicitly declared it with update_cache=no.
            if module.params.get('update_cache') is False:
                module.warn(
                    "Auto-installing missing dependency without updating cache: %s"
                    % PYTHON_APT)
            else:
                module.warn(
                    "Updating cache and auto-installing missing dependency: %s"
                    % PYTHON_APT)
                module.run_command(['apt-get', 'update'], check_rc=True)

            module.run_command([
                'apt-get', 'install', '--no-install-recommends', PYTHON_APT,
                '-y', '-q'
            ],
                               check_rc=True)
            global apt, apt_pkg
            import apt
            import apt.debfile
            import apt_pkg
        except ImportError:
            module.fail_json(
                msg="Could not import python modules: apt, apt_pkg. "
                "Please install %s package." % PYTHON_APT)

    global APTITUDE_CMD
    APTITUDE_CMD = module.get_bin_path("aptitude", False)
    global APT_GET_CMD
    APT_GET_CMD = module.get_bin_path("apt-get")

    p = module.params

    if p['upgrade'] == 'no':
        p['upgrade'] = None

    use_apt_get = p['force_apt_get']

    if not use_apt_get and not APTITUDE_CMD:
        use_apt_get = True

    updated_cache = False
    updated_cache_time = 0
    install_recommends = p['install_recommends']
    allow_unauthenticated = p['allow_unauthenticated']
    dpkg_options = expand_dpkg_options(p['dpkg_options'])
    autoremove = p['autoremove']
    fail_on_autoremove = p['fail_on_autoremove']
    autoclean = p['autoclean']

    # Get the cache object
    cache = get_cache(module)

    try:
        if p['default_release']:
            try:
                apt_pkg.config['APT::Default-Release'] = p['default_release']
            except AttributeError:
                apt_pkg.Config['APT::Default-Release'] = p['default_release']
            # reopen cache w/ modified config
            cache.open(progress=None)

        mtimestamp, updated_cache_time = get_updated_cache_time()
        # Cache valid time is default 0, which will update the cache if
        #  needed and `update_cache` was set to true
        updated_cache = False
        if p['update_cache'] or p['cache_valid_time']:
            now = datetime.datetime.now()
            tdelta = datetime.timedelta(seconds=p['cache_valid_time'])
            if not mtimestamp + tdelta >= now:
                # Retry to update the cache with exponential backoff
                err = ''
                update_cache_retries = module.params.get(
                    'update_cache_retries')
                update_cache_retry_max_delay = module.params.get(
                    'update_cache_retry_max_delay')
                randomize = random.randint(0, 1000) / 1000.0

                for retry in range(update_cache_retries):
                    try:
                        cache.update()
                        break
                    except apt.cache.FetchFailedException as e:
                        err = to_native(e)

                    # Use exponential backoff plus a little bit of randomness
                    delay = 2**retry + randomize
                    if delay > update_cache_retry_max_delay:
                        delay = update_cache_retry_max_delay + randomize
                    time.sleep(delay)
                else:
                    module.fail_json(msg='Failed to update apt cache: %s' %
                                     (err if err else 'unknown reason'))

                cache.open(progress=None)
                mtimestamp, post_cache_update_time = get_updated_cache_time()
                if updated_cache_time != post_cache_update_time:
                    updated_cache = True
                updated_cache_time = post_cache_update_time

            # If there is nothing else to do exit. This will set state as
            #  changed based on if the cache was updated.
            if not p['package'] and not p['upgrade'] and not p['deb']:
                module.exit_json(changed=updated_cache,
                                 cache_updated=updated_cache,
                                 cache_update_time=updated_cache_time)

        force_yes = p['force']

        if p['upgrade']:
            upgrade(module, p['upgrade'], force_yes, p['default_release'],
                    use_apt_get, dpkg_options, autoremove, fail_on_autoremove,
                    allow_unauthenticated)

        if p['deb']:
            if p['state'] != 'present':
                module.fail_json(msg="deb only supports state=present")
            if '://' in p['deb']:
                p['deb'] = fetch_file(module, p['deb'])
            install_deb(module,
                        p['deb'],
                        cache,
                        install_recommends=install_recommends,
                        allow_unauthenticated=allow_unauthenticated,
                        force=force_yes,
                        fail_on_autoremove=fail_on_autoremove,
                        dpkg_options=p['dpkg_options'])

        unfiltered_packages = p['package'] or ()
        packages = [
            package.strip() for package in unfiltered_packages
            if package != '*'
        ]
        all_installed = '*' in unfiltered_packages
        latest = p['state'] == 'latest'

        if latest and all_installed:
            if packages:
                module.fail_json(
                    msg=
                    'unable to install additional packages when upgrading all installed packages'
                )
            upgrade(module, 'yes', force_yes, p['default_release'],
                    use_apt_get, dpkg_options, autoremove, fail_on_autoremove,
                    allow_unauthenticated)

        if packages:
            for package in packages:
                if package.count('=') > 1:
                    module.fail_json(msg="invalid package spec: %s" % package)
                if latest and '=' in package:
                    module.fail_json(
                        msg='version number inconsistent with state=latest: %s'
                        % package)

        if not packages:
            if autoclean:
                cleanup(module,
                        p['purge'],
                        force=force_yes,
                        operation='autoclean',
                        dpkg_options=dpkg_options)
            if autoremove:
                cleanup(module,
                        p['purge'],
                        force=force_yes,
                        operation='autoremove',
                        dpkg_options=dpkg_options)

        if p['state'] in ('latest', 'present', 'build-dep', 'fixed'):
            state_upgrade = False
            state_builddep = False
            state_fixed = False
            if p['state'] == 'latest':
                state_upgrade = True
            if p['state'] == 'build-dep':
                state_builddep = True
            if p['state'] == 'fixed':
                state_fixed = True

            success, retvals = install(
                module,
                packages,
                cache,
                upgrade=state_upgrade,
                default_release=p['default_release'],
                install_recommends=install_recommends,
                force=force_yes,
                dpkg_options=dpkg_options,
                build_dep=state_builddep,
                fixed=state_fixed,
                autoremove=autoremove,
                fail_on_autoremove=fail_on_autoremove,
                only_upgrade=p['only_upgrade'],
                allow_unauthenticated=allow_unauthenticated)

            # Store if the cache has been updated
            retvals['cache_updated'] = updated_cache
            # Store when the update time was last
            retvals['cache_update_time'] = updated_cache_time

            if success:
                module.exit_json(**retvals)
            else:
                module.fail_json(**retvals)
        elif p['state'] == 'absent':
            remove(module,
                   packages,
                   cache,
                   p['purge'],
                   force=force_yes,
                   dpkg_options=dpkg_options,
                   autoremove=autoremove)

    except apt.cache.LockFailedException as lockFailedException:
        module.fail_json(msg="Failed to lock apt for exclusive operation: %s" %
                         lockFailedException)
    except apt.cache.FetchFailedException as fetchFailedException:
        module.fail_json(msg="Could not fetch updated apt files: %s" %
                         fetchFailedException)