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)
Beispiel #2
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 = 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 = 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)
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)
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)
Beispiel #7
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)
Beispiel #8
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 = 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)