Example #1
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            server_url=dict(required=True),
            username=dict(required=True, no_log=True),
            password=dict(required=True, no_log=True),
            verify_ssl=dict(type='bool', default=True),
            product=dict(required=True),
            organization=dict(required=True),
            name=dict(required=True),
            content_type=dict(required=True),
            url=dict(),
            download_policy=dict(
                choices=['background', 'immediate', 'on_demand']),
            state=dict(default='present',
                       choices=['present_with_defaults', 'present', 'absent']),
        ),
        supports_check_mode=True,
    )

    handle_no_nailgun(module, HAS_NAILGUN_PACKAGE)

    entity_dict = dict([(k, v) for (k, v) in module.params.items()
                        if v is not None])

    server_url = entity_dict.pop('server_url')
    verify_ssl = entity_dict.pop('verify_ssl')
    username = entity_dict.pop('username')
    password = entity_dict.pop('password')
    state = entity_dict.pop('state')

    try:
        create_server(server_url, (username, password), verify_ssl)
    except Exception as e:
        module.fail_json(msg="Failed to connect to Foreman server: %s " % e)

    ping_server(module)

    entity_dict['organization'] = find_organization(
        module, name=entity_dict['organization'])

    entity_dict['product'] = find_product(
        module,
        name=entity_dict['product'],
        organization=entity_dict['organization'])

    entity = find_repository(module,
                             name=entity_dict['name'],
                             product=entity_dict['product'],
                             failsafe=True)

    entity_dict = sanitize_entity_dict(entity_dict, name_map)

    changed = naildown_entity_state(Repository, entity_dict, entity, state,
                                    module)

    module.exit_json(changed=changed)
Example #2
0
def main():
    module = KatelloEntityAnsibleModule(
        argument_spec=dict(
            product=dict(required=True),
            label=dict(),
            name=dict(required=True),
            content_type=dict(
                required=True,
                choices=['docker', 'ostree', 'yum', 'puppet', 'file', 'deb']),
            url=dict(),
            gpg_key=dict(),
            docker_upstream_name=dict(),
            download_policy=dict(
                choices=['background', 'immediate', 'on_demand']),
            mirror_on_sync=dict(type='bool', default=True),
            state=dict(default='present',
                       choices=['present_with_defaults', 'present', 'absent']),
        ),
        supports_check_mode=True,
    )

    (entity_dict, state) = module.parse_params()

    if entity_dict[
            'content_type'] != 'docker' and 'docker_upstream_name' in entity_dict:
        module.fail_json(
            msg=
            "docker_upstream_name should not be set unless content_type: docker"
        )

    module.connect()

    entity_dict['organization'] = find_organization(
        module, name=entity_dict['organization'])

    entity_dict['product'] = find_product(
        module,
        name=entity_dict['product'],
        organization=entity_dict['organization'])

    if 'gpg_key' in entity_dict:
        entity_dict['gpg_key'] = find_content_credential(
            module,
            name=entity_dict['gpg_key'],
            organization=entity_dict['organization'])

    entity = find_repository(module,
                             name=entity_dict['name'],
                             product=entity_dict['product'],
                             failsafe=True)

    entity_dict = sanitize_entity_dict(entity_dict, name_map)

    changed = naildown_entity_state(Repository, entity_dict, entity, state,
                                    module)

    module.exit_json(changed=changed)
def main():
    module = ForemanAnsibleModule(argument_spec=dict(
        src=dict(required=True, type='path', aliases=['file']),
        repository=dict(required=True),
        product=dict(required=True),
        organization=dict(required=True),
    ), )

    entity_dict = module.parse_params()

    module.connect()

    entity_dict['organization'] = find_organization(
        module, name=entity_dict['organization'])
    entity_dict['product'] = find_product(
        module,
        name=entity_dict['product'],
        organization=entity_dict['organization'])
    entity_dict['repository'] = find_repository(module,
                                                name=entity_dict['repository'],
                                                product=entity_dict['product'])

    content_unit = None
    if entity_dict['repository'].content_type == "yum":
        name, version, release, arch = check_output(
            "rpm --queryformat '%%{NAME} %%{VERSION} %%{RELEASE} %%{ARCH}' -qp %s"
            % entity_dict['src'],
            shell=True).decode('ascii').split()
        query = "name = \"{}\" and version = \"{}\" and release = \"{}\" and arch = \"{}\"".format(
            name, version, release, arch)
        content_unit = find_package(module,
                                    query,
                                    repository=entity_dict['repository'],
                                    failsafe=True)
    elif entity_dict['repository'].content_type == "file":
        h = hashlib.sha256()
        with open(entity_dict['src'], "rb") as f:
            for chunk in iter(lambda: f.read(4096), b""):
                h.update(chunk)
        checksum = h.hexdigest()
        name = os.path.basename(entity_dict['src'])
        query = "name = \"{}\" and checksum = \"{}\"".format(name, checksum)
        content_unit = find_file(module,
                                 query,
                                 repository=entity_dict['repository'],
                                 failsafe=True)

    changed = False
    if not content_unit:
        try:
            changed = upload(module, entity_dict['src'],
                             entity_dict['repository'])
        except Exception as e:
            module.fail_json(msg=to_native(e))

    module.exit_json(changed=changed)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            server_url=dict(required=True),
            username=dict(required=True, no_log=True),
            password=dict(required=True, no_log=True),
            verify_ssl=dict(type='bool', default=True),
            src=dict(required=True, type='path', aliases=['file']),
            repository=dict(required=True),
            product=dict(required=True),
            organization=dict(required=True),
        ),
        supports_check_mode=True,
    )

    if has_import_error:
        module.fail_json(msg=import_error_msg)

    entity_dict = dict(
        [(k, v) for (k, v) in module.params.items() if v is not None])

    server_url = entity_dict.pop('server_url')
    username = entity_dict.pop('username')
    password = entity_dict.pop('password')
    verify_ssl = entity_dict.pop('verify_ssl')

    try:
        create_server(server_url, (username, password), verify_ssl)
    except Exception as e:
        module.fail_json(msg="Failed to connect to Foreman server: %s " % e)

    ping_server(module)

    name, version, release, arch = check_output("rpm --queryformat '%%{NAME} %%{VERSION} %%{RELEASE} %%{ARCH}' -qp %s" % entity_dict['src'],
                                                shell=True).split()

    entity_dict['organization'] = find_organization(module, name=entity_dict['organization'])
    entity_dict['product'] = find_product(module, name=entity_dict['product'], organization=entity_dict['organization'])
    entity_dict['repository'] = find_repository(module, name=entity_dict['repository'], product=entity_dict['product'])

    package = False
    if entity_dict['repository'].content_type == "yum":
        query = "name = \"{}\" and version = \"{}\" and release = \"{}\" and arch = \"{}\"".format(name, version, release, arch)
        package = find_package(module, query, repository=entity_dict['repository'], failsafe=True)

    changed = False
    if package is None or package is False:
        try:
            changed = upload(module, entity_dict['src'], entity_dict['repository'])
        except Exception as e:
            module.fail_json(msg=to_native(e))

    module.exit_json(changed=changed)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            server_url=dict(required=True),
            username=dict(required=True, no_log=True),
            password=dict(required=True, no_log=True),
            verify_ssl=dict(type='bool', default=True),
            name=dict(required=True),
            organization=dict(required=True),
            repositories=dict(type='list'),
            state=dict(default='present',
                       choices=['present_with_defaults', 'present', 'absent']),
        ),
        supports_check_mode=True,
    )

    if has_import_error:
        module.fail_json(msg=import_error_msg)

    entity_dict = dict([(k, v) for (k, v) in module.params.items()
                        if v is not None])

    server_url = entity_dict.pop('server_url')
    username = entity_dict.pop('username')
    password = entity_dict.pop('password')
    verify_ssl = entity_dict.pop('verify_ssl')
    state = entity_dict.pop('state')

    try:
        create_server(server_url, (username, password), verify_ssl)
    except Exception as e:
        module.fail_json(msg="Failed to connect to Foreman server: %s " % e)

    ping_server(module)

    entity_dict['organization'] = find_organization(
        module, name=entity_dict['organization'])
    if 'repositories' in entity_dict:
        entity_dict['repositories'] = find_repositories(
            module, entity_dict['repositories'], entity_dict['organization'])

    content_view_entity = find_content_view(
        module,
        name=entity_dict['name'],
        organization=entity_dict['organization'],
        failsafe=True)
    content_view_dict = sanitize_entity_dict(entity_dict, name_map)

    changed = naildown_entity_state(ContentView, content_view_dict,
                                    content_view_entity, state, module)

    module.exit_json(changed=changed)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            server_url=dict(required=True),
            username=dict(required=True, no_log=True),
            password=dict(required=True, no_log=True),
            verify_ssl=dict(type='bool', default=True),
            product=dict(required=True),
            organization=dict(required=True),
            name=dict(required=True),
            content_type=dict(required=True, choices=['docker', 'ostree', 'yum', 'puppet', 'file', 'deb']),
            url=dict(),
            docker_upstream_name=dict(),
            download_policy=dict(choices=['background', 'immediate', 'on_demand']),
            state=dict(default='present', choices=['present_with_defaults', 'present', 'absent']),
        ),
        supports_check_mode=True,
    )

    if has_import_error:
        module.fail_json(msg=import_error_msg)

    entity_dict = dict(
        [(k, v) for (k, v) in module.params.items() if v is not None])

    server_url = entity_dict.pop('server_url')
    verify_ssl = entity_dict.pop('verify_ssl')
    username = entity_dict.pop('username')
    password = entity_dict.pop('password')
    state = entity_dict.pop('state')

    if entity_dict['content_type'] != 'docker' and 'docker_upstream_name' in entity_dict:
        module.fail_json(msg="docker_upstream_name should not be set unless content_type: docker")

    try:
        create_server(server_url, (username, password), verify_ssl)
    except Exception as e:
        module.fail_json(msg="Failed to connect to Foreman server: %s " % e)

    ping_server(module)

    entity_dict['organization'] = find_organization(module, name=entity_dict['organization'])

    entity_dict['product'] = find_product(module, name=entity_dict['product'], organization=entity_dict['organization'])

    entity = find_repository(module, name=entity_dict['name'], product=entity_dict['product'], failsafe=True)

    entity_dict = sanitize_entity_dict(entity_dict, name_map)

    changed = naildown_entity_state(Repository, entity_dict, entity, state, module)

    module.exit_json(changed=changed)
Example #7
0
def repository_set(module,
                   name,
                   organization,
                   product,
                   label,
                   state,
                   repositories=[]):
    changed = False
    organization = find_organization(module, organization)
    if product:
        product = find_product(module, product, organization)
    repo_set = find_repository_set(module,
                                   name=name,
                                   product=product,
                                   organization=organization,
                                   label=label)

    available_repos = repo_set.available_repositories()['results']
    current_repos = map(lambda repo: repo.read(), repo_set.repositories)
    desired_repos = get_desired_repos(repositories, available_repos)

    available_repo_names = set(
        map(lambda repo: repo['repo_name'], available_repos))
    current_repo_names = set(map(lambda repo: repo.name, current_repos))
    desired_repo_names = set(map(lambda repo: repo['repo_name'],
                                 desired_repos))

    if len(desired_repo_names - available_repo_names) > 0:
        module.fail_json(
            msg=
            "Desired repositories are not available on the repository set {}. Desired: {} Available: {}"
            .format(name, desired_repo_names, available_repo_names))

    if state == 'enabled':
        for repo in desired_repo_names - current_repo_names:
            repo_to_enable = next(
                (r for r in available_repos if r['repo_name'] == repo))
            repo_to_enable['substitutions']['product_id'] = repo_set.product.id
            if not module.check_mode:
                repo_set.enable(data=repo_to_enable['substitutions'])
            changed = True
    elif state == 'disabled':
        for repo in current_repo_names & desired_repo_names:
            repo_to_disable = next(
                (r for r in available_repos if r['repo_name'] == repo))
            repo_to_disable['substitutions'][
                'product_id'] = repo_set.product.id
            if not module.check_mode:
                repo_set.disable(data=repo_to_disable['substitutions'])
            changed = True
    return changed
Example #8
0
def main(module):
    handle_no_nailgun(module, HAS_NAILGUN_PACKAGE)

    name = module.params.get('name')
    state = module.params.get('state')
    provider = module.params.get('provider').title()
    description = module.params.get('description')
    locations = module.params.get('locations')
    organizations = module.params.get('organizations')

    cement.create_server(
        server_url=module.params.get('server_url'),
        auth=(module.params.get('username'), module.params.get('password')),
        verify_ssl=module.params.get('verify_ssl'),
    )

    cement.ping_server(module)

    data = {
        'name': name,
        'description': description
    }

    compute_resource = cement.find_compute_resource(module, name=data.get('name'), failsafe=True)

    if organizations:
        data['organization'] = [cement.find_organization(module, organization) for organization in organizations]

    if locations:
        data['location'] = [cement.find_location(module, location) for location in locations]

    data['provider'] = provider
    provider_params = get_provider_params(provider=provider)

    if state in ['present', 'present_with_defaults']:
        if not provider_params and not compute_resource:
            module.fail_json(msg='To create a compute resource a valid provider must be supplied')

        for key in provider_params.get('credentials'):
            data.__setitem__(key, module.params.get('provider_auth').get(key))

        for key in provider_params.get('params'):
            if key not in module.params:
                module.fail_json(msg='missing required param {}'.format(key))

            data.__setitem__(key, module.params.get(key))

    changed = cement.naildown_entity_state(provider_params.get('class'), data, compute_resource, state, module)

    return changed
def lifecycle_environment(module,
                          name,
                          organization,
                          state,
                          label=None,
                          description=None,
                          prior=None):
    changed = False
    organization = find_organization(module, organization)
    prior = find_prior(module, prior, organization)
    current_environment = find_lifecycle_environment(module,
                                                     name,
                                                     organization,
                                                     failsafe=True)

    if state == 'present':
        if label is not None and current_environment is not None and current_environment.label != label:
            module.fail_json(
                msg="Label cannot be updated on a lifecycle environment.")
        if prior is not None and current_environment is not None and current_environment.prior.id != prior.id:
            module.fail_json(
                msg="Prior cannot be updated on a lifecycle environment.")
        desired_environment = LifecycleEnvironment(name=name,
                                                   organization=organization,
                                                   label=label,
                                                   description=description,
                                                   prior=prior)
        fields = ['description']
        if current_environment is not None:
            (needs_update, le) = update_fields(desired_environment,
                                               current_environment, fields)
            if needs_update:
                if not module.check_mode:
                    le.update(fields)
                changed = True
        else:
            desired_environment.prior = find_prior(
                module, "Library", organization) if prior is None else prior
            if not module.check_mode:
                desired_environment.create()
            changed = True
    elif current_environment is not None:
        if not module.check_mode:
            current_environment.delete()
        changed = True
    return changed
def main():
    module = KatelloEntityAnsibleModule(
        argument_spec=dict(
            name=dict(required=True),
            label=dict(),
            gpg_key=dict(),
            sync_plan=dict(),
            description=dict(),
            state=dict(default='present',
                       choices=['present_with_defaults', 'present', 'absent']),
        ),
        supports_check_mode=True,
    )

    (entity_dict, state) = module.parse_params()

    module.connect()

    entity_dict['organization'] = find_organization(
        module, name=entity_dict['organization'])

    if 'gpg_key' in entity_dict:
        entity_dict['gpg_key'] = find_content_credential(
            module,
            name=entity_dict['gpg_key'],
            organization=entity_dict['organization'])

    if 'sync_plan' in entity_dict:
        entity_dict['sync_plan'] = find_sync_plan(
            module,
            name=entity_dict['sync_plan'],
            organization=entity_dict['organization'])

    entity = find_product(module,
                          name=entity_dict['name'],
                          organization=entity_dict['organization'],
                          failsafe=True)

    entity_dict = sanitize_entity_dict(entity_dict, name_map)

    changed = naildown_entity_state(Product, entity_dict, entity, state,
                                    module)

    module.exit_json(changed=changed)
Example #11
0
def main():
    module = KatelloEntityAnsibleModule(
        argument_spec=dict(
            name=dict(required=True),
            label=dict(),
            gpg_key=dict(),
            description=dict(),
            state=dict(default='present',
                       choices=['present_with_defaults', 'present', 'absent']),
        ),
        supports_check_mode=True,
    )

    (server_params, entity_dict, state) = module.parse_params()

    try:
        (server_url, username, password, verify_ssl) = server_params
        create_server(server_url, (username, password), verify_ssl)
    except Exception as e:
        module.fail_json(msg="Failed to connect to Foreman server: %s " % e)

    ping_server(module)

    entity_dict['organization'] = find_organization(
        module, name=entity_dict['organization'])

    if 'gpg_key' in entity_dict:
        entity_dict['gpg_key'] = find_content_credential(
            module,
            name=entity_dict['gpg_key'],
            organization=entity_dict['organization'])

    entity = find_product(module,
                          name=entity_dict['name'],
                          organization=entity_dict['organization'],
                          failsafe=True)

    entity_dict = sanitize_entity_dict(entity_dict, name_map)

    changed = naildown_entity_state(Product, entity_dict, entity, state,
                                    module)

    module.exit_json(changed=changed)
Example #12
0
def manifest(module, organization, state, manifest_path=None, redhat_repository_url="https://cdn.redhat.com"):
    changed = False
    organization = find_organization(module, organization).read()
    current_manifest = current_subscription_manifest(module, organization)
    manifest_present = current_manifest is not None

    if organization.redhat_repository_url != redhat_repository_url:
        if not module.check_mode:
            organization.redhat_repository_url = redhat_repository_url
            organization.update({'redhat_repository_url'})
        changed = True

    if state == 'present':
        try:
            with open(manifest_path, 'rb') as manifest_file:
                files = {'content': (manifest_path, manifest_file, 'application/zip')}
                data = {'organization_id': organization.id, 'repository_url': redhat_repository_url}
                headers = {'content_type': 'multipart/form-data', 'multipart': 'true'}
                if not module.check_mode:
                    Subscription().upload(data=data, files=files, headers=headers)
                changed = True
        except IOError as e:
            module.fail_json(msg="Unable to open the manifest file: %s" % e)
        except TaskFailedError as e:
            if "same as existing data" in e.message:
                pass
            elif "older than existing data" in e.message:
                module.fail_json(msg="Manifest is older than existing data: %s" % e)
            else:
                module.fail_json(msg="Upload of the mainfest failed: %s" % e)
    elif state == 'absent' and manifest_present:
        if not module.check_mode:
            Subscription().delete_manifest(data={'organization_id': organization.id})
        changed = True
    elif state == 'refreshed':
        if not manifest_present:
            module.fail_json(msg="No manifest found to refresh.")
        else:
            if not module.check_mode:
                Subscription().refresh_manifest(data={'organization_id': organization.id})
            changed = True
    return changed
def main():
    module = ForemanEntityAnsibleModule(
        argument_spec=dict(
            name=dict(required=True),
            hostgroup=dict(),
            location=dict(),
            organization=dict(),
            enabled=dict(default='true', type='bool'),
            state=dict(default='present',
                       choices=['present_with_defaults', 'present', 'absent']),
        ),
        required_if=(
            ['state', 'present_with_defaults', ['hostgroup']],
            ['state', 'present', ['hostgroup']],
        ),
        supports_check_mode=True,
    )

    (host_dict, state) = module.parse_params()

    module.connect()

    host_dict['hostgroup'] = find_hostgroup(module,
                                            host_dict['hostgroup'],
                                            failsafe=True)

    host_dict['name'] = host_dict['name'] + '.' + \
        host_dict['hostgroup'].domain.read().fullname

    entity = find_host(module, host_dict['name'], failsafe=True)

    if 'location' in host_dict:
        host_dict['location'] = find_location(module, host_dict['location'])

    if 'organization' in host_dict:
        host_dict['organization'] = find_organization(
            module, host_dict['organization'])

    host_dict = sanitize_entity_dict(host_dict, name_map)
    changed = naildown_entity_state(Host, host_dict, entity, state, module)

    module.exit_json(changed=changed)
Example #14
0
def main():
    module = ForemanEntityAnsibleModule(
        argument_spec=dict(
            name=dict(required=True),
            label=dict(),
        ),
        supports_check_mode=True,
    )

    (entity_dict, state) = module.parse_params()

    module.connect()

    entity = find_organization(module, name=entity_dict['name'], failsafe=True)

    entity_dict = sanitize_entity_dict(entity_dict, name_map)

    changed = naildown_entity_state(Organization, entity_dict, entity, state,
                                    module)

    module.exit_json(changed=changed)
Example #15
0
def content_view_promote(module, name, organization, to_environment, **kwargs):
    changed = False

    organization = find_organization(module, organization)
    content_view = find_content_view(module,
                                     name=name,
                                     organization=organization)
    if kwargs['from_environment'] is not None:
        kwargs['from_environment'] = find_lifecycle_environment(
            module, name=kwargs['from_environment'], organization=organization)
    to_environment = find_lifecycle_environment(module,
                                                name=to_environment,
                                                organization=organization)
    content_view_version = find_content_view_version(
        module,
        content_view,
        environment=kwargs.pop('from_environment'),
        version=kwargs.pop('version'))

    request_data = {'environment_id': to_environment.id}
    request_data.update({k: v for k, v in kwargs.items() if v is not None})

    current_environment_ids = map(lambda environment: environment.id,
                                  content_view_version.environment)

    if to_environment.id not in current_environment_ids:
        if to_environment.prior.id in current_environment_ids or kwargs[
                'force']:
            if not module.check_mode:
                content_view_version.promote(data=request_data)
            changed = True
        elif to_environment.prior.id not in current_environment_ids:
            module.fail_json(
                msg=
                "Cannot promote directly to {} without having already promoted to {} without the force parameter"
                .format(to_environment.name,
                        to_environment.prior.read().name))

    return changed
def main():
    module = AnsibleModule(
        argument_spec=dict(
            server_url=dict(required=True),
            username=dict(required=True, no_log=True),
            password=dict(required=True, no_log=True),
            verify_ssl=dict(type='bool', default=True),
            name=dict(required=True),
            organization=dict(required=True),
            composite=dict(type='bool', default=False),
            auto_publish=dict(type='bool', default=False),
            components=dict(type='list'),
            repositories=dict(type='list'),
            state=dict(default='present', choices=['present_with_defaults', 'present', 'absent']),
        ),
        supports_check_mode=True,
        mutually_exclusive=[['repositories', 'components']],
    )

    if has_import_error:
        module.fail_json(msg=import_error_msg)

    entity_dict = dict(
        [(k, v) for (k, v) in module.params.items() if v is not None])

    server_url = entity_dict.pop('server_url')
    username = entity_dict.pop('username')
    password = entity_dict.pop('password')
    verify_ssl = entity_dict.pop('verify_ssl')
    state = entity_dict.pop('state')

    try:
        create_server(server_url, (username, password), verify_ssl)
    except Exception as e:
        module.fail_json(msg="Failed to connect to Foreman server: %s " % e)

    ping_server(module)

    entity_dict['organization'] = find_organization(module, name=entity_dict['organization'])
    if 'repositories' in entity_dict and not entity_dict['composite']:
        entity_dict['repositories'] = find_repositories(module, entity_dict['repositories'], entity_dict['organization'])

    content_view_entity = find_content_view(module, name=entity_dict['name'], organization=entity_dict['organization'], failsafe=True)
    content_view_dict = sanitize_entity_dict(entity_dict, name_map)

    changed, content_view_entity = naildown_entity(ContentView, content_view_dict, content_view_entity, state, module)

    # only update CVC's of newly created or updated CCV's
    if state == 'present' or (state == 'present_with_defaults' and changed):
        current_cvcs = []
        if hasattr(content_view_entity, 'content_view_component'):
            current_cvcs = [cvc.read() for cvc in content_view_entity.content_view_component]
        if 'components' in entity_dict and content_view_entity.composite:
            for component in entity_dict['components']:
                cvc = component.copy()
                cvc['content_view'] = find_content_view(module, name=component['content_view'], organization=entity_dict['organization'])
                cvc_matched = None
                for _cvc in current_cvcs:
                    if _cvc.content_view.id == cvc['content_view'].id:
                        cvc_matched = _cvc
                force_update = list()
                if 'version' in component:
                    cvc['version'] = find_content_view_version(module, cvc['content_view'], version=component['version'])
                    cvc['latest'] = False
                    if cvc_matched and cvc_matched.latest:
                        # When changing to latest=False & version is the latest we must send 'content_view_version' to the server
                        force_update.append('content_view_version')
                if cvc_matched:
                    cvc['composite_content_view'] = content_view_entity
                    cvc_dict = sanitize_entity_dict(cvc, cvc_map)
                    cvc_changed = naildown_entity_state(ContentViewComponent, cvc_dict, cvc_matched, 'present', module, force_update=force_update)
                    current_cvcs.remove(cvc_matched)
                    if cvc_changed:
                        changed = cvc_changed
                else:
                    for attr in ['latest', 'version']:
                        if attr not in cvc:
                            cvc[attr] = None
                    ContentViewComponent(composite_content_view=content_view_entity, content_view=cvc['content_view'],
                                         latest=cvc['latest'], content_view_version=cvc['version']).add()
                    changed = True
        for cvc in current_cvcs:
            # desired cvcs have already been updated and removed from `current_cvcs`
            cvc.remove()
            changed = True

    module.exit_json(changed=changed)
Example #17
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            server_url=dict(required=True),
            username=dict(required=True, no_log=True),
            password=dict(required=True, no_log=True),
            verify_ssl=dict(type='bool', default=True),
            src=dict(required=True, type='path', aliases=['file']),
            repository=dict(required=True),
            product=dict(required=True),
            organization=dict(required=True),
        ),
        supports_check_mode=True,
    )

    if has_import_error:
        module.fail_json(msg=import_error_msg)

    entity_dict = dict(
        [(k, v) for (k, v) in module.params.items() if v is not None])

    server_url = entity_dict.pop('server_url')
    username = entity_dict.pop('username')
    password = entity_dict.pop('password')
    verify_ssl = entity_dict.pop('verify_ssl')

    try:
        create_server(server_url, (username, password), verify_ssl)
    except Exception as e:
        module.fail_json(msg="Failed to connect to Foreman server: %s " % e)

    ping_server(module)

    entity_dict['organization'] = find_organization(module, name=entity_dict['organization'])
    entity_dict['product'] = find_product(module, name=entity_dict['product'], organization=entity_dict['organization'])
    entity_dict['repository'] = find_repository(module, name=entity_dict['repository'], product=entity_dict['product'])

    content_unit = None
    if entity_dict['repository'].content_type == "yum":
        name, version, release, arch = check_output("rpm --queryformat '%%{NAME} %%{VERSION} %%{RELEASE} %%{ARCH}' -qp %s" % entity_dict['src'],
                                                    shell=True).decode('ascii').split()
        query = "name = \"{}\" and version = \"{}\" and release = \"{}\" and arch = \"{}\"".format(name, version, release, arch)
        content_unit = find_package(module, query, repository=entity_dict['repository'], failsafe=True)
    elif entity_dict['repository'].content_type == "file":
        h = hashlib.sha256()
        with open(entity_dict['src'], "rb") as f:
            for chunk in iter(lambda: f.read(4096), b""):
                h.update(chunk)
        checksum = h.hexdigest()
        name = os.path.basename(entity_dict['src'])
        query = "name = \"{}\" and checksum = \"{}\"".format(name, checksum)
        content_unit = find_file(module, query, repository=entity_dict['repository'], failsafe=True)

    changed = False
    if not content_unit:
        try:
            changed = upload(module, entity_dict['src'], entity_dict['repository'])
        except Exception as e:
            module.fail_json(msg=to_native(e))

    module.exit_json(changed=changed)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            server_url=dict(required=True),
            username=dict(required=True, no_log=True),
            password=dict(required=True, no_log=True),
            verify_ssl=dict(type='bool', default=True),
            content_view=dict(required=True),
            organization=dict(required=True),
            state=dict(default='present', choices=['present', 'absent']),
            version=dict(),
            lifecycle_environments=dict(type='list', default=['Library']),
            force=dict(type='bool', aliases=['force_promote'], default=False),
            force_yum_metadata_regeneration=dict(type='bool', default=False),
            synchronous=dict(type='bool', default=True),
            current_lifecycle_environment=dict(),
        ),
        mutually_exclusive=[['current_lifecycle_environment', 'version']],
        supports_check_mode=True,
    )

    if has_import_error:
        module.fail_json(msg=import_error_msg)

    set_task_timeout(3600000)  # 60 minutes

    params_dict = dict([(k, v) for (k, v) in module.params.items()
                        if v is not None])

    server_url = module.params['server_url']
    username = module.params['username']
    password = module.params['password']
    verify_ssl = module.params['verify_ssl']
    state = module.params['state']

    try:
        create_server(server_url, (username, password), verify_ssl)
    except Exception as e:
        module.fail_json(msg="Failed to connect to Foreman server: %s " % e)

    ping_server(module)

    organization = find_organization(module, params_dict['organization'])
    content_view = find_content_view(module,
                                     name=params_dict['content_view'],
                                     organization=organization)

    if 'current_lifecycle_environment' in params_dict:
        params_dict[
            'current_lifecycle_environment'] = find_lifecycle_environment(
                module,
                name=params_dict['current_lifecycle_environment'],
                organization=organization)
        content_view_version = find_content_view_version(
            module,
            content_view,
            environment=params_dict['current_lifecycle_environment'])
    elif 'version' in params_dict:
        content_view_version = find_content_view_version(
            module,
            content_view,
            version=params_dict['version'],
            failsafe=True)
    else:
        content_view_version = None

    changed = False
    if state == 'present':
        if content_view_version is None:
            kwargs = dict(data=dict())
            if 'description' in params_dict:
                kwargs['data'].update(description=params_dict['description'])
            if 'force_metadata_regeneration' in params_dict:
                kwargs['data'].update(
                    force_yum_metadata_regeneration=params_dict[
                        'force_metadata_regeneration'])
            if 'version' in params_dict:
                kwargs['data'].update(
                    major=map(int,
                              str(params_dict['version']).split('.'))[0])
                kwargs['data'].update(
                    minor=map(int,
                              str(params_dict['version']).split('.'))[1])

            response = content_view.publish(params_dict['synchronous'],
                                            **kwargs)
            changed = True
            content_view_version = ContentViewVersion(
                id=response['output']['content_view_version_id']).read()

        if 'lifecycle_environments' in params_dict:
            lifecycle_environments = find_lifecycle_environments(
                module,
                names=params_dict['lifecycle_environments'],
                organization=organization)
            le_changed = promote_content_view_version(
                module,
                content_view_version,
                organization,
                lifecycle_environments,
                params_dict['synchronous'],
                force=params_dict['force'],
                force_yum_metadata_regeneration=params_dict[
                    'force_yum_metadata_regeneration'])
    elif state == 'absent':
        changed = naildown_entity_state(ContentViewVersion, dict(),
                                        content_view_version, state, module)

    module.exit_json(changed=changed or le_changed)
Example #19
0
def main():
    module = KatelloEntityAnsibleModule(
        argument_spec=dict(
            product=dict(required=True),
            label=dict(),
            name=dict(required=True),
            content_type=dict(
                required=True,
                choices=['docker', 'ostree', 'yum', 'puppet', 'file', 'deb']),
            url=dict(),
            gpg_key=dict(),
            docker_upstream_name=dict(),
            download_policy=dict(
                choices=['background', 'immediate', 'on_demand']),
            state=dict(default='present',
                       choices=['present_with_defaults', 'present', 'absent']),
        ),
        supports_check_mode=True,
    )

    (server_params, entity_dict, state) = module.parse_params()

    if entity_dict[
            'content_type'] != 'docker' and 'docker_upstream_name' in entity_dict:
        module.fail_json(
            msg=
            "docker_upstream_name should not be set unless content_type: docker"
        )

    try:
        (server_url, username, password, verify_ssl) = server_params
        create_server(server_url, (username, password), verify_ssl)
    except Exception as e:
        module.fail_json(msg="Failed to connect to Foreman server: %s " % e)

    ping_server(module)

    entity_dict['organization'] = find_organization(
        module, name=entity_dict['organization'])

    entity_dict['product'] = find_product(
        module,
        name=entity_dict['product'],
        organization=entity_dict['organization'])

    if 'gpg_key' in entity_dict:
        entity_dict['gpg_key'] = find_content_credential(
            module,
            name=entity_dict['gpg_key'],
            organization=entity_dict['organization'])

    entity = find_repository(module,
                             name=entity_dict['name'],
                             product=entity_dict['product'],
                             failsafe=True)

    entity_dict = sanitize_entity_dict(entity_dict, name_map)

    changed = naildown_entity_state(Repository, entity_dict, entity, state,
                                    module)

    module.exit_json(changed=changed)
def main():
    module = ForemanEntityAnsibleModule(
        argument_spec=dict(
            name=dict(required=True),
            description=dict(),
            organization=dict(required=True),
            interval=dict(choices=['hourly', 'daily', 'weekly', 'custom cron'],
                          required=True),
            enabled=dict(type='bool', required=True),
            sync_date=dict(required=True),
            cron_expression=dict(),
            products=dict(type='list'),
        ),
        required_if=[
            ['interval', 'custom cron', ['cron_expression']],
        ],
    )

    (entity_dict, state) = module.parse_params()

    if entity_dict['interval'] != 'custom cron':
        if 'cron_expression' in entity_dict:
            module.fail_json(
                msg=
                '"cron_expression" cannot be combined with "interval"!="custom cron".'
            )

    module.connect()

    entity_dict['organization'] = find_organization(
        module, entity_dict['organization'])
    products = entity_dict.pop('products', None)

    sync_plan = find_sync_plan(module,
                               entity_dict['name'],
                               entity_dict['organization'],
                               failsafe=True)

    entity_dict = sanitize_entity_dict(entity_dict, name_map)

    changed, sync_plan = naildown_entity(SyncPlan, entity_dict, sync_plan,
                                         state, module)

    if products is not None:
        products = find_products(module, products, entity_dict['organization'])
        desired_product_ids = set(p.id for p in products)
        current_product_ids = set(p.id for p in sync_plan.product)

        if desired_product_ids != current_product_ids:
            if not module.check_mode:
                product_ids_to_add = desired_product_ids - current_product_ids
                if product_ids_to_add:
                    sync_plan.add_products(
                        data={'product_ids': list(product_ids_to_add)})
                product_ids_to_remove = current_product_ids - desired_product_ids
                if product_ids_to_remove:
                    sync_plan.remove_products(
                        data={'product_ids': list(product_ids_to_remove)})
            changed = True

    module.exit_json(changed=changed)
Example #21
0
def main():
    module = ForemanAnsibleModule(
        argument_spec=dict(
            name=dict(required=True),
            description=dict(),
            repositories=dict(type='list', default=[]),
            inclusion=dict(type='bool', default=False),
            content_view=dict(required=True),
            filter_type=dict(required=True, choices=['rpm', 'package_group', 'erratum', 'docker']),
            organization=dict(required=True),
            filter_state=dict(default='present', choices=['present', 'absent']),
            rule_state=dict(default='present', choices=['present', 'absent']),
            rule_name=dict(aliases=['package_name', 'package_group', 'tag']),
            date_type=dict(default='updated', choices=['issued', 'updated']),
            end_date=dict(),
            errata_id=dict(),
            max_version=dict(),
            min_version=dict(),
            start_date=dict(),
            types=dict(default=["bugfix", "enhancement", "security"], type='list'),
            version=dict(),
        ),
        supports_check_mode=False,
    )

    entity_dict = module.parse_params()
    filter_state = entity_dict.pop('filter_state')
    rule_state = entity_dict.pop('rule_state')

    module.connect()

    organization = find_organization(module, name=entity_dict.pop('organization'))
    entity_dict['content_view'] = find_content_view(module, name=entity_dict['content_view'], organization=organization)
    if len(entity_dict['repositories']) > 0:
        entity_dict['repositories'] = find_repositories(module, entity_dict['repositories'], organization)

    content_view_filter_entity = find_content_view_filter(module, name=entity_dict['name'], content_view=entity_dict['content_view'], failsafe=True)
    content_view_filter_dict = sanitize_entity_dict(entity_dict, content_filter_map)

    content_view_filter_changed = naildown_entity_state(AbstractContentViewFilter, content_view_filter_dict, content_view_filter_entity, filter_state, module)

    if entity_dict['filter_type'] == 'erratum':
        entity_dict['rule_name'] = None
    elif 'rule_name' not in entity_dict:
        entity_dict['rule_name'] = entity_dict['name']

    # Find content_view_filter again as it may have just been created
    entity_dict['content_view_filter'] = find_content_view_filter(module, name=entity_dict['name'], content_view=entity_dict['content_view'], failsafe=True)

    if entity_dict['content_view_filter'] is not None:
        if 'errata_id' in entity_dict:
            rule_map = content_filter_rule_erratum_id_map
            entity_dict['errata'] = find_errata(module, id=entity_dict['errata_id'], organization=organization)
            content_view_filter_rule_entity = find_content_view_filter_rule(module, content_view_filter=entity_dict['content_view_filter'],
                                                                            errata=entity_dict['errata'], failsafe=True)
        else:
            rule_map = globals()['content_filter_rule_%s_map' % (entity_dict['filter_type'])]
            content_view_filter_rule_entity = find_content_view_filter_rule(module, content_view_filter=entity_dict['content_view_filter'],
                                                                            name=entity_dict['rule_name'], failsafe=True)

        if entity_dict['filter_type'] == 'package_group':
            entity_dict['uuid'] = find_package_group(module, name=entity_dict['rule_name']).uuid

        content_view_filter_rule_dict = sanitize_entity_dict(entity_dict, rule_map)
        check_missing = ['min_version', 'max_version', 'version', 'start_date', 'end_date', 'architecture', 'date_type']
        content_view_filter_rule_changed = naildown_entity_state(ContentViewFilterRule, content_view_filter_rule_dict, content_view_filter_rule_entity,
                                                                 rule_state, module, check_missing)
        changed = content_view_filter_changed or content_view_filter_rule_changed
    else:
        changed = content_view_filter_changed

    module.exit_json(changed=changed)
def main():
    module = KatelloEntityAnsibleModule(
        argument_spec=dict(
            name=dict(required=True),
            composite=dict(type='bool', default=False),
            auto_publish=dict(type='bool', default=False),
            components=dict(type='list'),
            repositories=dict(type='list'),
            state=dict(default='present',
                       choices=['present_with_defaults', 'present', 'absent']),
        ),
        mutually_exclusive=[['repositories', 'components']],
    )

    (entity_dict, state) = module.parse_params()

    module.connect()

    entity_dict['organization'] = find_organization(
        module, name=entity_dict['organization'])
    if 'repositories' in entity_dict and not entity_dict['composite']:
        entity_dict['repositories'] = find_repositories(
            module, entity_dict['repositories'], entity_dict['organization'])

    content_view_entity = find_content_view(
        module,
        name=entity_dict['name'],
        organization=entity_dict['organization'],
        failsafe=True)
    content_view_dict = sanitize_entity_dict(entity_dict, name_map)

    changed, content_view_entity = naildown_entity(ContentView,
                                                   content_view_dict,
                                                   content_view_entity, state,
                                                   module)

    # only update CVC's of newly created or updated CCV's
    if state == 'present' or (state == 'present_with_defaults' and changed):
        current_cvcs = []
        if hasattr(content_view_entity, 'content_view_component'):
            current_cvcs = [
                cvc.read()
                for cvc in content_view_entity.content_view_component
            ]
        if 'components' in entity_dict and content_view_entity.composite:
            for component in entity_dict['components']:
                cvc = component.copy()
                cvc['content_view'] = find_content_view(
                    module,
                    name=component['content_view'],
                    organization=entity_dict['organization'])
                cvc_matched = None
                for _cvc in current_cvcs:
                    if _cvc.content_view.id == cvc['content_view'].id:
                        cvc_matched = _cvc
                force_update = list()
                if 'version' in component:
                    cvc['version'] = find_content_view_version(
                        module,
                        cvc['content_view'],
                        version=component['version'])
                    cvc['latest'] = False
                    if cvc_matched and cvc_matched.latest:
                        # When changing to latest=False & version is the latest we must send 'content_view_version' to the server
                        force_update.append('content_view_version')
                if cvc_matched:
                    cvc['composite_content_view'] = content_view_entity
                    cvc_dict = sanitize_entity_dict(cvc, cvc_map)
                    cvc_changed = naildown_entity_state(
                        ContentViewComponent,
                        cvc_dict,
                        cvc_matched,
                        'present',
                        module,
                        force_update=force_update)
                    current_cvcs.remove(cvc_matched)
                    if cvc_changed:
                        changed = cvc_changed
                else:
                    for attr in ['latest', 'version']:
                        if attr not in cvc:
                            cvc[attr] = None
                    ContentViewComponent(
                        composite_content_view=content_view_entity,
                        content_view=cvc['content_view'],
                        latest=cvc['latest'],
                        content_view_version=cvc['version']).add()
                    changed = True
        for cvc in current_cvcs:
            # desired cvcs have already been updated and removed from `current_cvcs`
            cvc.remove()
            changed = True

    module.exit_json(changed=changed)
Example #23
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            server_url=dict(required=True),
            username=dict(required=True, no_log=True),
            password=dict(required=True, no_log=True),
            verify_ssl=dict(type='bool', default=True),
            name=dict(required=True),
            new_name=dict(),
            organization=dict(required=True),
            lifecycle_environment=dict(),
            content_view=dict(),
            subscriptions=dict(type='list'),
            content_overrides=dict(type='list'),
            auto_attach=dict(type='bool', default=True),
            state=dict(default='present',
                       choices=[
                           'present', 'present_with_defaults', 'absent',
                           'copied'
                       ]),
        ),
        supports_check_mode=True,
        required_if=[
            ['state', 'copied', ['new_name']],
        ],
    )

    if has_import_error:
        module.fail_json(msg=import_error_msg)

    entity_dict = dict([(k, v) for (k, v) in module.params.items()
                        if v is not None])

    server_url = entity_dict.pop('server_url')
    username = entity_dict.pop('username')
    password = entity_dict.pop('password')
    verify_ssl = entity_dict.pop('verify_ssl')
    state = entity_dict.pop('state')

    try:
        create_server(server_url, (username, password), verify_ssl)
    except Exception as e:
        module.fail_json(msg="Failed to connect to Foreman server: %s " % e)

    ping_server(module)

    entity_dict['organization'] = find_organization(
        module, name=entity_dict['organization'])
    if 'lifecycle_environment' in entity_dict:
        entity_dict['lifecycle_environment'] = find_lifecycle_environment(
            module, entity_dict['lifecycle_environment'],
            entity_dict['organization'])

    if 'content_view' in entity_dict:
        entity_dict['content_view'] = find_content_view(
            module, entity_dict['content_view'], entity_dict['organization'])

    activation_key_dict = sanitize_entity_dict(entity_dict, name_map)
    activation_key_entity = find_activation_key(
        module,
        name=entity_dict['name'],
        organization=entity_dict['organization'],
        failsafe=True)

    try:
        changed, activation_key_entity = naildown_entity(
            ActivationKey, activation_key_dict, activation_key_entity, state,
            module)

        # only update subscriptions of newly created or updated AKs
        # copied keys inherit the subscriptions of the origin, so one would not have to specify them again
        # deleted keys don't need subscriptions anymore either
        if state == 'present' or (state == 'present_with_defaults'
                                  and changed):
            if 'subscriptions' in entity_dict:
                subscriptions = entity_dict['subscriptions']
                desired_subscription_ids = map(
                    lambda s: s.id,
                    find_subscriptions(module, subscriptions,
                                       entity_dict['organization']))
                current_subscriptions = [
                    Subscription(**result)
                    for result in Subscription().search_normalize(
                        activation_key_entity.subscriptions()['results'])
                ]
                current_subscription_ids = map(lambda s: s.id,
                                               current_subscriptions)

                if set(desired_subscription_ids) != set(
                        current_subscription_ids):
                    if not module.check_mode:
                        for subscription_id in set(
                                desired_subscription_ids) - set(
                                    current_subscription_ids):
                            activation_key_entity.add_subscriptions(
                                data={
                                    'quantity': 1,
                                    'subscription_id': subscription_id
                                })
                        for subscription_id in set(
                                current_subscription_ids) - set(
                                    desired_subscription_ids):
                            activation_key_entity.remove_subscriptions(
                                data={'subscription_id': subscription_id})
                    changed = True

            if 'content_overrides' in entity_dict:
                content_overrides = entity_dict['content_overrides']
                product_content = activation_key_entity.product_content()
                current_content_overrides = set()
                for product in product_content['results']:
                    if product['enabled_content_override'] is not None:
                        current_content_overrides.add(
                            (product['content']['label'],
                             product['enabled_content_override']))
                desired_content_overrides = set()
                for product in content_overrides:
                    desired_content_overrides.add(
                        (product['label'],
                         override_to_boolnone(product['override'])))

                if desired_content_overrides != current_content_overrides:
                    if not module.check_mode:
                        for (
                                label, override
                        ) in current_content_overrides - desired_content_overrides:
                            activation_key_entity.content_override(
                                data={
                                    'content_override': {
                                        'content_label': label,
                                        'value': 'default'
                                    }
                                })
                        for (
                                label, override
                        ) in desired_content_overrides - current_content_overrides:
                            activation_key_entity.content_override(
                                data={
                                    'content_override': {
                                        'content_label':
                                        label,
                                        'value':
                                        str(override_to_boolnone(
                                            override)).lower()
                                    }
                                })
                    changed = True

        module.exit_json(changed=changed)
    except Exception as e:
        module.fail_json(msg=e)
def main():
    module = KatelloEntityAnsibleModule(
        argument_spec=dict(
            name=dict(required=True),
            new_name=dict(),
            lifecycle_environment=dict(),
            content_view=dict(),
            subscriptions=dict(type='list'),
            host_collections=dict(type='list'),
            content_overrides=dict(type='list'),
            auto_attach=dict(type='bool', default=True),
            state=dict(default='present',
                       choices=[
                           'present', 'present_with_defaults', 'absent',
                           'copied'
                       ]),
        ),
        supports_check_mode=True,
        required_if=[
            ['state', 'copied', ['new_name']],
        ],
    )

    (entity_dict, state) = module.parse_params()

    module.connect()

    entity_dict['organization'] = find_organization(
        module, name=entity_dict['organization'])
    if 'lifecycle_environment' in entity_dict:
        entity_dict['lifecycle_environment'] = find_lifecycle_environment(
            module, entity_dict['lifecycle_environment'],
            entity_dict['organization'])

    if 'content_view' in entity_dict:
        entity_dict['content_view'] = find_content_view(
            module, entity_dict['content_view'], entity_dict['organization'])

    if 'host_collections' in entity_dict:
        entity_dict['host_collections'] = find_host_collections(
            module, entity_dict['host_collections'],
            entity_dict['organization'])

    activation_key_entity = find_activation_key(
        module,
        name=entity_dict['name'],
        organization=entity_dict['organization'],
        failsafe=True)

    activation_key_dict = sanitize_entity_dict(entity_dict, name_map)

    try:
        changed, activation_key_entity = naildown_entity(
            ActivationKey, activation_key_dict, activation_key_entity, state,
            module)

        # only update subscriptions of newly created or updated AKs
        # copied keys inherit the subscriptions of the origin, so one would not have to specify them again
        # deleted keys don't need subscriptions anymore either
        if state == 'present' or (state == 'present_with_defaults'
                                  and changed):
            if 'subscriptions' in entity_dict:
                subscriptions = entity_dict['subscriptions']
                desired_subscription_ids = set(
                    s.id for s in find_subscriptions(
                        module, subscriptions, entity_dict['organization']))
                current_subscriptions = [
                    Subscription(**result)
                    for result in Subscription().search_normalize(
                        activation_key_entity.subscriptions()['results'])
                ]
                current_subscription_ids = set(s.id
                                               for s in current_subscriptions)

                if desired_subscription_ids != current_subscription_ids:
                    if not module.check_mode:
                        for subscription_id in (desired_subscription_ids -
                                                current_subscription_ids):
                            activation_key_entity.add_subscriptions(
                                data={
                                    'quantity': 1,
                                    'subscription_id': subscription_id
                                })
                        for subscription_id in (current_subscription_ids -
                                                desired_subscription_ids):
                            activation_key_entity.remove_subscriptions(
                                data={'subscription_id': subscription_id})
                    changed = True

            if 'content_overrides' in entity_dict:
                content_overrides = entity_dict['content_overrides']
                product_content = activation_key_entity.product_content()
                current_content_overrides = set(
                    (product['content']['label'],
                     product['enabled_content_override'])
                    for product in product_content['results']
                    if product['enabled_content_override'] is not None)
                desired_content_overrides = set(
                    (product['label'],
                     override_to_boolnone(product['override']))
                    for product in content_overrides)

                if desired_content_overrides != current_content_overrides:
                    if not module.check_mode:
                        for (
                                label, override
                        ) in current_content_overrides - desired_content_overrides:
                            activation_key_entity.content_override(
                                data={
                                    'content_override': {
                                        'content_label': label,
                                        'value': 'default'
                                    }
                                })
                        for (
                                label, override
                        ) in desired_content_overrides - current_content_overrides:
                            activation_key_entity.content_override(
                                data={
                                    'content_override': {
                                        'content_label': label,
                                        'value': str(override).lower()
                                    }
                                })
                    changed = True

        module.exit_json(changed=changed)
    except Exception as e:
        module.fail_json(msg=e)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            server_url=dict(required=True),
            username=dict(required=True, no_log=True),
            password=dict(required=True, no_log=True),
            verify_ssl=dict(type='bool', default=True),
            name=dict(required=True),
            description=dict(),
            repositories=dict(type='list', default=[]),
            inclusion=dict(type='bool', default=False),
            content_view=dict(required=True),
            filter_type=dict(
                required=True,
                choices=['rpm', 'package_group', 'erratum', 'docker']),
            organization=dict(required=True),
            filter_state=dict(default='present', choices=['present',
                                                          'absent']),
            rule_state=dict(default='present', choices=['present', 'absent']),
            rule_name=dict(aliases=['package_name', 'package_group', 'tag']),
            date_type=dict(default='updated', choices=['issued', 'updated']),
            end_date=dict(),
            errata_id=dict(),
            max_version=dict(),
            min_version=dict(),
            start_date=dict(),
            types=dict(default=["bugfix", "enhancement", "security"],
                       type='list'),
            version=dict(),
        ),
        supports_check_mode=False,
    )

    if has_import_error:
        module.fail_json(msg=import_error_msg)

    entity_dict = dict([(k, v) for (k, v) in module.params.items()
                        if v is not None])

    server_url = entity_dict.pop('server_url')
    username = entity_dict.pop('username')
    password = entity_dict.pop('password')
    verify_ssl = entity_dict.pop('verify_ssl')
    filter_state = entity_dict.pop('filter_state')
    rule_state = entity_dict.pop('rule_state')

    try:
        create_server(server_url, (username, password), verify_ssl)
    except Exception as e:
        module.fail_json(msg="Failed to connect to Foreman server: %s " % e)

    ping_server(module)

    organization = find_organization(module,
                                     name=entity_dict.pop('organization'))
    entity_dict['content_view'] = find_content_view(
        module, name=entity_dict['content_view'], organization=organization)
    if len(entity_dict['repositories']) > 0:
        entity_dict['repositories'] = find_repositories(
            module, entity_dict['repositories'], organization)

    content_view_filter_entity = find_content_view_filter(
        module,
        name=entity_dict['name'],
        content_view=entity_dict['content_view'],
        failsafe=True)
    content_view_filter_dict = sanitize_entity_dict(entity_dict,
                                                    content_filter_map)

    content_view_filter_changed = naildown_entity_state(
        AbstractContentViewFilter, content_view_filter_dict,
        content_view_filter_entity, filter_state, module)

    if entity_dict['filter_type'] == 'erratum':
        entity_dict['rule_name'] = None
    elif 'rule_name' not in entity_dict:
        entity_dict['rule_name'] = entity_dict['name']

    # Find content_view_filter again as it may have just been created
    entity_dict['content_view_filter'] = find_content_view_filter(
        module,
        name=entity_dict['name'],
        content_view=entity_dict['content_view'],
        failsafe=True)

    if entity_dict['content_view_filter'] is not None:
        if 'errata_id' in entity_dict:
            rule_map = content_filter_rule_erratum_id_map
            entity_dict['errata'] = find_errata(module,
                                                id=entity_dict['errata_id'],
                                                organization=organization)
            content_view_filter_rule_entity = find_content_view_filter_rule(
                module,
                content_view_filter=entity_dict['content_view_filter'],
                errata=entity_dict['errata'],
                failsafe=True)
        else:
            rule_map = globals()['content_filter_rule_%s_map' %
                                 (entity_dict['filter_type'])]
            content_view_filter_rule_entity = find_content_view_filter_rule(
                module,
                content_view_filter=entity_dict['content_view_filter'],
                name=entity_dict['rule_name'],
                failsafe=True)

        if entity_dict['filter_type'] == 'package_group':
            entity_dict['uuid'] = find_package_group(
                module, name=entity_dict['rule_name']).uuid

        content_view_filter_rule_dict = sanitize_entity_dict(
            entity_dict, rule_map)
        check_missing = [
            'min_version', 'max_version', 'version', 'start_date', 'end_date',
            'architecture', 'date_type'
        ]
        content_view_filter_rule_changed = naildown_entity_state(
            ContentViewFilterRule, content_view_filter_rule_dict,
            content_view_filter_rule_entity, rule_state, module, check_missing)
        changed = content_view_filter_changed or content_view_filter_rule_changed
    else:
        changed = content_view_filter_changed

    module.exit_json(changed=changed)