def main():
    module = KatelloEntityAnsibleModule(
        entity_spec=dict(
            name=dict(required=True),
            description=dict(),
            interval=dict(choices=['hourly', 'daily', 'weekly', 'custom cron'], required=True),
            enabled=dict(type='bool', required=True),
            sync_date=dict(required=True),
            cron_expression=dict(),
            state=dict(default='present', choices=['present_with_defaults', 'present', 'absent']),
        ),
        argument_spec=dict(
            products=dict(type='list', elements='str'),
        ),
        required_if=[
            ['interval', 'custom cron', ['cron_expression']],
        ],
    )

    entity_dict = module.clean_params()

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

    with module.api_connection():
        entity_dict, scope = module.handle_organization_param(entity_dict)

        entity = module.find_resource_by_name('sync_plans', name=entity_dict['name'], params=scope, failsafe=True)

        products = entity_dict.pop('products', None)

        sync_plan = module.ensure_entity('sync_plans', entity_dict, entity, params=scope)

        if not (module.desired_absent or module.state == 'present_with_defaults') and products is not None:
            products = module.find_resources_by_name('products', products, params=scope, thin=True)
            desired_product_ids = set(product['id'] for product in products)
            current_product_ids = set(product['id'] for product in entity['products']) if entity else set()

            module.record_before('sync_plans/products', {'id': sync_plan['id'], 'product_ids': current_product_ids})
            module.record_after('sync_plans/products', {'id': sync_plan['id'], 'product_ids': desired_product_ids})
            module.record_after_full('sync_plans/products', {'id': sync_plan['id'], 'product_ids': desired_product_ids})

            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:
                        payload = {
                            'id': sync_plan['id'],
                            'product_ids': list(product_ids_to_add),
                        }
                        payload.update(scope)
                        module.resource_action('sync_plans', 'add_products', payload)
                    product_ids_to_remove = current_product_ids - desired_product_ids
                    if product_ids_to_remove:
                        payload = {
                            'id': sync_plan['id'],
                            'product_ids': list(product_ids_to_remove),
                        }
                        payload.update(scope)
                        module.resource_action('sync_plans', 'remove_products', payload)
                else:
                    module.set_changed()
Пример #2
0
def main():
    module = KatelloEntityAnsibleModule(
        entity_spec=dict(
            name=dict(required=True),
            description=dict(),
            composite=dict(type='bool', default=False),
            auto_publish=dict(type='bool', default=False),
            components=dict(type='nested_list', entity_spec=cvc_entity_spec),
            repositories=dict(type='entity_list', flat_name='repository_ids', elements='dict', options=dict(
                name=dict(required=True),
                product=dict(required=True),
            )),
        ),
        argument_spec=dict(
            state=dict(default='present', choices=['present_with_defaults', 'present', 'absent']),
        ),
        mutually_exclusive=[['repositories', 'components']],
    )

    entity_dict = module.clean_params()

    # components is None when we're managing a CCV but don't want to adjust its components
    components = entity_dict.pop('components', None)
    if components:
        for component in components:
            if not component['latest'] and component.get('content_view_version') is None:
                module.fail_json(msg="Content View Component must either have latest=True or provide a Content View Version.")

    module.connect()

    entity_dict['organization'] = module.find_resource_by_name('organizations', entity_dict['organization'], thin=True)
    scope = {'organization_id': entity_dict['organization']['id']}
    if not module.desired_absent:
        if 'repositories' in entity_dict:
            if entity_dict['composite']:
                module.fail_json(msg="Repositories cannot be parts of a Composite Content View.")
            else:
                repositories = []
                for repository in entity_dict['repositories']:
                    product = module.find_resource_by_name('products', repository['product'], params=scope, thin=True)
                    repositories.append(module.find_resource_by_name('repositories', repository['name'], params={'product_id': product['id']}, thin=True))
                entity_dict['repositories'] = repositories

    entity = module.find_resource_by_name('content_views', name=entity_dict['name'], params=scope, failsafe=True)

    changed, content_view_entity = module.ensure_entity('content_views', entity_dict, entity, params=scope)

    # only update CVC's of newly created or updated CV's that are composite if components are specified
    update_dependent_entities = (module.state == 'present' or (module.state == 'present_with_defaults' and changed))
    if update_dependent_entities and content_view_entity['composite'] and components is not None:
        if not changed:
            content_view_entity['content_view_components'] = entity['content_view_components']
        current_cvcs = content_view_entity.get('content_view_components', [])

        # only record a subset of data
        current_cvcs_record = [{"id": cvc['id'], "content_view_id": cvc['content_view']['id'],
                                "content_view_version_id": cvc['content_view_version']['id'],
                                "latest": cvc['latest']}
                               for cvc in current_cvcs]
        module.record_before('content_views/components', {'composite_content_view_id': content_view_entity['id'],
                                                          'content_view_components': current_cvcs_record})
        final_cvcs_record = copy.deepcopy(current_cvcs_record)

        components_to_add = []
        ccv_scope = {'composite_content_view_id': content_view_entity['id']}
        for component in components:
            cvc = {
                'content_view': module.find_resource_by_name('content_views', name=component['content_view'], params=scope),
                'latest': component['latest'],
            }
            cvc_matched = next((item for item in current_cvcs if item['content_view']['id'] == cvc['content_view']['id']), None)
            if not cvc['latest']:
                search = "content_view_id={0},version={1}".format(cvc['content_view']['id'], component['content_view_version'])
                cvc['content_view_version'] = module.find_resource('content_view_versions', search=search, thin=True)
                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
                    # Let's fake, it wasn't there...
                    cvc_matched.pop('content_view_version', None)
                    cvc_matched.pop('content_view_version_id', None)
            if cvc_matched:
                changed |= module.ensure_entity_state(
                    'content_view_components', cvc, cvc_matched, state='present', entity_spec=cvc_entity_spec, params=ccv_scope)
                current_cvcs.remove(cvc_matched)
            else:
                cvc['content_view_id'] = cvc.pop('content_view')['id']
                if 'content_view_version' in cvc:
                    cvc['content_view_version_id'] = cvc.pop('content_view_version')['id']
                components_to_add.append(cvc)

        if components_to_add:
            payload = {
                'composite_content_view_id': content_view_entity['id'],
                'components': components_to_add,
            }
            module.resource_action('content_view_components', 'add_components', payload)
            changed = True

            final_cvcs_record.extend(components_to_add)

        # desired cvcs have already been updated and removed from `current_cvcs`
        components_to_remove = [item['id'] for item in current_cvcs]
        if components_to_remove:
            payload = {
                'composite_content_view_id': content_view_entity['id'],
                'component_ids': components_to_remove,
            }
            module.resource_action('content_view_components', 'remove_components', payload)
            changed = True

            final_cvcs_record = [item for item in final_cvcs_record if item['id'] not in components_to_remove]

        module.record_after('content_views/components', {'composite_content_view_id': content_view_entity['id'],
                                                         'content_view_components': final_cvcs_record})
        module.record_after_full('content_views/components', {'composite_content_view_id': content_view_entity['id'],
                                                              'content_view_components': final_cvcs_record})

    module.exit_json(changed=changed)
Пример #3
0
def main():
    module = KatelloEntityAnsibleModule(
        entity_spec=dict(
            name=dict(required=True),
            new_name=dict(),
            lifecycle_environment=dict(type='entity',
                                       flat_name='environment_id'),
            content_view=dict(type='entity'),
            host_collections=dict(type='entity_list'),
            auto_attach=dict(type='bool'),
            release_version=dict(),
            service_level=dict(
                choices=['Self-Support', 'Standard', 'Premium']),
            max_hosts=dict(type='int'),
            unlimited_hosts=dict(type='bool'),
            purpose_usage=dict(),
            purpose_role=dict(),
            purpose_addons=dict(type='list', elements='str'),
        ),
        argument_spec=dict(
            subscriptions=dict(
                type='list',
                elements='dict',
                options=dict(
                    name=dict(),
                    pool_id=dict(),
                ),
                required_one_of=[['name', 'pool_id']],
                mutually_exclusive=[['name', 'pool_id']],
            ),
            content_overrides=dict(
                type='list',
                elements='dict',
                options=dict(
                    label=dict(required=True),
                    override=dict(required=True,
                                  choices=['enabled', 'disabled', 'default']),
                )),
            state=dict(default='present',
                       choices=[
                           'present', 'present_with_defaults', 'absent',
                           'copied'
                       ]),
        ),
        required_if=[
            ['state', 'copied', ['new_name']],
            ['unlimited_hosts', False, ['max_hosts']],
        ],
    )

    entity_dict = module.clean_params()

    with module.api_connection():
        entity_dict, scope = module.handle_organization_param(entity_dict)

        if not module.desired_absent:
            if 'lifecycle_environment' in entity_dict:
                entity_dict[
                    'lifecycle_environment'] = module.find_resource_by_name(
                        'lifecycle_environments',
                        entity_dict['lifecycle_environment'],
                        params=scope,
                        thin=True)

            if 'content_view' in entity_dict:
                entity_dict['content_view'] = module.find_resource_by_name(
                    'content_views',
                    entity_dict['content_view'],
                    params=scope,
                    thin=True)

        entity = module.find_resource_by_name('activation_keys',
                                              name=entity_dict['name'],
                                              params=scope,
                                              failsafe=True)

        if module.state == 'copied':
            new_entity = module.find_resource_by_name(
                'activation_keys',
                name=entity_dict['new_name'],
                params=scope,
                failsafe=True)
            if new_entity is not None:
                module.warn("Activation Key '{0}' already exists.".format(
                    entity_dict['new_name']))
                module.exit_json()

        subscriptions = entity_dict.pop('subscriptions', None)
        content_overrides = entity_dict.pop('content_overrides', None)
        host_collections = entity_dict.pop('host_collections', None)
        activation_key = module.ensure_entity('activation_keys',
                                              entity_dict,
                                              entity,
                                              params=scope)

        # 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 module.state == 'present' or (
                module.state == 'present_with_defaults' and module.changed):
            # the auto_attach, release_version and service_level parameters can only be set on an existing AK with an update,
            # not during create, so let's force an update. see https://projects.theforeman.org/issues/27632 for details
            if any(key in entity_dict for key in [
                    'auto_attach', 'release_version', 'service_level'
            ]) and module.changed:
                activation_key = module.ensure_entity('activation_keys',
                                                      entity_dict,
                                                      activation_key,
                                                      params=scope)

            ak_scope = {'activation_key_id': activation_key['id']}
            if subscriptions is not None:
                desired_subscriptions = []
                for subscription in subscriptions:
                    if subscription['name'] is not None and subscription[
                            'pool_id'] is None:
                        desired_subscriptions.append(
                            module.find_resource_by_name('subscriptions',
                                                         subscription['name'],
                                                         params=scope,
                                                         thin=True))
                    if subscription['pool_id'] is not None:
                        desired_subscriptions.append(
                            module.find_resource_by_id('subscriptions',
                                                       subscription['pool_id'],
                                                       params=scope,
                                                       thin=True))
                desired_subscription_ids = set(
                    item['id'] for item in desired_subscriptions)
                current_subscriptions = module.list_resource(
                    'subscriptions', params=ak_scope) if entity else []
                current_subscription_ids = set(
                    item['id'] for item in current_subscriptions)

                if desired_subscription_ids != current_subscription_ids:
                    module.record_before(
                        'activation_keys/subscriptions', {
                            'id': activation_key['id'],
                            'subscriptions': current_subscription_ids
                        })
                    module.record_after(
                        'activation_keys/subscriptions', {
                            'id': activation_key['id'],
                            'subscriptions': desired_subscription_ids
                        })
                    module.record_after_full(
                        'activation_keys/subscriptions', {
                            'id': activation_key['id'],
                            'subscriptions': desired_subscription_ids
                        })

                    ids_to_remove = current_subscription_ids - desired_subscription_ids
                    if ids_to_remove:
                        payload = {
                            'id':
                            activation_key['id'],
                            'subscriptions': [{
                                'id': item
                            } for item in ids_to_remove],
                        }
                        payload.update(scope)
                        module.resource_action('activation_keys',
                                               'remove_subscriptions', payload)

                    ids_to_add = desired_subscription_ids - current_subscription_ids
                    if ids_to_add:
                        payload = {
                            'id':
                            activation_key['id'],
                            'subscriptions': [{
                                'id': item,
                                'quantity': 1
                            } for item in ids_to_add],
                        }
                        payload.update(scope)
                        module.resource_action('activation_keys',
                                               'add_subscriptions', payload)

            if content_overrides is not None:
                if entity:
                    product_content = module.resource_action(
                        'activation_keys',
                        'product_content',
                        params={
                            'id': activation_key['id'],
                            'content_access_mode_all': True
                        },
                        ignore_check_mode=True,
                    )
                else:
                    product_content = {'results': []}
                current_content_overrides = {
                    product['content']['label']:
                    product['enabled_content_override']
                    for product in product_content['results']
                    if product['enabled_content_override'] is not None
                }
                desired_content_overrides = {
                    product['label']: override_to_boolnone(product['override'])
                    for product in content_overrides
                }
                changed_content_overrides = []

                module.record_before(
                    'activation_keys/content_overrides', {
                        'id': activation_key['id'],
                        'content_overrides': current_content_overrides.copy()
                    })
                module.record_after(
                    'activation_keys/content_overrides', {
                        'id': activation_key['id'],
                        'content_overrides': desired_content_overrides
                    })
                module.record_after_full(
                    'activation_keys/content_overrides', {
                        'id': activation_key['id'],
                        'content_overrides': desired_content_overrides
                    })

                for label, override in desired_content_overrides.items():
                    if override is not None and override != current_content_overrides.pop(
                            label, None):
                        changed_content_overrides.append({
                            'content_label': label,
                            'value': override
                        })
                for label in current_content_overrides.keys():
                    changed_content_overrides.append({
                        'content_label': label,
                        'remove': True
                    })

                if changed_content_overrides:
                    payload = {
                        'id': activation_key['id'],
                        'content_overrides': changed_content_overrides,
                    }
                    module.resource_action('activation_keys',
                                           'content_override', payload)

            if host_collections is not None:
                if not entity:
                    current_host_collection_ids = set()
                elif 'host_collection_ids' in activation_key:
                    current_host_collection_ids = set(
                        activation_key['host_collection_ids'])
                else:
                    current_host_collection_ids = set(
                        item['id']
                        for item in activation_key['host_collections'])
                desired_host_collections = module.find_resources_by_name(
                    'host_collections',
                    host_collections,
                    params=scope,
                    thin=True)
                desired_host_collection_ids = set(
                    item['id'] for item in desired_host_collections)

                if desired_host_collection_ids != current_host_collection_ids:
                    module.record_before(
                        'activation_keys/host_collections', {
                            'id': activation_key['id'],
                            'host_collections': current_host_collection_ids
                        })
                    module.record_after(
                        'activation_keys/host_collections', {
                            'id': activation_key['id'],
                            'host_collections': desired_host_collection_ids
                        })
                    module.record_after_full(
                        'activation_keys/host_collections', {
                            'id': activation_key['id'],
                            'host_collections': desired_host_collection_ids
                        })

                    ids_to_remove = current_host_collection_ids - desired_host_collection_ids
                    if ids_to_remove:
                        payload = {
                            'id': activation_key['id'],
                            'host_collection_ids': list(ids_to_remove),
                        }
                        module.resource_action('activation_keys',
                                               'remove_host_collections',
                                               payload)

                    ids_to_add = desired_host_collection_ids - current_host_collection_ids
                    if ids_to_add:
                        payload = {
                            'id': activation_key['id'],
                            'host_collection_ids': list(ids_to_add),
                        }
                        module.resource_action('activation_keys',
                                               'add_host_collections', payload)