Esempio n. 1
0
def main(module):
    handle_no_nailgun(module, HAS_NAILGUN_PACKAGE)

    updated_name = module.params.get('updated_name')
    state = module.params.get('state')

    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': module.params.get('name')}

    compute_profile = cement.find_compute_profile(module,
                                                  name=data.get('name'),
                                                  failsafe=True)

    if state == 'present' and updated_name:
        data['name'] = updated_name

    data = sanitize_compute_profile_dict(data)

    changed = cement.naildown_entity_state(nailgun.entities.ComputeProfile,
                                           data, compute_profile, state,
                                           module)

    return changed
Esempio n. 2
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            server_url=dict(required=True),
            username=dict(required=True),
            password=dict(required=True, no_log=True),
            verify_ssl=dict(type='bool', default=True),
            name=dict(),
        ),
        supports_check_mode=True,
    )

    handle_no_nailgun(module, HAS_NAILGUN_PACKAGE)

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

    server_url = params_dict.pop('server_url')
    username = params_dict.pop('username')
    password = params_dict.pop('password')
    verify_ssl = params_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)

    search_params = {k: v for (k, v) in params_dict.items() if k == 'name'}
    entities = find_entities(Setting, **search_params)
    settings = [{key: getattr(entity, value) for (key, value) in name_map.items()}
                for entity in entities]

    module.exit_json(changed=False, settings=settings)
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', 'latest']:
        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
Esempio n. 4
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)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            server_url=dict(required=True),
            username=dict(required=True),
            password=dict(required=True, no_log=True),
            verify_ssl=dict(type='bool', default=True),
            name=dict(required=True),
            description=dict(),
            dns_proxy=dict(),
            locations=dict(type='list'),
            organizations=dict(type='list'),
            state=dict(choices=['present', 'absent'], default='present'),
        ),
        supports_check_mode=True,
    )

    handle_no_nailgun(module, HAS_NAILGUN_PACKAGE)

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

    server_url = domain_dict.pop('server_url')
    username = domain_dict.pop('username')
    password = domain_dict.pop('password')
    verify_ssl = domain_dict.pop('verify_ssl')
    state = domain_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)
    try:
        # Try to find the Domain to work on
        entity = find_domain(module, name=domain_dict['name'], failsafe=True)
    except Exception as e:
        module.fail_json(msg='Failed to find entity: %s ' % e)

    if 'dns_proxy' in domain_dict:
        domain_dict['dns_proxy'] = find_smart_proxy(module,
                                                    domain_dict['dns_proxy'])

    if 'locations' in domain_dict:
        domain_dict['locations'] = find_locations(module,
                                                  domain_dict['locations'])

    if 'organizations' in domain_dict:
        domain_dict['organizations'] = find_organizations(
            module, domain_dict['organizations'])

    domain_dict = sanitize_entity_dict(domain_dict, name_map)

    changed = naildown_entity_state(Domain, domain_dict, entity, state, module)

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

    handle_no_nailgun(module, HAS_NAILGUN_PACKAGE)

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

    server_url = global_parameter_dict.pop('server_url')
    username = global_parameter_dict.pop('username')
    password = global_parameter_dict.pop('password')
    verify_ssl = global_parameter_dict.pop('verify_ssl')
    state = global_parameter_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)
    try:
        entities = find_entities(CommonParameter,
                                 name=global_parameter_dict['name'])
        if len(entities) > 0:
            entity = entities[0]
        else:
            entity = None
    except Exception as e:
        module.fail_json(msg='Failed to find entity: %s ' % e)

    global_parameter_dict = sanitize_global_parameter_dict(
        global_parameter_dict)

    changed = naildown_entity_state(CommonParameter, global_parameter_dict,
                                    entity, state, module)

    module.exit_json(changed=changed)
Esempio n. 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),
            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']),
        ),
        supports_check_mode=True,
    )

    handle_no_nailgun(module, HAS_NAILGUN_PACKAGE)

    server_url = module.params['server_url']
    verify_ssl = module.params['verify_ssl']
    username = module.params['username']
    password = module.params['password']
    product = module.params['product']
    organization = module.params['organization']
    name = module.params['name']
    content_type = module.params['content_type']
    url = module.params['url']
    download_policy = module.params['download_policy']

    server = ServerConfig(url=server_url,
                          auth=(username, password),
                          verify=verify_ssl)
    ng = NailGun(server, entities, module)

    # Lets make an connection to the server with username and password
    try:
        org = entities.Organization(server)
        org.search()
    except Exception as e:
        module.fail_json(msg="Failed to connect to Foreman server: %s " % e)

    try:
        changed = ng.repository(name,
                                content_type,
                                product,
                                organization,
                                url=url,
                                download_policy=download_policy)
        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),
            realm_proxy=dict(type='int', required=True),
            realm_type=dict(required=True,
                            choices=[
                                'Red Hat Identity Management', 'FreeIPA',
                                'Active Directory'
                            ]),
            state=dict(required=True, choices=['present', 'absent']),
        ),
        supports_check_mode=True,
    )

    handle_no_nailgun(module, HAS_NAILGUN_PACKAGE)

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

    server_url = realm_dict.pop('server_url')
    username = realm_dict.pop('username')
    password = realm_dict.pop('password')
    verify_ssl = realm_dict.pop('verify_ssl')
    state = realm_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)
    try:
        entities = find_entities(Realm, name=realm_dict['name'])
        if len(entities) > 0:
            entity = entities[0]
        else:
            entity = None
    except Exception as e:
        module.fail_json(msg='Failed to find entity: %s ' % e)

    realm_dict = sanitize_realm_dict(realm_dict)

    changed = naildown_entity_state(Realm, realm_dict, 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),
        name=dict(required=True),
        organization=dict(required=True),
        interval=dict(required=True),
        enabled=dict(required=True),
        sync_date=dict(required=True),
        products=dict(type='list', default=[]),
    ),
                           supports_check_mode=True)

    handle_no_nailgun(module, HAS_NAILGUN_PACKAGE)

    server_url = module.params['server_url']
    username = module.params['username']
    password = module.params['password']
    verify_ssl = module.params['verify_ssl']
    name = module.params['name']
    organization = module.params['organization']
    interval = module.params['interval']
    enabled = module.params['enabled']
    sync_date = datetime.strptime(module.params['sync_date'],
                                  '%Y-%m-%d %H:%M:%S')
    products = module.params['products']

    server = ServerConfig(url=server_url,
                          auth=(username, password),
                          verify=verify_ssl)
    ng = NailGun(server, entities, module)

    # Lets make an connection to the server with username and password
    try:
        org = entities.Organization(server)
        org.search()
    except Exception as e:
        module.fail_json(msg="Failed to connect to Foreman server: %s " % e)

    try:
        changed = ng.sync_plan(name,
                               organization,
                               interval=interval,
                               enabled=enabled,
                               sync_date=sync_date,
                               products=products)
        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),
                           organization=dict(required=True),
                           from_environment=dict(),
                           version=dict(),
                           to_environment=dict(required=True),
                           force=dict(type='bool'),
                           force_yum_metadata_regeneration=dict(type='bool')),
        required_one_of=[['from_environment', 'version']],
        mutually_exclusive=[['from_environment', 'version']],
        supports_check_mode=True,
    )

    handle_no_nailgun(module, HAS_NAILGUN_PACKAGE)

    set_task_timeout(3600000)  # 60 minutes

    server_url = module.params['server_url']
    username = module.params['username']
    password = module.params['password']
    verify_ssl = module.params['verify_ssl']
    name = module.params['name']
    organization = module.params['organization']
    from_environment = module.params['from_environment']
    version = module.params['version']
    to_environment = module.params['to_environment']
    force = module.params['force']
    force_yum_metadata_regeneration = module.params[
        'force_yum_metadata_regeneration']

    create_server(server_url, (username, password), verify_ssl)
    ping_server(module)

    try:
        changed = content_view_promote(
            module,
            name,
            organization,
            to_environment,
            from_environment=from_environment,
            version=version,
            force=force,
            force_yum_metadata_regeneration=force_yum_metadata_regeneration)
        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),
            organization=dict(required=True),
            lifecycle_environment=dict(),
            content_view=dict(),
            subscriptions=dict(type='list'),
        ),
        supports_check_mode=True,
    )

    handle_no_nailgun(module, HAS_NAILGUN_PACKAGE)

    server_url = module.params['server_url']
    username = module.params['username']
    password = module.params['password']
    verify_ssl = module.params['verify_ssl']
    name = module.params['name']
    organization = module.params['organization']
    lifecycle_environment = module.params['lifecycle_environment']
    content_view = module.params['content_view']
    subscriptions = module.params['subscriptions']

    server = ServerConfig(url=server_url,
                          auth=(username, password),
                          verify=verify_ssl)
    ng = NailGun(server, entities, module)

    # Lets make an connection to the server with username and password
    try:
        org = entities.Organization(server)
        org.search()
    except Exception as e:
        module.fail_json(msg="Failed to connect to Foreman server: %s " % e)

    try:
        changed = ng.activation_key(
            name,
            organization,
            lifecycle_environment=lifecycle_environment,
            content_view=content_view,
            subscriptions=subscriptions)
        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),
            label=dict(),
            description=dict(),
            prior=dict(),
            organization=dict(required=True),
            state=dict(required=True),
        ),
        supports_check_mode=True,
    )

    handle_no_nailgun(module, HAS_NAILGUN_PACKAGE)

    server_url = module.params['server_url']
    username = module.params['username']
    password = module.params['password']
    verify_ssl = module.params['verify_ssl']
    name = module.params['name']
    label = module.params['label'] if module.params['label'] != '' else None
    description = module.params['description']
    prior = None if module.params['prior'] == '' else module.params['prior']
    organization = module.params['organization']
    state = module.params['state']

    create_server(server_url, (username, password), verify_ssl)
    ping_server(module)
    validate_params(module,
                    state,
                    label=label,
                    description=description,
                    prior=prior)

    try:
        changed = lifecycle_environment(module,
                                        name,
                                        organization,
                                        state,
                                        label=label,
                                        description=description,
                                        prior=prior)
        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),
            organization=dict(required=True),
            manifest_path=dict(),
            state=dict(required=True,
                       choices=['absent', 'present', 'refreshed']),
            redhat_repository_url=dict(),
        ),
        required_if=[
            ['state', 'present', ['manifest_path']],
        ],
        supports_check_mode=True,
    )

    handle_no_nailgun(module, HAS_NAILGUN_PACKAGE)

    set_task_timeout(300000)  # 5 minutes

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

    validate_params(module, state=state, manifest_path=manifest_path)

    create_server(server_url, (username, password), verify_ssl)
    ping_server(module)

    try:
        changed = manifest(module,
                           organization,
                           state,
                           manifest_path,
                           redhat_repository_url=redhat_repository_url)
        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),
            src=dict(required=True, type='path', aliases=['file']),
            repository=dict(required=True),
            product=dict(required=True),
            organization=dict(required=True),
        ),
        supports_check_mode=True,
    )

    handle_no_nailgun(module, HAS_NAILGUN_PACKAGE)

    server_url = module.params['server_url']
    username = module.params['username']
    password = module.params['password']
    src = module.params['src']
    repository = module.params['repository']
    product = module.params['product']
    organization = module.params['organization']
    verify_ssl = module.params['verify_ssl']

    server = ServerConfig(url=server_url,
                          auth=(username, password),
                          verify=verify_ssl)
    ng = NailGun(server, entities, module)

    # Lets make an connection to the server with username and password
    try:
        org = entities.Organization(server)
        org.search()
    except Exception as e:
        module.fail_json(msg="Failed to connect to Foreman server: %s " % e)

    try:
        if not module.check_mode:
            ng.upload(src, repository, product, organization)
    except Exception as e:
        module.fail_json(msg=to_native(e))

    module.exit_json(changed=True,
                     result="File successfully uploaded to %s" % repository)
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'),
        ),
        supports_check_mode=True,
    )

    handle_no_nailgun(module, HAS_NAILGUN_PACKAGE)

    server_url = module.params['server_url']
    username = module.params['username']
    password = module.params['password']
    verify_ssl = module.params['verify_ssl']
    name = module.params['name']
    organization = module.params['organization']
    repositories = module.params['repositories']

    server = ServerConfig(url=server_url,
                          auth=(username, password),
                          verify=verify_ssl)
    ng = NailGun(server, entities, module)

    # Lets make an connection to the server with username and password
    try:
        org = entities.Organization(server)
        org.search()
    except Exception as e:
        module.fail_json(msg="Failed to connect to Foreman server: %s " % e)

    kwargs = {}
    if repositories:
        kwargs['repositories'] = repositories

    try:
        changed = ng.content_view(name, organization, **kwargs)
        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),
            password=dict(required=True, no_log=True),
            verify_ssl=dict(type='bool', default=True),
            name=dict(required=True),
            value=dict(),
        ),
        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')
    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 = find_setting(
        module,
        name=entity_dict['name'],
        failsafe=False,
    )

    if 'value' not in entity_dict:
        entity_dict['value'] = entity.default or ""

    entity_dict = sanitize_entity_dict(entity_dict, name_map)

    changed = naildown_entity_state(Setting, entity_dict, entity, 'present', 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),
            name=dict(required=True),
            product=dict(),
            organization=dict(required=True),
            repositories=dict(required=True, type='list'),
            state=dict(required=True, choices=['disabled', 'enabled']),
        ),
        supports_check_mode=True,
    )

    handle_no_nailgun(module, HAS_NAILGUN_PACKAGE)

    server_url = module.params['server_url']
    username = module.params['username']
    password = module.params['password']
    verify_ssl = module.params['verify_ssl']
    name = module.params['name']
    product = module.params['product']
    organization = module.params['organization']
    repositories = module.params['repositories']
    state = module.params['state']

    create_server(server_url, (username, password), verify_ssl)
    ping_server(module)

    try:
        changed = repository_set(module,
                                 name,
                                 organization,
                                 product,
                                 state,
                                 repositories=repositories)
        module.exit_json(changed=changed)
    except Exception as e:
        module.fail_json(msg=e)
Esempio n. 18
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            server_url=dict(required=True),
            username=dict(required=True),
            password=dict(required=True, no_log=True),
            verify_ssl=dict(type='bool', default=True),
            operatingsystem=dict(required=True),
            template_kind=dict(required=True),
            provisioning_template=dict(required=False),
            state=dict(required=True,
                       choices=['present', 'present_with_defaults', 'absent']),
        ),
        required_if=(
            ['state', 'present', ['provisioning_template']],
            ['state', 'present_with_defaults', ['provisioning_template']],
        ),
        supports_check_mode=True,
    )

    handle_no_nailgun(module, HAS_NAILGUN_PACKAGE)

    entity_dict = dict([(k, v) for (k, v) in module.params.iteritems()
                        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)
    os_list = OperatingSystem().search(
        set(), {'search': 'title~"{}"'.format(entity_dict['operatingsystem'])})
    if len(os_list) == 0:
        module.fail_json(msg='Operating system "{}" not found.'.format(
            entity_dict['operatingsystem']))
    if len(os_list) > 1:
        module.fail_json(msg='Provided operating system ({}) is not unique.'.
                         format(entity_dict['operatingsystem']))

    entity_dict['operatingsystem'] = os_list[0]
    entity_dict['template_kind'] = find_entities_by_name(
        TemplateKind, [entity_dict['template_kind']], module)[0]

    entity = find_os_default_template(
        module,
        operatingsystem=entity_dict['operatingsystem'],
        template_kind=entity_dict['template_kind'],
        failsafe=True,
    )

    # Find Provisioning Template
    if 'provisioning_template' in entity_dict:
        if state == 'absent':
            module.fail_json(
                msg='Provisioning template must not be specified for deletion.'
            )
        entity_dict['provisioning_template'] = find_entities_by_name(
            ProvisioningTemplate, [entity_dict['provisioning_template']],
            module)[0]
        if entity_dict['provisioning_template'].template_kind.id != entity_dict[
                'template_kind'].id:
            module.fail_json(msg='Provisioning template kind mismatching.')

    entity_dict = sanitize_os_default_template_dict(entity_dict)

    changed = naildown_entity_state(OSDefaultTemplate, entity_dict, 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),
            audit_comment=dict(),
            kind=dict(choices=[
                'finish',
                'iPXE',
                'job_template',
                'POAP',
                'provision',
                'ptable',
                'PXELinux',
                'PXEGrub',
                'PXEGrub2',
                'script',
                'snippet',
                'user_data',
                'ZTP',
            ]),
            template=dict(),
            file_name=dict(type='path'),
            locations=dict(type='list'),
            locked=dict(type='bool', default=False),
            name=dict(),
            organizations=dict(type='list'),
            operatingsystems=dict(type='list'),
            state=dict(default='present', choices=['absent', 'present_with_defaults', 'present']),
        ),
        supports_check_mode=True,
        mutually_exclusive=[
            ['file_name', 'template'],
        ],
        required_one_of=[
            ['name', 'file_name', 'template'],
        ],

    )

    # We do not want a template text for bulk operations
    if module.params['name'] == '*':
        if module.params['file_name'] or module.params['template']:
            module.fail_json(
                msg="Neither file_name nor template allowed if 'name: *'!")

    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')
    username = entity_dict.pop('username')
    password = entity_dict.pop('password')
    verify_ssl = entity_dict.pop('verify_ssl')
    state = entity_dict.pop('state')
    file_name = entity_dict.pop('file_name', None)

    if file_name or 'template' in entity_dict:
        if file_name:
            parsed_dict = parse_template_from_file(file_name, module)
        else:
            parsed_dict = parse_template(entity_dict['template'], module)
        # sanitize name from template data
        # The following condition can actually be hit, when someone is trying to import a
        # template with the name set to '*'.
        # Besides not being sensible, this would go horribly wrong in this module.
        if 'name' in parsed_dict and parsed_dict['name'] == '*':
            module.fail_json(msg="Cannot use '*' as a template name!")
        # module params are priorized
        parsed_dict.update(entity_dict)
        entity_dict = parsed_dict

    # make sure, we have a name
    if 'name' not in entity_dict:
        if file_name:
            entity_dict['name'] = os.path.splitext(
                os.path.basename(file_name))[0]
        else:
            module.fail_json(
                msg='No name specified and no filename to infer it.')

    name = entity_dict['name']

    affects_multiple = name == '*'
    # sanitize user input, filter unuseful configuration combinations with 'name: *'
    if affects_multiple:
        if state == 'present_with_defaults':
            module.fail_json(msg="'state: present_with_defaults' and 'name: *' cannot be used together")
        if state == 'absent':
            if entity_dict.keys() != ['name', 'locked']:
                module.fail_json(msg="When deleting all templates, there is no need to specify further parameters.")

    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)

    try:
        if affects_multiple:
            entities = find_entities(ProvisioningTemplate)
        else:
            entities = find_entities(ProvisioningTemplate, name=entity_dict['name'])
    except Exception as e:
        module.fail_json(msg='Failed to search for entities: %s ' % e)

    # Set Locations of Template
    if 'locations' in entity_dict:
        entity_dict['locations'] = find_entities_by_name(
            Location, entity_dict['locations'], module)

    # Set Organizations of Template
    if 'organizations' in entity_dict:
        entity_dict['organizations'] = find_entities_by_name(
            Organization, entity_dict['organizations'], module)

    if 'operatingsystems' in entity_dict:
        entity_dict['operatingsystems'] = [find_operating_system_by_title(module, title)
                                           for title in entity_dict['operatingsystems']]

    if not affects_multiple:
        entity_dict = find_template_kind(entity_dict, module)

    entity_dict = sanitize_entity_dict(entity_dict, name_map)

    changed = False
    if not affects_multiple:
        if len(entities) == 0:
            entity = None
        else:
            entity = entities[0]
        changed = naildown_entity_state(
            ProvisioningTemplate, entity_dict, entity, state, module)
    else:
        entity_dict.pop('name')
        for entity in entities:
            changed |= naildown_entity_state(
                ProvisioningTemplate, entity_dict, entity, state, module)

    module.exit_json(changed=changed)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            server_url=dict(required=True),
            username=dict(required=True),
            password=dict(required=True, no_log=True),
            verify_ssl=dict(type='bool', default=True),
            name=dict(required=True),
            release_name=dict(),
            description=dict(),
            family=dict(),
            major=dict(),
            minor=dict(),
            architectures=dict(type='list'),
            media=dict(type='list'),
            ptables=dict(type='list'),
            provisioning_templates=dict(type='list'),
            password_hash=dict(choices=['MD5', 'SHA256', 'SHA512']),
            state=dict(default='present',
                       choices=['present', 'present_with_defaults', 'absent']),
        ),
        supports_check_mode=True,
    )

    handle_no_nailgun(module, HAS_NAILGUN_PACKAGE)

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

    server_url = operating_system_dict.pop('server_url')
    username = operating_system_dict.pop('username')
    password = operating_system_dict.pop('password')
    verify_ssl = operating_system_dict.pop('verify_ssl')
    state = operating_system_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)
    try:
        # Try to find the Operating System to work on
        # name is however not unique, but description is, as well as "<name> <major>[.<minor>]"
        entity = None
        # If we have a description, search for it
        if 'description' in operating_system_dict and operating_system_dict[
                'description'] != '':
            entity = find_operating_system_by_title(
                module,
                title=operating_system_dict['description'],
                failsafe=True)
        # If we did not yet find a unique OS, search by name & version
        if entity is None:
            search_dict = {'name': operating_system_dict['name']}
            if 'major' in operating_system_dict:
                search_dict['major'] = operating_system_dict['major']
            if 'minor' in operating_system_dict:
                search_dict['minor'] = operating_system_dict['minor']
            entities = find_entities(OperatingSystem, **search_dict)
            if len(entities) == 1:
                entity = entities[0]
    except Exception as e:
        module.fail_json(msg='Failed to find entity: %s ' % e)

    if not entity and (state == 'present' or state == 'present_with_defaults'):
        # we actually attempt to create a new one...
        for param_name in ['major', 'family', 'password_hash']:
            if param_name not in operating_system_dict.keys():
                module.fail_json(
                    msg=
                    '{} is a required parameter to create a new operating system.'
                    .format(param_name))

    # Set Architectures of Operating System
    if 'architectures' in operating_system_dict:
        operating_system_dict['architectures'] = find_entities_by_name(
            Architecture, operating_system_dict['architectures'], module)

    # Set Installation Media of Operating System
    if 'media' in operating_system_dict:
        operating_system_dict['media'] = find_entities_by_name(
            Media, operating_system_dict['media'], module)

    # Set Partition Tables of Operating System
    if 'ptables' in operating_system_dict:
        operating_system_dict['ptables'] = find_entities_by_name(
            PartitionTable, operating_system_dict['ptables'], module)

    # Set Provisioning Templates of Operating System
    if 'provisioning_templates' in operating_system_dict:
        operating_system_dict[
            'provisioning_templates'] = find_entities_by_name(
                ProvisioningTemplate,
                operating_system_dict['provisioning_templates'], module)

    operating_system_dict = sanitize_entity_dict(operating_system_dict,
                                                 name_map)

    changed = naildown_entity_state(OperatingSystem, operating_system_dict,
                                    entity, state, module)

    module.exit_json(changed=changed)
Esempio n. 21
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            server_url=dict(required=True),
            username=dict(required=True),
            password=dict(required=True, no_log=True),
            verify_ssl=dict(type='bool', default=True),
            name=dict(required=True),
            description=dict(),
            family=dict(),
            major=dict(),
            minor=dict(),
            architectures=dict(type='list'),
            media=dict(type='list'),
            ptables=dict(type='list'),
            provisioning_templates=dict(type='list'),
            password_hash=dict(choices=['MD5', 'SHA256', 'SHA512']),
            state=dict(required=True,
                       choices=['present', 'present_with_defaults', 'absent']),
        ),
        supports_check_mode=True,
    )

    handle_no_nailgun(module, HAS_NAILGUN_PACKAGE)

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

    server_url = operating_system_dict.pop('server_url')
    username = operating_system_dict.pop('username')
    password = operating_system_dict.pop('password')
    verify_ssl = operating_system_dict.pop('verify_ssl')
    state = operating_system_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)
    try:
        entities = find_entities(OperatingSystem,
                                 name=operating_system_dict['name'])
        if len(entities) > 0:
            entity = entities[0]
        else:
            entity = None
    except Exception as e:
        module.fail_json(msg='Failed to find entity: %s ' % e)

    if not entity and (state == 'present' or state == 'present_with_defaults'):
        # we actually attempt to create a new one...
        for param_name in ['major', 'family', 'password_hash']:
            if param_name not in operating_system_dict.keys():
                module.fail_json(
                    msg=
                    '{} is a required parameter to create a new operating system.'
                    .format(param_name))

    # Set Architectures of Operating System
    if 'architectures' in operating_system_dict:
        operating_system_dict['architectures'] = find_entities_by_name(
            Architecture, operating_system_dict['architectures'], module)

    # Set Installation Media of Operating System
    if 'media' in operating_system_dict:
        operating_system_dict['media'] = find_entities_by_name(
            Media, operating_system_dict['media'], module)

    # Set Partition Tables of Operating System
    if 'ptables' in operating_system_dict:
        operating_system_dict['ptables'] = find_entities_by_name(
            PartitionTable, operating_system_dict['ptables'], module)

    # Set Provisioning Templates of Operating System
    if 'provisioning_templates' in operating_system_dict:
        operating_system_dict[
            'provisioning_templates'] = find_entities_by_name(
                ProvisioningTemplate,
                operating_system_dict['provisioning_templates'], module)

    operating_system_dict = sanitize_operating_system_dict(
        operating_system_dict)

    changed = naildown_entity_state(OperatingSystem, operating_system_dict,
                                    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),
            # audit_comment=dict(),
            layout=dict(),
            file_name=dict(type='path'),
            locations=dict(type='list'),
            # locked=dict(type='bool', default=False),
            name=dict(),
            organizations=dict(type='list'),
            os_family=dict(choices=list(_OPERATING_SYSTEMS)),
            state=dict(required=True, choices=['absent', 'present', 'latest']),
        ),
        supports_check_mode=True,
        mutually_exclusive=[
            ['file_name', 'layout'],
        ],
        required_one_of=[
            ['name', 'file_name', 'layout'],
        ],
    )
    # We do not want a layout text for bulk operations
    if module.params['name'] == '*':
        if module.params['file_name'] or module.params['layout']:
            module.fail_json(
                msg="Neither file_name nor layout allowed if 'name: *'!")

    handle_no_nailgun(module, HAS_NAILGUN_PACKAGE)

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

    server_url = ptable_dict.pop('server_url')
    username = ptable_dict.pop('username')
    password = ptable_dict.pop('password')
    verify_ssl = ptable_dict.pop('verify_ssl')
    state = ptable_dict.pop('state')
    file_name = ptable_dict.pop('file_name', None)

    if file_name or 'layout' in ptable_dict:
        if file_name:
            parsed_dict = parse_template_from_file(file_name, module)
        else:
            parsed_dict = parse_template(ptable_dict['layout'], module)
        # sanitize name from template data
        # The following condition can actually be hit, when someone is trying to import a
        # template with the name set to '*'.
        # Besides not being sensible, this would go horribly wrong in this module.
        if 'name' in parsed_dict and parsed_dict['name'] == '*':
            module.fail_json(msg="Cannot use '*' as a partition table name!")
        # module params are priorized
        parsed_dict.update(ptable_dict)
        ptable_dict = parsed_dict

    # make sure, we have a name
    if 'name' not in ptable_dict:
        if file_name:
            ptable_dict['name'] = os.path.splitext(
                os.path.basename(file_name))[0]
        else:
            module.fail_json(
                msg='No name specified and no filename to infer it.')

    name = ptable_dict['name']

    affects_multiple = name == '*'
    # sanitize user input, filter unuseful configuration combinations with 'name: *'
    if affects_multiple:
        if state == 'present':
            module.fail_json(
                msg="'state: present' and 'name: *' cannot be used together")
        if state == 'absent':
            if ptable_dict.keys() != ['name']:
                module.fail_json(
                    msg=
                    "When deleting all partition tables, there is no need to specify further parameters."
                )

    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)

    try:
        if affects_multiple:
            entities = find_entities(PartitionTable)
        else:
            entities = find_entities(PartitionTable, name=ptable_dict['name'])
    except Exception as e:
        module.fail_json(msg='Failed to find entity: %s ' % e)

    # Set Locations of partition table
    if 'locations' in ptable_dict:
        ptable_dict['locations'] = find_entities_by_name(
            Location, ptable_dict['locations'], module)

    # Set Organizations of partition table
    if 'organizations' in ptable_dict:
        ptable_dict['organizations'] = find_entities_by_name(
            Organization, ptable_dict['organizations'], module)

    ptable_dict = sanitize_ptable_dict(ptable_dict)

    changed = False
    if not affects_multiple:
        if len(entities) == 0:
            entity = None
        else:
            entity = entities[0]
        changed = naildown_entity_state(PartitionTable, ptable_dict, entity,
                                        state, module)
    else:
        ptable_dict.pop('name')
        for entity in entities:
            changed |= naildown_entity_state(PartitionTable, ptable_dict,
                                             entity, state, module)

    module.exit_json(changed=changed)