Exemple #1
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 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),
            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),
            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)
def find_prior(module, prior, organization):
    if prior is not None:
        return find_lifecycle_environment(module, prior, organization)
Exemple #6
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)