Beispiel #1
0
def main():

    argument_spec = openstack_full_argument_spec(
        name=dict(required=True),
        tag=dict(required=False, default=None),
        template=dict(default=None),
        environment=dict(default=None, type='list'),
        parameters=dict(default={}, type='dict'),
        rollback=dict(default=False, type='bool'),
        timeout=dict(default=3600, type='int'),
        state=dict(default='present', choices=['absent', 'present']),
    )

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

    # stack API introduced in 1.8.0
    min_version = '1.8.0'
    tag = module.params['tag']
    if tag is not None:
        # stack tag API was introduced in 1.26.0
        min_version = '1.26.0'

    state = module.params['state']
    name = module.params['name']
    # Check for required parameters when state == 'present'
    if state == 'present':
        for p in ['template']:
            if not module.params[p]:
                module.fail_json(msg='%s required with present state' % p)

    shade, cloud = openstack_cloud_from_module(module, min_version='1.26.0')
    try:
        stack = cloud.get_stack(name)

        if module.check_mode:
            module.exit_json(changed=_system_state_change(module, stack,
                                                          cloud))

        if state == 'present':
            if not stack:
                stack = _create_stack(module, stack, cloud, shade)
            else:
                stack = _update_stack(module, stack, cloud, shade)
            changed = True
            module.exit_json(changed=changed,
                             stack=stack,
                             id=stack.id)
        elif state == 'absent':
            if not stack:
                changed = False
            else:
                changed = True
                if not cloud.delete_stack(name, wait=module.params['wait']):
                    module.fail_json(msg='delete stack failed for stack: %s' % name)
            module.exit_json(changed=changed)
    except shade.OpenStackCloudException as e:
        module.fail_json(msg=to_native(e))
def main():
    argument_spec = openstack_full_argument_spec(
        display_name=dict(required=True, aliases=['name']),
        display_description=dict(default=None, aliases=['description']),
        volume=dict(required=True),
        force=dict(required=False, default=False, type='bool'),
        state=dict(default='present', choices=['absent', 'present']),
    )

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

    if not HAS_SHADE:
        module.fail_json(msg='shade is required for this module')

    state = module.params['state']

    try:
        cloud = shade.openstack_cloud(**module.params)
        if cloud.volume_exists(module.params['volume']):
            if module.check_mode:
                module.exit_json(changed=_system_state_change(module, cloud))
            if state == 'present':
                _present_volume_snapshot(module, cloud)
            if state == 'absent':
                _absent_volume_snapshot(module, cloud)
        else:
            module.fail_json(
                msg="No volume with name or id '{0}' was found.".format(
                    module.params['volume']))
    except (shade.OpenStackCloudException, shade.OpenStackCloudTimeout) as e:
        module.fail_json(msg=e.message)
def main():

    argument_spec = openstack_full_argument_spec(
        server=dict(required=False),
        detailed=dict(required=False, type='bool'),
    )
    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec, **module_kwargs)

    shade, cloud = openstack_cloud_from_module(module)
    try:
        openstack_servers = cloud.list_servers(
            detailed=module.params['detailed'])

        if module.params['server']:
            # filter servers by name
            pattern = module.params['server']
            # TODO(mordred) This is handled by shade now
            openstack_servers = [server for server in openstack_servers
                                 if fnmatch.fnmatch(server['name'], pattern) or fnmatch.fnmatch(server['id'], pattern)]
        module.exit_json(changed=False, ansible_facts=dict(
            openstack_servers=openstack_servers))

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
def main():

    argument_spec = openstack_full_argument_spec(
        name=dict(required=False, default=None),
        filters=dict(required=False, type='dict', default=None),
    )
    module_kwargs = openstack_module_kwargs(
        mutually_exclusive=[
            ['name', 'filters'],
        ]
    )
    module = AnsibleModule(argument_spec, **module_kwargs)

    shade, opcloud = openstack_cloud_from_module(module)
    try:
        name = module.params['name']
        filters = module.params['filters']

        if name:
            # Let's suppose user is passing domain ID
            try:
                domains = opcloud.get_domain(name)
            except:
                domains = opcloud.search_domains(filters={'name': name})

        else:
            domains = opcloud.search_domains(filters)

        module.exit_json(changed=False, ansible_facts=dict(
            openstack_domains=domains))

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
def main():
    argument_spec = openstack_full_argument_spec(
        server=dict(required=True),
        volume=dict(required=True),
        device=dict(default=None),  # None == auto choose device name
        state=dict(default='present', choices=['absent', 'present']),
    )

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

    state = module.params['state']
    wait = module.params['wait']
    timeout = module.params['timeout']

    shade, cloud = openstack_cloud_from_module(module)
    try:
        server = cloud.get_server(module.params['server'])
        volume = cloud.get_volume(module.params['volume'])
        dev = cloud.get_volume_attach_device(volume, server.id)

        if module.check_mode:
            module.exit_json(changed=_system_state_change(state, dev))

        if state == 'present':
            if dev:
                # Volume is already attached to this server
                module.exit_json(changed=False)

            cloud.attach_volume(server, volume, module.params['device'],
                                wait=wait, timeout=timeout)

            server = cloud.get_server(module.params['server'])  # refresh
            volume = cloud.get_volume(module.params['volume'])  # refresh
            hostvars = cloud.get_openstack_vars(server)

            module.exit_json(
                changed=True,
                id=volume['id'],
                attachments=volume['attachments'],
                openstack=hostvars
            )

        elif state == 'absent':
            if not dev:
                # Volume is not attached to this server
                module.exit_json(changed=False)

            cloud.detach_volume(server, volume, wait=wait, timeout=timeout)
            module.exit_json(
                changed=True,
                result='Detached volume from server'
            )

    except (shade.OpenStackCloudException, shade.OpenStackCloudTimeout) as e:
        module.fail_json(msg=str(e))
def main():
    argument_spec = openstack_full_argument_spec(
        name=dict(required=True),
        description=dict(default=None),
        enabled=dict(default=True, type='bool'),
        state=dict(default='present', choices=['absent', 'present']),
    )

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

    name = module.params['name']
    description = module.params['description']
    enabled = module.params['enabled']
    state = module.params['state']

    shade, cloud = openstack_cloud_from_module(module)
    try:

        domains = cloud.search_domains(filters=dict(name=name))

        if len(domains) > 1:
            module.fail_json(msg='Domain name %s is not unique' % name)
        elif len(domains) == 1:
            domain = domains[0]
        else:
            domain = None

        if module.check_mode:
            module.exit_json(changed=_system_state_change(module, domain))

        if state == 'present':
            if domain is None:
                domain = cloud.create_domain(
                    name=name, description=description, enabled=enabled)
                changed = True
            else:
                if _needs_update(module, domain):
                    domain = cloud.update_domain(
                        domain.id, name=name, description=description,
                        enabled=enabled)
                    changed = True
                else:
                    changed = False
            module.exit_json(changed=changed, domain=domain, id=domain.id)

        elif state == 'absent':
            if domain is None:
                changed = False
            else:
                cloud.delete_domain(domain.id)
                changed = True
            module.exit_json(changed=changed)

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Beispiel #7
0
def main():
    argument_spec = openstack_full_argument_spec(
        name=dict(required=True),
        public_key=dict(default=None),
        public_key_file=dict(default=None),
        state=dict(default='present',
                   choices=['absent', 'present']),
    )

    module_kwargs = openstack_module_kwargs(
        mutually_exclusive=[['public_key', 'public_key_file']])

    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

    state = module.params['state']
    name = module.params['name']
    public_key = module.params['public_key']

    if module.params['public_key_file']:
        public_key = open(module.params['public_key_file']).read()
        public_key = public_key.rstrip()

    shade, cloud = openstack_cloud_from_module(module)
    try:
        keypair = cloud.get_keypair(name)

        if module.check_mode:
            module.exit_json(changed=_system_state_change(module, keypair))

        if state == 'present':
            if keypair and keypair['name'] == name:
                if public_key and (public_key != keypair['public_key']):
                    module.fail_json(
                        msg="Key name %s present but key hash not the same"
                            " as offered. Delete key first." % name
                    )
                else:
                    changed = False
            else:
                keypair = cloud.create_keypair(name, public_key)
                changed = True

            module.exit_json(changed=changed,
                             key=keypair,
                             id=keypair['id'])

        elif state == 'absent':
            if keypair:
                cloud.delete_keypair(name)
                module.exit_json(changed=True)
            module.exit_json(changed=False)

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
def main():
    argument_spec = openstack_full_argument_spec(
        name=dict(required=False, default=None),
        ram=dict(required=False, default=None),
        vcpus=dict(required=False, default=None),
        limit=dict(required=False, default=None, type='int'),
        ephemeral=dict(required=False, default=None),
    )
    module_kwargs = openstack_module_kwargs(
        mutually_exclusive=[
            ['name', 'ram'],
            ['name', 'vcpus'],
            ['name', 'ephemeral']
        ]
    )
    module = AnsibleModule(argument_spec, **module_kwargs)

    name = module.params['name']
    vcpus = module.params['vcpus']
    ram = module.params['ram']
    ephemeral = module.params['ephemeral']
    limit = module.params['limit']

    filters = {}
    if vcpus:
        filters['vcpus'] = vcpus
    if ram:
        filters['ram'] = ram
    if ephemeral:
        filters['ephemeral'] = ephemeral

    if filters:
        # Range search added in 1.5.0
        min_version = '1.5.0'
    else:
        min_version = None

    shade, cloud = openstack_cloud_from_module(module, min_version=min_version)
    try:
        if name:
            flavors = cloud.search_flavors(filters={'name': name})

        else:
            flavors = cloud.list_flavors()
            if filters:
                flavors = cloud.range_search(flavors, filters)

        if limit is not None:
            flavors = flavors[:limit]

        module.exit_json(changed=False,
                         ansible_facts=dict(openstack_flavors=flavors))

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Beispiel #9
0
def main():
    argument_spec = openstack_full_argument_spec(
        name=dict(required=True),
        description=dict(required=False, default=None),
        domain_id=dict(required=False, default=None),
        state=dict(default='present', choices=['absent', 'present']),
    )

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

    name = module.params.get('name')
    description = module.params.get('description')
    state = module.params.get('state')

    domain_id = module.params.pop('domain_id')

    shade, cloud = openstack_cloud_from_module(module)
    try:
        if domain_id:
            group = cloud.get_group(name, filters={'domain_id': domain_id})
        else:
            group = cloud.get_group(name)

        if module.check_mode:
            module.exit_json(changed=_system_state_change(state, description, group))

        if state == 'present':
            if group is None:
                group = cloud.create_group(
                    name=name, description=description, domain=domain_id)
                changed = True
            else:
                if description is not None and group.description != description:
                    group = cloud.update_group(
                        group.id, description=description)
                    changed = True
                else:
                    changed = False
            module.exit_json(changed=changed, group=group)

        elif state == 'absent':
            if group is None:
                changed = False
            else:
                cloud.delete_group(group.id)
                changed = True
            module.exit_json(changed=changed)

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Beispiel #10
0
def main():
    argument_spec = openstack_full_argument_spec(
        name=dict(required=True),
        policies=dict(required=False, type='list'),
        state=dict(default='present', choices=['absent', 'present']),
    )
    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(
        argument_spec,
        supports_check_mode=True,
        **module_kwargs
    )

    name = module.params['name']
    policies = module.params['policies']
    state = module.params['state']

    shade, cloud = openstack_cloud_from_module(module)
    try:
        server_group = cloud.get_server_group(name)

        if module.check_mode:
            module.exit_json(
                changed=_system_state_change(state, server_group)
            )

        changed = False
        if state == 'present':
            if not server_group:
                if not policies:
                    module.fail_json(
                        msg="Parameter 'policies' is required in Server Group "
                            "Create"
                    )
                server_group = cloud.create_server_group(name, policies)
                changed = True

            module.exit_json(
                changed=changed,
                id=server_group['id'],
                server_group=server_group
            )
        if state == 'absent':
            if server_group:
                cloud.delete_server_group(server_group['id'])
                changed = True
            module.exit_json(changed=changed)
    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e), extra_data=e.extra_data)
def main():
    argument_spec = openstack_full_argument_spec(
        auth_type=dict(required=False),
        uuid=dict(required=False),
        name=dict(required=False),
        mac=dict(required=False),
        ironic_url=dict(required=False),
        timeout=dict(default=1200, type='int', required=False),
    )
    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec, **module_kwargs)

    if (module.params['auth_type'] in [None, 'None'] and
            module.params['ironic_url'] is None):
        module.fail_json(msg="Authentication appears to be disabled, "
                             "Please define an ironic_url parameter")

    if (module.params['ironic_url'] and
            module.params['auth_type'] in [None, 'None']):
        module.params['auth'] = dict(
            endpoint=module.params['ironic_url']
        )

    shade, cloud = openstack_cloud_from_module(
        module, min_version='1.0.0')
    try:

        if module.params['name'] or module.params['uuid']:
            server = cloud.get_machine(_choose_id_value(module))
        elif module.params['mac']:
            server = cloud.get_machine_by_mac(module.params['mac'])
        else:
            module.fail_json(msg="The worlds did not align, "
                                 "the host was not found as "
                                 "no name, uuid, or mac was "
                                 "defined.")
        if server:
            cloud.inspect_machine(server['uuid'], module.params['wait'])
            # TODO(TheJulia): diff properties, ?and ports? and determine
            # if a change occurred.  In theory, the node is always changed
            # if introspection is able to update the record.
            module.exit_json(changed=True,
                             ansible_facts=server['properties'])

        else:
            module.fail_json(msg="node not found.")

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Beispiel #12
0
def main():

    argument_spec = openstack_full_argument_spec()
    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec, **module_kwargs)

    shade, cloud = openstack_cloud_from_module(module)
    try:
        module.exit_json(
            changed=False,
            ansible_facts=dict(
                auth_token=cloud.auth_token,
                service_catalog=cloud.service_catalog))
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
Beispiel #13
0
def main():

    argument_spec = openstack_full_argument_spec(
        image=dict(required=True),
    )
    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec, **module_kwargs)

    shade, cloud = openstack_cloud_from_module(module)
    try:
        image = cloud.get_image(module.params['image'])
        module.exit_json(changed=False, ansible_facts=dict(
            openstack_image=image))

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
def main():

    argument_spec = openstack_full_argument_spec(
        name=dict(required=False, default=None),
        filters=dict(required=False, type='dict', default=None)
    )
    module = AnsibleModule(argument_spec)

    shade, cloud = openstack_cloud_from_module(module)
    try:
        subnets = cloud.search_subnets(module.params['name'],
                                       module.params['filters'])
        module.exit_json(changed=False, ansible_facts=dict(
            openstack_subnets=subnets))

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Beispiel #15
0
def main():
    argument_spec = openstack_full_argument_spec(
        name=dict(required=False, default=None),
        container=dict(required=True),
        filename=dict(required=False, default=None),
        container_access=dict(default='private', choices=['private', 'public']),
        state=dict(default='present', choices=['absent', 'present']),
    )
    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec, **module_kwargs)

    shade, cloud = openstack_cloud_from_module(module)
    try:
        changed = process_object(cloud, **module.params)

        module.exit_json(changed=changed)
    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
def main():
    argument_spec = openstack_full_argument_spec(
        name=dict(required=True),
        description=dict(default=''),
        state=dict(default='present', choices=['absent', 'present']),
    )

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

    name = module.params['name']
    state = module.params['state']
    description = module.params['description']

    shade, cloud = openstack_cloud_from_module(module)
    try:
        secgroup = cloud.get_security_group(name)

        if module.check_mode:
            module.exit_json(changed=_system_state_change(module, secgroup))

        changed = False
        if state == 'present':
            if not secgroup:
                secgroup = cloud.create_security_group(name, description)
                changed = True
            else:
                if _needs_update(module, secgroup):
                    secgroup = cloud.update_security_group(
                        secgroup['id'], description=description)
                    changed = True
            module.exit_json(
                changed=changed, id=secgroup['id'], secgroup=secgroup)

        if state == 'absent':
            if secgroup:
                cloud.delete_security_group(secgroup['id'])
                changed = True
            module.exit_json(changed=changed)

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
def main():

    argument_spec = openstack_full_argument_spec(
        name=dict(required=False, default=None),
        domain=dict(required=False, default=None),
        filters=dict(required=False, type='dict', default=None),
    )

    module = AnsibleModule(argument_spec)

    shade, opcloud = openstack_cloud_from_module(module)
    try:
        name = module.params['name']
        domain = module.params['domain']
        filters = module.params['filters']

        if domain:
            try:
                # We assume admin is passing domain id
                dom = opcloud.get_domain(domain)['id']
                domain = dom
            except:
                # If we fail, maybe admin is passing a domain name.
                # Note that domains have unique names, just like id.
                dom = opcloud.search_domains(filters={'name': domain})
                if dom:
                    domain = dom[0]['id']
                else:
                    module.fail_json(msg='Domain name or ID does not exist')

            if not filters:
                filters = {}

            filters['domain_id'] = domain

        projects = opcloud.search_projects(name, filters)
        module.exit_json(changed=False, ansible_facts=dict(
            openstack_projects=projects))

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Beispiel #18
0
def main():
    module = AnsibleModule(
        argument_spec=openstack_full_argument_spec(
            password=dict(required=True, type='str'),
            project=dict(required=True, type='str'),
            role=dict(required=True, type='str'),
            user=dict(required=True, type='str'),
            service=dict(required=True, type='str'),
        )
    )

    try:
        changed = True
        cloud = shade.operator_cloud(**module.params)

        getattr(SanityChecks, module.params.pop("service"))(cloud)

        module.exit_json(changed=changed)
    except Exception:
        module.exit_json(failed=True, changed=True,
                         msg=repr(traceback.format_exc()))
def main():
    argument_spec = openstack_full_argument_spec(
        name=dict(required=True),
        state=dict(default='present', choices=['absent', 'present']),
    )

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

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

    shade, cloud = openstack_cloud_from_module(module)
    try:

        role = cloud.get_role(name)

        if module.check_mode:
            module.exit_json(changed=_system_state_change(state, role))

        if state == 'present':
            if role is None:
                role = cloud.create_role(name)
                changed = True
            else:
                changed = False
            module.exit_json(changed=changed, role=role)
        elif state == 'absent':
            if role is None:
                changed = False
            else:
                cloud.delete_role(name)
                changed = True
            module.exit_json(changed=changed)

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Beispiel #20
0
def main():
    argument_spec = openstack_full_argument_spec(
        user=dict(required=True),
        group=dict(required=True),
        state=dict(default='present', choices=['absent', 'present']),
    )

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

    user = module.params['user']
    group = module.params['group']
    state = module.params['state']

    shade, cloud = openstack_cloud_from_module(module)
    try:
        in_group = cloud.is_user_in_group(user, group)

        if module.check_mode:
            module.exit_json(changed=_system_state_change(state, in_group))

        changed = False
        if state == 'present':
            if not in_group:
                cloud.add_user_to_group(user, group)
                changed = True

        elif state == 'absent':
            if in_group:
                cloud.remove_user_from_group(user, group)
                changed = True

        module.exit_json(changed=changed)

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e), extra_data=e.extra_data)
Beispiel #21
0
def main():

    argument_spec = openstack_full_argument_spec(
        name=dict(required=True),
        state=dict(default='present', choices=['absent', 'present']),
        backup_gigabytes=dict(required=False, type='int', default=None),
        backups=dict(required=False, type='int', default=None),
        cores=dict(required=False, type='int', default=None),
        fixed_ips=dict(required=False, type='int', default=None),
        floating_ips=dict(required=False, type='int', default=None, aliases=['compute_floating_ips']),
        floatingip=dict(required=False, type='int', default=None, aliases=['network_floating_ips']),
        gigabytes=dict(required=False, type='int', default=None),
        gigabytes_types=dict(required=False, type='dict', default={}),
        injected_file_size=dict(required=False, type='int', default=None),
        injected_files=dict(required=False, type='int', default=None),
        injected_path_size=dict(required=False, type='int', default=None),
        instances=dict(required=False, type='int', default=None),
        key_pairs=dict(required=False, type='int', default=None),
        loadbalancer=dict(required=False, type='int', default=None),
        network=dict(required=False, type='int', default=None),
        per_volume_gigabytes=dict(required=False, type='int', default=None),
        pool=dict(required=False, type='int', default=None),
        port=dict(required=False, type='int', default=None),
        project=dict(required=False, type='int', default=None),
        properties=dict(required=False, type='int', default=None),
        ram=dict(required=False, type='int', default=None),
        rbac_policy=dict(required=False, type='int', default=None),
        router=dict(required=False, type='int', default=None),
        security_group_rule=dict(required=False, type='int', default=None),
        security_group=dict(required=False, type='int', default=None),
        server_group_members=dict(required=False, type='int', default=None),
        server_groups=dict(required=False, type='int', default=None),
        snapshots=dict(required=False, type='int', default=None),
        snapshots_types=dict(required=False, type='dict', default={}),
        subnet=dict(required=False, type='int', default=None),
        subnetpool=dict(required=False, type='int', default=None),
        volumes=dict(required=False, type='int', default=None),
        volumes_types=dict(required=False, type='dict', default={})
    )

    module = AnsibleModule(argument_spec,
                           supports_check_mode=True
                           )

    shade, cloud = openstack_cloud_from_module(module)
    try:
        cloud_params = dict(module.params)

        # In order to handle the different volume types we update module params after.
        dynamic_types = [
            'gigabytes_types',
            'snapshots_types',
            'volumes_types',
        ]

        for dynamic_type in dynamic_types:
            for k, v in module.params[dynamic_type].items():
                module.params[k] = int(v)

        # Get current quota values
        project_quota_output = _get_quotas(
            shade, module, cloud, cloud_params['name'])
        changes_required = False

        if module.params['state'] == "absent":
            # If a quota state is set to absent we should assume there will be changes.
            # The default quota values are not accessible so we can not determine if
            # no changes will occur or not.
            if module.check_mode:
                module.exit_json(changed=True)

            # Calling delete_network_quotas when a quota has not been set results
            # in an error, according to the shade docs it should return the
            # current quota.
            # The following error string is returned:
            # network client call failed: Quota for tenant 69dd91d217e949f1a0b35a4b901741dc could not be found.
            neutron_msg1 = "network client call failed: Quota for tenant"
            neutron_msg2 = "could not be found"

            for quota_type in project_quota_output.keys():
                quota_call = getattr(cloud, 'delete_%s_quotas' % (quota_type))
                try:
                    quota_call(cloud_params['name'])
                except shade.OpenStackCloudException as e:
                    error_msg = str(e)
                    if error_msg.find(neutron_msg1) > -1 and error_msg.find(neutron_msg2) > -1:
                        pass
                    else:
                        module.fail_json(msg=str(e), extra_data=e.extra_data)

            project_quota_output = _get_quotas(
                shade, module, cloud, cloud_params['name'])
            changes_required = True

        elif module.params['state'] == "present":
            if module.check_mode:
                module.exit_json(changed=_system_state_change(module, project_quota_output))

            changes_required, quota_change_request = _system_state_change_details(
                module,
                project_quota_output
            )

            if changes_required:
                for quota_type in quota_change_request.keys():
                    quota_call = getattr(cloud, 'set_%s_quotas' % (quota_type))
                    quota_call(cloud_params['name'], **quota_change_request[quota_type])

                # Get quota state post changes for validation
                project_quota_update = _get_quotas(
                    shade, module, cloud, cloud_params['name'])

                if project_quota_output == project_quota_update:
                    module.fail_json(msg='Could not apply quota update')

                project_quota_output = project_quota_update

        module.exit_json(changed=changes_required,
                         openstack_quotas=project_quota_output
                         )

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e), extra_data=e.extra_data)
Beispiel #22
0
def main():
    argument_spec = openstack_full_argument_spec(
        uuid=dict(required=False),
        name=dict(required=False),
        driver=dict(required=False),
        driver_info=dict(type='dict', required=True),
        nics=dict(type='list', required=True),
        properties=dict(type='dict', default={}),
        ironic_url=dict(required=False),
        chassis_uuid=dict(required=False),
        skip_update_of_masked_password=dict(required=False, type='bool'),
        state=dict(required=False, default='present'))
    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec, **module_kwargs)

    if not HAS_SHADE:
        module.fail_json(msg='shade is required for this module')
    if not HAS_JSONPATCH:
        module.fail_json(msg='jsonpatch is required for this module')
    if (module.params['auth_type'] in [None, 'None']
            and module.params['ironic_url'] is None):
        module.fail_json(msg="Authentication appears to be disabled, "
                         "Please define an ironic_url parameter")

    if (module.params['ironic_url']
            and module.params['auth_type'] in [None, 'None']):
        module.params['auth'] = dict(endpoint=module.params['ironic_url'])

    node_id = _choose_id_value(module)

    try:
        cloud = shade.operator_cloud(**module.params)
        server = cloud.get_machine(node_id)
        if module.params['state'] == 'present':
            if module.params['driver'] is None:
                module.fail_json(msg="A driver must be defined in order "
                                 "to set a node to present.")

            properties = _parse_properties(module)
            driver_info = _parse_driver_info(module)
            kwargs = dict(
                driver=module.params['driver'],
                properties=properties,
                driver_info=driver_info,
                name=module.params['name'],
            )

            if module.params['chassis_uuid']:
                kwargs['chassis_uuid'] = module.params['chassis_uuid']

            if server is None:
                # Note(TheJulia): Add a specific UUID to the request if
                # present in order to be able to re-use kwargs for if
                # the node already exists logic, since uuid cannot be
                # updated.
                if module.params['uuid']:
                    kwargs['uuid'] = module.params['uuid']

                server = cloud.register_machine(module.params['nics'],
                                                **kwargs)
                module.exit_json(changed=True,
                                 uuid=server['uuid'],
                                 provision_state=server['provision_state'])
            else:
                # TODO(TheJulia): Presently this does not support updating
                # nics.  Support needs to be added.
                #
                # Note(TheJulia): This message should never get logged
                # however we cannot realistically proceed if neither a
                # name or uuid was supplied to begin with.
                if not node_id:
                    module.fail_json(msg="A uuid or name value "
                                     "must be defined")

                # Note(TheJulia): Constructing the configuration to compare
                # against.  The items listed in the server_config block can
                # be updated via the API.

                server_config = dict(
                    driver=server['driver'],
                    properties=server['properties'],
                    driver_info=server['driver_info'],
                    name=server['name'],
                )

                # Add the pre-existing chassis_uuid only if
                # it is present in the server configuration.
                if hasattr(server, 'chassis_uuid'):
                    server_config['chassis_uuid'] = server['chassis_uuid']

                # Note(TheJulia): If a password is defined and concealed, a
                # patch will always be generated and re-asserted.
                patch = jsonpatch.JsonPatch.from_diff(server_config, kwargs)

                if not patch:
                    _exit_node_not_updated(module, server)
                elif _choose_if_password_only(module, list(patch)):
                    # Note(TheJulia): Normally we would allow the general
                    # exception catch below, however this allows a specific
                    # message.
                    try:
                        server = cloud.patch_machine(server['uuid'],
                                                     list(patch))
                    except Exception as e:
                        module.fail_json(msg="Failed to update node, "
                                         "Error: %s" % e.message)

                    # Enumerate out a list of changed paths.
                    change_list = []
                    for change in list(patch):
                        change_list.append(change['path'])
                    module.exit_json(changed=True,
                                     result="Node Updated",
                                     changes=change_list,
                                     uuid=server['uuid'],
                                     provision_state=server['provision_state'])

            # Return not updated by default as the conditions were not met
            # to update.
            _exit_node_not_updated(module, server)

        if module.params['state'] == 'absent':
            if not node_id:
                module.fail_json(msg="A uuid or name value must be defined "
                                 "in order to remove a node.")

            if server is not None:
                cloud.unregister_machine(module.params['nics'], server['uuid'])
                module.exit_json(changed=True, result="deleted")
            else:
                module.exit_json(changed=False, result="Server not found")

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Beispiel #23
0
def main():
    argument_spec = openstack_full_argument_spec(
        name=dict(required=True),
        state=dict(default='present', choices=['absent', 'present']),
        loadbalancer=dict(default=None),
        listener=dict(default=None),
        protocol=dict(default='HTTP',
                      choices=['HTTP', 'HTTPS', 'TCP', 'UDP', 'PROXY']),
        lb_algorithm=dict(
            default='ROUND_ROBIN',
            choices=['ROUND_ROBIN', 'LEAST_CONNECTIONS', 'SOURCE_IP']))
    module_kwargs = openstack_module_kwargs(
        mutually_exclusive=[['loadbalancer', 'listener']])
    module = AnsibleModule(argument_spec, **module_kwargs)
    sdk, cloud = openstack_cloud_from_module(module)

    loadbalancer = module.params['loadbalancer']
    listener = module.params['listener']

    try:
        changed = False
        pool = cloud.load_balancer.find_pool(name_or_id=module.params['name'])

        if module.params['state'] == 'present':
            if not pool:
                loadbalancer_id = None
                if not (loadbalancer or listener):
                    module.fail_json(
                        msg="either loadbalancer or listener must be provided")

                if loadbalancer:
                    lb = cloud.load_balancer.find_load_balancer(loadbalancer)
                    if not lb:
                        module.fail_json(msg='load balancer %s is not '
                                         'found' % loadbalancer)
                    loadbalancer_id = lb.id

                listener_id = None
                if listener:
                    listener_ret = cloud.load_balancer.find_listener(listener)
                    if not listener_ret:
                        module.fail_json(msg='listener %s is not found' %
                                         listener)
                    listener_id = listener_ret.id

                pool = cloud.load_balancer.create_pool(
                    name=module.params['name'],
                    loadbalancer_id=loadbalancer_id,
                    listener_id=listener_id,
                    protocol=module.params['protocol'],
                    lb_algorithm=module.params['lb_algorithm'])
                changed = True

                if not module.params['wait']:
                    module.exit_json(changed=changed,
                                     pool=pool.to_dict(),
                                     id=pool.id)

            if module.params['wait']:
                pool = _wait_for_pool_status(module, cloud, pool.id, "ACTIVE",
                                             ["ERROR"])

            module.exit_json(changed=changed, pool=pool.to_dict(), id=pool.id)

        elif module.params['state'] == 'absent':
            if pool:
                cloud.load_balancer.delete_pool(pool)
                changed = True

            module.exit_json(changed=changed)
    except sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e), extra_data=e.extra_data)
def main():
    argument_spec = openstack_full_argument_spec(
        description=dict(required=True, type='str'),
        service_name=dict(required=True, type='str'),
        service_type=dict(required=True, type='str'),
        url=dict(required=True, type='str'),
        interface=dict(required=True, type='str'),
        endpoint_region=dict(required=True, type='str'),
        endpoint_type=dict(type='str'))
    module = AnsibleModule(argument_spec)

    try:
        description = module.params.pop('description')
        service_name = module.params.pop('service_name')
        service_type = module.params.pop('service_type')
        url = module.params.pop('url')
        interface = module.params.pop('interface')
        endpoint_region = module.params.pop('endpoint_region')

        changed = False
        service = None
        endpoint = None

        cloud = shade.operator_cloud(**module.params)

        for _service in cloud.keystone_client.services.list():
            if _service.type == service_type:
                service = _service
                service_description = getattr(service, 'description', None)
                if service.name != service_name or \
                        service_description != description:
                    changed = True
                    cloud.keystone_client.services.update(
                        service, name=service_name, description=description)
                break
        else:
            changed = True
            service = cloud.keystone_client.services.create(
                name=service_name,
                service_type=service_type,
                description=description)

        for _endpoint in cloud.keystone_client.endpoints.list():
            if _endpoint.service_id == service.id and \
                    _endpoint.interface == interface and \
                    _endpoint.region == endpoint_region:
                endpoint = _endpoint
                if endpoint.url != url:
                    changed = True
                    cloud.keystone_client.endpoints.update(endpoint, url=url)
                break
        else:
            changed = True
            cloud.keystone_client.endpoints.create(service=service.id,
                                                   url=url,
                                                   interface=interface,
                                                   region=endpoint_region)

        module.exit_json(changed=changed)
    except Exception:
        module.exit_json(failed=True,
                         changed=True,
                         msg=repr(traceback.format_exc()))
Beispiel #25
0
def main():
    argument_spec = openstack_full_argument_spec(
        name=dict(required=True),
        state=dict(default='present', choices=['absent', 'present']),
        vip_network=dict(required=False),
        vip_subnet=dict(required=False),
        vip_port=dict(required=False),
        vip_address=dict(required=False),
    )
    module_kwargs = openstack_module_kwargs(required_one_of=[
        ['vip_network', 'vip_subnet', 'vip_port'],
    ])
    module = AnsibleModule(argument_spec, **module_kwargs)

    sdk, cloud = openstack_cloud_from_module(module)
    vip_network_id = None
    vip_subnet_id = None
    vip_port_id = None

    try:
        changed = False
        lb = cloud.load_balancer.find_load_balancer(
            name_or_id=module.params['name'])

        if module.params['state'] == 'present':
            if not lb:
                if module.params['vip_network']:
                    network = cloud.get_network(module.params['vip_network'])
                    if not network:
                        module.fail_json(msg='network %s is not found' %
                                         module.params['vip_network'])
                    vip_network_id = network.id
                if module.params['vip_subnet']:
                    subnet = cloud.get_subnet(module.params['vip_subnet'])
                    if not subnet:
                        module.fail_json(msg='subnet %s is not found' %
                                         module.params['vip_subnet'])
                    vip_subnet_id = subnet.id
                if module.params['vip_port']:
                    port = cloud.get_port(module.params['vip_port'])
                    if not port:
                        module.fail_json(msg='port %s is not found' %
                                         module.params['vip_port'])
                    vip_port_id = port.id

                lb = cloud.load_balancer.create_load_balancer(
                    name=module.params['name'],
                    vip_network_id=vip_network_id,
                    vip_subnet_id=vip_subnet_id,
                    vip_port_id=vip_port_id,
                    vip_address=module.params['vip_address'],
                )
                changed = True

                if not module.params['wait']:
                    module.exit_json(changed=changed,
                                     loadbalancer=lb.to_dict(),
                                     id=lb.id)

            if module.params['wait']:
                _lb_wait_for_status(module, cloud, lb, "ACTIVE", ["ERROR"])

            module.exit_json(changed=changed,
                             loadbalancer=lb.to_dict(),
                             id=lb.id)
        elif module.params['state'] == 'absent':
            if not lb:
                changed = False
            else:
                # Deleting load balancer with `cascade=False` does not make
                # sense because the deletion will always fail if there are
                # sub-resources.
                cloud.load_balancer.delete_load_balancer(lb, cascade=True)
                changed = True

            module.exit_json(changed=changed)
    except sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e), extra_data=e.extra_data)
Beispiel #26
0
def main():

    argument_spec = openstack_full_argument_spec(
        name=dict(required=True),
        image=dict(default=None),
        image_exclude=dict(default='(deprecated)'),
        flavor=dict(default=None),
        flavor_ram=dict(default=None, type='int'),
        flavor_include=dict(default=None),
        key_name=dict(default=None),
        security_groups=dict(default=['default'], type='list'),
        network=dict(default=None),
        nics=dict(default=[], type='list'),
        meta=dict(default=None, type='raw'),
        userdata=dict(default=None, aliases=['user_data']),
        config_drive=dict(default=False, type='bool'),
        auto_ip=dict(default=True, type='bool', aliases=['auto_floating_ip', 'public_ip']),
        floating_ips=dict(default=None, type='list'),
        floating_ip_pools=dict(default=None, type='list'),
        volume_size=dict(default=False, type='int'),
        boot_from_volume=dict(default=False, type='bool'),
        boot_volume=dict(default=None, aliases=['root_volume']),
        terminate_volume=dict(default=False, type='bool'),
        volumes=dict(default=[], type='list'),
        scheduler_hints=dict(default=None, type='dict'),
        state=dict(default='present', choices=['absent', 'present']),
        delete_fip=dict(default=False, type='bool'),
        reuse_ips=dict(default=True, type='bool'),
    )
    module_kwargs = openstack_module_kwargs(
        mutually_exclusive=[
            ['auto_ip', 'floating_ips'],
            ['auto_ip', 'floating_ip_pools'],
            ['floating_ips', 'floating_ip_pools'],
            ['flavor', 'flavor_ram'],
            ['image', 'boot_volume'],
            ['boot_from_volume', 'boot_volume'],
            ['nics', 'network'],
        ],
        required_if=[
            ('boot_from_volume', True, ['volume_size', 'image']),
        ],
    )
    module = AnsibleModule(argument_spec, **module_kwargs)

    state = module.params['state']
    image = module.params['image']
    boot_volume = module.params['boot_volume']
    flavor = module.params['flavor']
    flavor_ram = module.params['flavor_ram']

    if state == 'present':
        if not (image or boot_volume):
            module.fail_json(
                msg="Parameter 'image' or 'boot_volume' is required "
                    "if state == 'present'"
            )
        if not flavor and not flavor_ram:
            module.fail_json(
                msg="Parameter 'flavor' or 'flavor_ram' is required "
                    "if state == 'present'"
            )

    shade, cloud = openstack_cloud_from_module(module)
    try:
        if state == 'present':
            _get_server_state(module, cloud)
            _create_server(module, cloud)
        elif state == 'absent':
            _get_server_state(module, cloud)
            _delete_server(module, cloud)
    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e), extra_data=e.extra_data)
Beispiel #27
0
def main():
    argument_spec = openstack_full_argument_spec(
        state=dict(default='present', choices=['absent', 'present']),
        name=dict(required=True),
        admin_state_up=dict(type='bool', default=True),
        enable_snat=dict(type='bool'),
        network=dict(default=None),
        interfaces=dict(type='list', default=None),
        external_fixed_ips=dict(type='list', default=None),
        project=dict(default=None))

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

    state = module.params['state']
    name = module.params['name']
    network = module.params['network']
    project = module.params['project']

    if module.params['external_fixed_ips'] and not network:
        module.fail_json(
            msg='network is required when supplying external_fixed_ips')

    sdk, cloud = openstack_cloud_from_module(module)
    try:
        if project is not None:
            proj = cloud.get_project(project)
            if proj is None:
                module.fail_json(msg='Project %s could not be found' % project)
            project_id = proj['id']
            filters = {'tenant_id': project_id}
        else:
            project_id = None
            filters = None

        router = cloud.get_router(name, filters=filters)
        net = None
        if network:
            net = cloud.get_network(network)
            if not net:
                module.fail_json(msg='network %s not found' % network)

        # Validate and cache the subnet IDs so we can avoid duplicate checks
        # and expensive API calls.
        external_ids, subnet_internal_ids, internal_portids = _validate_subnets(
            module, cloud, filters)
        if module.check_mode:
            module.exit_json(changed=_system_state_change(
                cloud, module, router, net, subnet_internal_ids,
                internal_portids, filters))

        if state == 'present':
            changed = False

            if not router:
                kwargs = _build_kwargs(cloud, module, router, net)
                if project_id:
                    kwargs['project_id'] = project_id
                router = cloud.create_router(**kwargs)
                for int_s_id in subnet_internal_ids:
                    cloud.add_router_interface(router, subnet_id=int_s_id)
                changed = True
                # add interface by port id as well
                for int_p_id in internal_portids:
                    cloud.add_router_interface(router, port_id=int_p_id)
                changed = True
            else:
                if _needs_update(cloud, module, router, net,
                                 subnet_internal_ids, internal_portids,
                                 filters):
                    kwargs = _build_kwargs(cloud, module, router, net)
                    updated_router = cloud.update_router(**kwargs)

                    # Protect against update_router() not actually
                    # updating the router.
                    if not updated_router:
                        changed = False

                    # On a router update, if any internal interfaces were supplied,
                    # just detach all existing internal interfaces and attach the new.
                    if internal_portids or subnet_internal_ids:
                        router = updated_router
                        ports = _router_internal_interfaces(cloud, router)
                        for port in ports:
                            cloud.remove_router_interface(router,
                                                          port_id=port['id'])
                    if internal_portids:
                        external_ids, subnet_internal_ids, internal_portids = _validate_subnets(
                            module, cloud, filters)
                        for int_p_id in internal_portids:
                            cloud.add_router_interface(router,
                                                       port_id=int_p_id)
                        changed = True
                    if subnet_internal_ids:
                        for s_id in subnet_internal_ids:
                            cloud.add_router_interface(router, subnet_id=s_id)
                        changed = True

            module.exit_json(changed=changed, router=router, id=router['id'])

        elif state == 'absent':
            if not router:
                module.exit_json(changed=False)
            else:
                # We need to detach all internal interfaces on a router before
                # we will be allowed to delete it.
                ports = _router_internal_interfaces(cloud, router)
                router_id = router['id']
                for port in ports:
                    cloud.remove_router_interface(router, port_id=port['id'])
                cloud.delete_router(router_id)
                module.exit_json(changed=True)

    except sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Beispiel #28
0
def main():

    argument_spec = openstack_full_argument_spec(
        name=dict(required=True),
        id=dict(default=None),
        checksum=dict(default=None),
        disk_format=dict(default='qcow2',
                         choices=[
                             'ami', 'ari', 'aki', 'vhd', 'vmdk', 'raw',
                             'qcow2', 'vdi', 'iso', 'vhdx', 'ploop'
                         ]),
        container_format=dict(
            default='bare',
            choices=['ami', 'aki', 'ari', 'bare', 'ovf', 'ova', 'docker']),
        owner=dict(default=None),
        min_disk=dict(type='int', default=0),
        min_ram=dict(type='int', default=0),
        is_public=dict(type='bool', default=False),
        protected=dict(type='bool', default=False),
        filename=dict(default=None),
        ramdisk=dict(default=None),
        kernel=dict(default=None),
        properties=dict(type='dict', default={}),
        volume=dict(default=None),
        state=dict(default='present', choices=['absent', 'present']),
    )

    module_kwargs = openstack_module_kwargs(
        mutually_exclusive=[['filename', 'volume']], )
    module = AnsibleModule(argument_spec, **module_kwargs)

    sdk, cloud = openstack_cloud_from_module(module)
    try:

        changed = False
        if module.params['checksum']:
            image = cloud.get_image(
                name_or_id=None,
                filters={'checksum': module.params['checksum']})
        else:
            image = cloud.get_image(name_or_id=module.params['name'])

        if module.params['state'] == 'present':
            if not image:
                kwargs = {}
                if module.params['id'] is not None:
                    kwargs['id'] = module.params['id']
                image = cloud.create_image(
                    name=module.params['name'],
                    filename=module.params['filename'],
                    disk_format=module.params['disk_format'],
                    container_format=module.params['container_format'],
                    wait=module.params['wait'],
                    timeout=module.params['timeout'],
                    is_public=module.params['is_public'],
                    protected=module.params['protected'],
                    min_disk=module.params['min_disk'],
                    min_ram=module.params['min_ram'],
                    volume=module.params['volume'],
                    **kwargs)
                changed = True
                if not module.params['wait']:
                    module.exit_json(changed=changed, image=image, id=image.id)

            cloud.update_image_properties(image=image,
                                          kernel=module.params['kernel'],
                                          ramdisk=module.params['ramdisk'],
                                          protected=module.params['protected'],
                                          **module.params['properties'])
            image = cloud.get_image(name_or_id=image.id)
            module.exit_json(changed=changed, image=image, id=image.id)

        elif module.params['state'] == 'absent':
            if not image:
                changed = False
            else:
                cloud.delete_image(name_or_id=module.params['name'],
                                   wait=module.params['wait'],
                                   timeout=module.params['timeout'])
                changed = True
            module.exit_json(changed=changed)

    except sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e), extra_data=e.extra_data)
def main():
    argument_spec = openstack_full_argument_spec(
        uuid=dict(required=False),
        name=dict(required=False),
        instance_info=dict(type='dict', required=False),
        config_drive=dict(required=False),
        ironic_url=dict(required=False),
        state=dict(required=False, default='present'),
        maintenance=dict(required=False),
        maintenance_reason=dict(required=False),
        power=dict(required=False, default='present'),
        deploy=dict(required=False, default=True),
        wait=dict(type='bool', required=False, default=False),
        timeout=dict(required=False, type='int', default=1800),
    )
    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec, **module_kwargs)

    if module.params['wait']:
        min_version = '1.4.0'
    else:
        min_version = None

    if (module.params['auth_type'] in [None, 'None']
            and module.params['ironic_url'] is None):
        module.fail_json(msg="Authentication appears disabled, Please "
                         "define an ironic_url parameter")

    if (module.params['ironic_url']
            and module.params['auth_type'] in [None, 'None']):
        module.params['auth'] = dict(endpoint=module.params['ironic_url'])

    node_id = _choose_id_value(module)

    if not node_id:
        module.fail_json(msg="A uuid or name value must be defined "
                         "to use this module.")
    shade, cloud = openstack_cloud_from_module(module, min_version=min_version)
    try:
        node = cloud.get_machine(node_id)

        if node is None:
            module.fail_json(msg="node not found")

        uuid = node['uuid']
        instance_info = module.params['instance_info']
        changed = False
        wait = module.params['wait']
        timeout = module.params['timeout']

        # User has reqeusted desired state to be in maintenance state.
        if module.params['state'] is 'maintenance':
            module.params['maintenance'] = True

        if node['provision_state'] in [
                'cleaning', 'deleting', 'wait call-back'
        ]:
            module.fail_json(msg="Node is in %s state, cannot act upon the "
                             "request as the node is in a transition "
                             "state" % node['provision_state'])
        # TODO(TheJulia) This is in-development code, that requires
        # code in the shade library that is still in development.
        if _check_set_maintenance(module, cloud, node):
            if node['provision_state'] in 'active':
                module.exit_json(changed=True,
                                 result="Maintenance state changed")
            changed = True
            node = cloud.get_machine(node_id)

        if _check_set_power_state(module, cloud, node):
            changed = True
            node = cloud.get_machine(node_id)

        if _is_true(module.params['state']):
            if _is_false(module.params['deploy']):
                module.exit_json(changed=changed,
                                 result="User request has explicitly disabled "
                                 "deployment logic")

            if 'active' in node['provision_state']:
                module.exit_json(changed=changed,
                                 result="Node already in an active state.")

            if instance_info is None:
                module.fail_json(changed=changed,
                                 msg="When setting an instance to present, "
                                 "instance_info is a required variable.")

            # TODO(TheJulia): Update instance info, however info is
            # deployment specific. Perhaps consider adding rebuild
            # support, although there is a known desire to remove
            # rebuild support from Ironic at some point in the future.
            patch = _prepare_instance_info_patch(instance_info)
            cloud.set_node_instance_info(uuid, patch)
            cloud.validate_node(uuid)
            if not wait:
                cloud.activate_node(uuid, module.params['config_drive'])
            else:
                cloud.activate_node(uuid,
                                    configdrive=module.params['config_drive'],
                                    wait=wait,
                                    timeout=timeout)
            # TODO(TheJulia): Add more error checking..
            module.exit_json(changed=changed, result="node activated")

        elif _is_false(module.params['state']):
            if node['provision_state'] not in "deleted":
                cloud.purge_node_instance_info(uuid)
                if not wait:
                    cloud.deactivate_node(uuid)
                else:
                    cloud.deactivate_node(uuid, wait=wait, timeout=timeout)

                module.exit_json(changed=True, result="deleted")
            else:
                module.exit_json(changed=False, result="node not found")
        else:
            module.fail_json(msg="State must be present, absent, "
                             "maintenance, off")

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
def main():
    argument_spec = openstack_full_argument_spec(
        server=dict(required=True),
        action=dict(required=True, choices=['stop', 'start', 'pause', 'unpause',
                                            'lock', 'unlock', 'suspend', 'resume',
                                            'rebuild']),
        image=dict(required=False),
    )

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec, supports_check_mode=True,
                           required_if=[('action', 'rebuild', ['image'])],
                           **module_kwargs)

    if module._name == 'os_server_actions':
        module.deprecate("The 'os_server_actions' module is being renamed 'os_server_action'", version=2.8)

    action = module.params['action']
    wait = module.params['wait']
    timeout = module.params['timeout']
    image = module.params['image']

    if action in _admin_actions:
        shade, cloud = openstack_cloud_from_module(module)
    else:
        shade, cloud = openstack_cloud_from_module(module)
    try:
        server = cloud.get_server(module.params['server'])
        if not server:
            module.fail_json(msg='Could not find server %s' % server)
        status = server.status

        if module.check_mode:
            module.exit_json(changed=_system_state_change(action, status))

        if action == 'stop':
            if not _system_state_change(action, status):
                module.exit_json(changed=False)

            cloud.nova_client.servers.stop(server=server.id)
            if wait:
                _wait(timeout, cloud, server, action, module, shade)
                module.exit_json(changed=True)

        if action == 'start':
            if not _system_state_change(action, status):
                module.exit_json(changed=False)

            cloud.nova_client.servers.start(server=server.id)
            if wait:
                _wait(timeout, cloud, server, action, module, shade)
                module.exit_json(changed=True)

        if action == 'pause':
            if not _system_state_change(action, status):
                module.exit_json(changed=False)

            cloud.nova_client.servers.pause(server=server.id)
            if wait:
                _wait(timeout, cloud, server, action, module, shade)
                module.exit_json(changed=True)

        elif action == 'unpause':
            if not _system_state_change(action, status):
                module.exit_json(changed=False)

            cloud.nova_client.servers.unpause(server=server.id)
            if wait:
                _wait(timeout, cloud, server, action, module, shade)
            module.exit_json(changed=True)

        elif action == 'lock':
            # lock doesn't set a state, just do it
            cloud.nova_client.servers.lock(server=server.id)
            module.exit_json(changed=True)

        elif action == 'unlock':
            # unlock doesn't set a state, just do it
            cloud.nova_client.servers.unlock(server=server.id)
            module.exit_json(changed=True)

        elif action == 'suspend':
            if not _system_state_change(action, status):
                module.exit_json(changed=False)

            cloud.nova_client.servers.suspend(server=server.id)
            if wait:
                _wait(timeout, cloud, server, action, module, shade)
            module.exit_json(changed=True)

        elif action == 'resume':
            if not _system_state_change(action, status):
                module.exit_json(changed=False)

            cloud.nova_client.servers.resume(server=server.id)
            if wait:
                _wait(timeout, cloud, server, action, module, shade)
            module.exit_json(changed=True)

        elif action == 'rebuild':
            image = cloud.get_image(image)

            if image is None:
                module.fail_json(msg="Image does not exist")

            # rebuild doesn't set a state, just do it
            cloud.nova_client.servers.rebuild(server=server.id, image=image.id)
            if wait:
                _wait(timeout, cloud, server, action, module, shade)
            module.exit_json(changed=True)

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e), extra_data=e.extra_data)
def main():
    argument_spec = openstack_full_argument_spec(
        service=dict(type='str', required=True),
        endpoint_interface=dict(type='str',
                                required=True,
                                choices=['admin', 'public', 'internal']),
        url=dict(type='str', required=True),
        region=dict(type='str'),
        enabled=dict(type='bool', default=True),
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present']),
    )

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

    service_name_or_id = module.params['service']
    interface = module.params['endpoint_interface']
    url = module.params['url']
    region = module.params['region']
    enabled = module.params['enabled']
    state = module.params['state']

    sdk, cloud = openstack_cloud_from_module(module)
    try:

        service = cloud.get_service(service_name_or_id)
        if service is None:
            module.fail_json(msg='Service %s does not exist' %
                             service_name_or_id)

        filters = dict(service_id=service.id, interface=interface)
        if region is not None:
            filters['region'] = region
        endpoints = cloud.search_endpoints(filters=filters)

        if len(endpoints) > 1:
            module.fail_json(msg='Service %s, interface %s and region %s are '
                             'not unique' %
                             (service_name_or_id, interface, region))
        elif len(endpoints) == 1:
            endpoint = endpoints[0]
        else:
            endpoint = None

        if module.check_mode:
            module.exit_json(changed=_system_state_change(module, endpoint))

        if state == 'present':
            if endpoint is None:
                result = cloud.create_endpoint(service_name_or_id=service,
                                               url=url,
                                               interface=interface,
                                               region=region,
                                               enabled=enabled)
                endpoint = result[0]
                changed = True
            else:
                if _needs_update(module, endpoint):
                    endpoint = cloud.update_endpoint(endpoint.id,
                                                     url=url,
                                                     enabled=enabled)
                    changed = True
                else:
                    changed = False
            module.exit_json(changed=changed, endpoint=endpoint)

        elif state == 'absent':
            if endpoint is None:
                changed = False
            else:
                cloud.delete_endpoint(endpoint.id)
                changed = True
            module.exit_json(changed=changed)

    except sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Beispiel #32
0
def main():
    argument_spec = openstack_full_argument_spec(
        state=dict(required=False,
                   default='present',
                   choices=['absent', 'present']),
        name=dict(required=False),

        # required when state is 'present'
        ram=dict(required=False, type='int'),
        vcpus=dict(required=False, type='int'),
        disk=dict(required=False, type='int'),
        ephemeral=dict(required=False, default=0, type='int'),
        swap=dict(required=False, default=0, type='int'),
        rxtx_factor=dict(required=False, default=1.0, type='float'),
        is_public=dict(required=False, default=True, type='bool'),
        flavorid=dict(required=False, default="auto"),
        extra_specs=dict(required=False, default=None, type='dict'),
    )

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           required_if=[('state', 'present',
                                         ['ram', 'vcpus', 'disk'])],
                           **module_kwargs)

    state = module.params['state']
    name = module.params['name']
    extra_specs = module.params['extra_specs'] or {}

    sdk, cloud = openstack_cloud_from_module(module)
    try:
        flavor = cloud.get_flavor(name)

        if module.check_mode:
            module.exit_json(changed=_system_state_change(module, flavor))

        if state == 'present':
            old_extra_specs = {}
            require_update = False

            if flavor:
                old_extra_specs = flavor['extra_specs']
                for param_key in [
                        'ram', 'vcpus', 'disk', 'ephemeral', 'swap',
                        'rxtx_factor', 'is_public'
                ]:
                    if module.params[param_key] != flavor[param_key]:
                        require_update = True
                        break

            if flavor and require_update:
                cloud.delete_flavor(name)
                flavor = None

            if not flavor:
                flavor = cloud.create_flavor(
                    name=name,
                    ram=module.params['ram'],
                    vcpus=module.params['vcpus'],
                    disk=module.params['disk'],
                    flavorid=module.params['flavorid'],
                    ephemeral=module.params['ephemeral'],
                    swap=module.params['swap'],
                    rxtx_factor=module.params['rxtx_factor'],
                    is_public=module.params['is_public'])
                changed = True
            else:
                changed = False

            new_extra_specs = dict([(k, str(v))
                                    for k, v in extra_specs.items()])
            unset_keys = set(old_extra_specs.keys()) - set(extra_specs.keys())

            if unset_keys and not require_update:
                cloud.unset_flavor_specs(flavor['id'], unset_keys)

            if old_extra_specs != new_extra_specs:
                cloud.set_flavor_specs(flavor['id'], extra_specs)

            changed = (changed or old_extra_specs != new_extra_specs)

            module.exit_json(changed=changed, flavor=flavor, id=flavor['id'])

        elif state == 'absent':
            if flavor:
                cloud.delete_flavor(name)
                module.exit_json(changed=True)
            module.exit_json(changed=False)

    except sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Beispiel #33
0
def main():
    argument_spec = openstack_full_argument_spec(
        role=dict(required=True),
        user=dict(required=False),
        group=dict(required=False),
        project=dict(required=False),
        domain=dict(required=False),
        state=dict(default='present', choices=['absent', 'present']),
    )

    module_kwargs = openstack_module_kwargs(
        required_one_of=[
            ['user', 'group']
        ])
    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

    role = module.params.get('role')
    user = module.params.get('user')
    group = module.params.get('group')
    project = module.params.get('project')
    domain = module.params.get('domain')
    state = module.params.get('state')

    # role grant/revoke API introduced in 1.5.0
    shade, cloud = openstack_cloud_from_module(
        module, min_version='1.5.0')
    try:
        filters = {}

        r = cloud.get_role(role)
        if r is None:
            module.fail_json(msg="Role %s is not valid" % role)
        filters['role'] = r['id']

        if user:
            u = cloud.get_user(user)
            if u is None:
                module.fail_json(msg="User %s is not valid" % user)
            filters['user'] = u['id']
        if group:
            g = cloud.get_group(group)
            if g is None:
                module.fail_json(msg="Group %s is not valid" % group)
            filters['group'] = g['id']
        if domain:
            d = cloud.get_domain(domain)
            if d is None:
                module.fail_json(msg="Domain %s is not valid" % domain)
            filters['domain'] = d['id']
        if project:
            if domain:
                p = cloud.get_project(project, domain_id=filters['domain'])
            else:
                p = cloud.get_project(project)

            if p is None:
                module.fail_json(msg="Project %s is not valid" % project)
            filters['project'] = p['id']

        assignment = cloud.list_role_assignments(filters=filters)

        if module.check_mode:
            module.exit_json(changed=_system_state_change(state, assignment))

        changed = False

        if state == 'present':
            if not assignment:
                kwargs = _build_kwargs(user, group, project, domain)
                cloud.grant_role(role, **kwargs)
                changed = True

        elif state == 'absent':
            if assignment:
                kwargs = _build_kwargs(user, group, project, domain)
                cloud.revoke_role(role, **kwargs)
                changed = True

        module.exit_json(changed=changed)

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Beispiel #34
0
def main():
    argument_spec = openstack_full_argument_spec(
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present']),
        cluster=dict(type='str', alias='cluster_id', required=True),
        name=dict(type='str'),
        flavor=dict(type='str'),
        availability_zone=dict(type='str', default="eu-de-01"),
        key_name=dict(type='str'),
        count=dict(type='int'),
        root_volume=dict(type='dict'),
        data_volumes=dict(type='list'),
        public_ip=dict(type='dict'),
    )

    # FIXME: define some more constraints like mutual exclusives
    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           supports_check_mode=False,
                           **module_kwargs)

    state = module.params['state']
    clustername_id = module.params['cluster']

    cloud = connect_from_ansible(module)
    try:
        # temporary fix for the fact that the new RDS service is not yet in catalog
        cloud.add_service(cce_service.CceService("ccev2.0", aliases=["cce2"]))

        # search for cluster by name or id
        cluster = cloud.cce2.find_cluster(clustername_id)
        if cluster:
            if state == 'present':
                # filter existing nodes with given spec
                existing_nodes, existing_ids = _current_spec_nodes(
                    cloud, cluster.id, **module.params)
                new_count = int(module.params['count']) - len(existing_nodes)

                if new_count > 0:
                    _add_nodes(cloud, cluster.id, new_count, **module.params)
                    changed = True
                    if module.params['wait']:
                        new_nodes = _new_nodes(cloud, cluster.id, existing_ids,
                                               **module.params)
                        cloud.cce2.wait_for_status_nodes(cluster.id, new_nodes)
                    existing_nodes, existing_ids = _current_spec_nodes(
                        cloud, cluster.id, **module.params)

                elif new_count < 0:
                    nodes_to_delete = existing_nodes[new_count:]
                    if nodes_to_delete:
                        for node in nodes_to_delete:
                            cloud.cce2.delete_cluster_node(cluster.id, node)
                        changed = True
                        if module.params['wait']:
                            cloud.cce2.wait_for_delete_nodes(
                                cluster.id, nodes_to_delete)
                        existing_nodes, existing_ids = _current_spec_nodes(
                            cloud, cluster.id, **module.params)
                else:
                    changed = False
                module.exit_json(changed=changed,
                                 ids=existing_ids,
                                 nodes=existing_nodes)

            elif state == 'absent':
                nodes_to_delete = _filter_for_delete(cloud, cluster.id,
                                                     **module.params)
                if nodes_to_delete:
                    for node in nodes_to_delete:
                        cloud.cce2.delete_cluster_node(cluster.id, node)
                    changed = True
                    if module.params['wait']:
                        cloud.cce2.wait_for_delete_nodes(
                            cluster.id, nodes_to_delete)
                else:
                    changed = False
                module.exit_json(changed=changed)

        else:
            module.fail_json(msg=str("Cluster " + clustername_id +
                                     " not found"))

    except exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
def main():
    argument_spec = openstack_full_argument_spec(
        server=dict(required=True),
        action=dict(required=True,
                    choices=[
                        'stop', 'start', 'pause', 'unpause', 'lock', 'unlock',
                        'suspend', 'resume', 'rebuild'
                    ]),
        image=dict(required=False),
    )

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           required_if=[('action', 'rebuild', ['image'])],
                           **module_kwargs)

    if module._name == 'os_server_actions':
        module.deprecate(
            "The 'os_server_actions' module is being renamed 'os_server_action'",
            version=2.8)

    if not HAS_SHADE:
        module.fail_json(msg='shade is required for this module')

    action = module.params['action']
    wait = module.params['wait']
    timeout = module.params['timeout']
    image = module.params['image']

    try:
        if action in _admin_actions:
            cloud = shade.operator_cloud(**module.params)
        else:
            cloud = shade.openstack_cloud(**module.params)
        server = cloud.get_server(module.params['server'])
        if not server:
            module.fail_json(msg='Could not find server %s' % server)
        status = server.status

        if module.check_mode:
            module.exit_json(changed=_system_state_change(action, status))

        if action == 'stop':
            if not _system_state_change(action, status):
                module.exit_json(changed=False)

            cloud.nova_client.servers.stop(server=server.id)
            if wait:
                _wait(timeout, cloud, server, action, module)
                module.exit_json(changed=True)

        if action == 'start':
            if not _system_state_change(action, status):
                module.exit_json(changed=False)

            cloud.nova_client.servers.start(server=server.id)
            if wait:
                _wait(timeout, cloud, server, action, module)
                module.exit_json(changed=True)

        if action == 'pause':
            if not _system_state_change(action, status):
                module.exit_json(changed=False)

            cloud.nova_client.servers.pause(server=server.id)
            if wait:
                _wait(timeout, cloud, server, action, module)
                module.exit_json(changed=True)

        elif action == 'unpause':
            if not _system_state_change(action, status):
                module.exit_json(changed=False)

            cloud.nova_client.servers.unpause(server=server.id)
            if wait:
                _wait(timeout, cloud, server, action, module)
            module.exit_json(changed=True)

        elif action == 'lock':
            # lock doesn't set a state, just do it
            cloud.nova_client.servers.lock(server=server.id)
            module.exit_json(changed=True)

        elif action == 'unlock':
            # unlock doesn't set a state, just do it
            cloud.nova_client.servers.unlock(server=server.id)
            module.exit_json(changed=True)

        elif action == 'suspend':
            if not _system_state_change(action, status):
                module.exit_json(changed=False)

            cloud.nova_client.servers.suspend(server=server.id)
            if wait:
                _wait(timeout, cloud, server, action, module)
            module.exit_json(changed=True)

        elif action == 'resume':
            if not _system_state_change(action, status):
                module.exit_json(changed=False)

            cloud.nova_client.servers.resume(server=server.id)
            if wait:
                _wait(timeout, cloud, server, action, module)
            module.exit_json(changed=True)

        elif action == 'rebuild':
            image = cloud.get_image(image)

            if image is None:
                module.fail_json(msg="Image does not exist")

            # rebuild doesn't set a state, just do it
            cloud.nova_client.servers.rebuild(server=server.id, image=image.id)
            if wait:
                _wait(timeout, cloud, server, action, module)
            module.exit_json(changed=True)

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e), extra_data=e.extra_data)
Beispiel #36
0
def main():
    ipv6_mode_choices = ['dhcpv6-stateful', 'dhcpv6-stateless', 'slaac']
    argument_spec = openstack_full_argument_spec(
        name=dict(required=True),
        network_name=dict(default=None),
        cidr=dict(default=None),
        ip_version=dict(default='4', choices=['4', '6']),
        enable_dhcp=dict(default='true', type='bool'),
        gateway_ip=dict(default=None),
        no_gateway_ip=dict(default=False, type='bool'),
        dns_nameservers=dict(default=None, type='list'),
        allocation_pool_start=dict(default=None),
        allocation_pool_end=dict(default=None),
        host_routes=dict(default=None, type='list'),
        ipv6_ra_mode=dict(default=None, choice=ipv6_mode_choices),
        ipv6_address_mode=dict(default=None, choice=ipv6_mode_choices),
        use_default_subnetpool=dict(default=False, type='bool'),
        state=dict(default='present', choices=['absent', 'present']),
        project=dict(default=None))

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

    state = module.params['state']
    network_name = module.params['network_name']
    cidr = module.params['cidr']
    ip_version = module.params['ip_version']
    enable_dhcp = module.params['enable_dhcp']
    subnet_name = module.params['name']
    gateway_ip = module.params['gateway_ip']
    no_gateway_ip = module.params['no_gateway_ip']
    dns = module.params['dns_nameservers']
    pool_start = module.params['allocation_pool_start']
    pool_end = module.params['allocation_pool_end']
    host_routes = module.params['host_routes']
    ipv6_ra_mode = module.params['ipv6_ra_mode']
    ipv6_a_mode = module.params['ipv6_address_mode']
    use_default_subnetpool = module.params['use_default_subnetpool']
    project = module.params.pop('project')

    # Check for required parameters when state == 'present'
    if state == 'present':
        if not module.params['network_name']:
            module.fail_json(msg='network_name required with present state')
        if not module.params['cidr'] and not use_default_subnetpool:
            module.fail_json(msg='cidr or use_default_subnetpool required '
                             'with present state')

    if pool_start and pool_end:
        pool = [dict(start=pool_start, end=pool_end)]
    elif pool_start or pool_end:
        module.fail_json(msg='allocation pool requires start and end values')
    else:
        pool = None

    if no_gateway_ip and gateway_ip:
        module.fail_json(msg='no_gateway_ip is not allowed with gateway_ip')

    sdk, cloud = openstack_cloud_from_module(module)
    try:
        if project is not None:
            proj = cloud.get_project(project)
            if proj is None:
                module.fail_json(msg='Project %s could not be found' % project)
            project_id = proj['id']
            filters = {'tenant_id': project_id}
        else:
            project_id = None
            filters = None

        subnet = cloud.get_subnet(subnet_name, filters=filters)

        if module.check_mode:
            module.exit_json(
                changed=_system_state_change(module, subnet, cloud))

        if state == 'present':
            if not subnet:
                kwargs = dict(ip_version=ip_version,
                              enable_dhcp=enable_dhcp,
                              subnet_name=subnet_name,
                              gateway_ip=gateway_ip,
                              disable_gateway_ip=no_gateway_ip,
                              dns_nameservers=dns,
                              allocation_pools=pool,
                              host_routes=host_routes,
                              ipv6_ra_mode=ipv6_ra_mode,
                              ipv6_address_mode=ipv6_a_mode,
                              tenant_id=project_id)
                if use_default_subnetpool:
                    kwargs['use_default_subnetpool'] = use_default_subnetpool
                subnet = cloud.create_subnet(network_name, cidr, **kwargs)
                changed = True
            else:
                if _needs_update(subnet, module, cloud):
                    cloud.update_subnet(subnet['id'],
                                        subnet_name=subnet_name,
                                        enable_dhcp=enable_dhcp,
                                        gateway_ip=gateway_ip,
                                        disable_gateway_ip=no_gateway_ip,
                                        dns_nameservers=dns,
                                        allocation_pools=pool,
                                        host_routes=host_routes)
                    changed = True
                else:
                    changed = False
            module.exit_json(changed=changed, subnet=subnet, id=subnet['id'])

        elif state == 'absent':
            if not subnet:
                changed = False
            else:
                changed = True
                cloud.delete_subnet(subnet_name)
            module.exit_json(changed=changed)

    except sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
def main():
    argument_spec = openstack_full_argument_spec(
        description=dict(default=None),
        enabled=dict(default=True, type='bool'),
        name=dict(required=True),
        service_type=dict(required=True),
        state=dict(default='present', choices=['absent', 'present']),
    )

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

    description = module.params['description']
    enabled = module.params['enabled']
    name = module.params['name']
    state = module.params['state']
    service_type = module.params['service_type']

    shade, cloud = openstack_cloud_from_module(module, min_version='1.6.0')
    try:
        services = cloud.search_services(name_or_id=name,
                                         filters=dict(type=service_type))

        if len(services) > 1:
            module.fail_json(msg='Service name %s and type %s are not unique' %
                             (name, service_type))
        elif len(services) == 1:
            service = services[0]
        else:
            service = None

        if module.check_mode:
            module.exit_json(changed=_system_state_change(module, service))

        if state == 'present':
            if service is None:
                service = cloud.create_service(name=name, description=description,
                                               type=service_type, enabled=True)
                changed = True
            else:
                if _needs_update(module, service):
                    service = cloud.update_service(
                        service.id, name=name, type=service_type, enabled=enabled,
                        description=description)
                    changed = True
                else:
                    changed = False
            module.exit_json(changed=changed, service=service, id=service.id)

        elif state == 'absent':
            if service is None:
                changed = False
            else:
                cloud.delete_service(service.id)
                changed = True
            module.exit_json(changed=changed)

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Beispiel #38
0
def main():
    argument_spec = openstack_full_argument_spec(
        state=dict(required=False,
                   default='present',
                   choices=['absent', 'present']),
        target_project_id=dict(required=True, type='str'),
        resource_type=dict(required=True, type='str'),
        resource_name=dict(required=True, type='str'),
    )

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           required_if=[('state', 'present',
                                         ['target_project_id'])],
                           **module_kwargs)

    if not HAS_SHADE:
        module.fail_json(msg='shade is required for this module')

    changed = False
    state = module.params['state']
    resource_name = module.params['resource_name']
    resource_type = module.params['resource_type']
    target_project_id = module.params['target_project_id']

    try:
        cloud = shade.operator_cloud(**module.params)

        if resource_type == 'nova_flavor':
            # returns Munch({'NAME_ATTR': 'name',
            # 'tenant_id': u'37e55da59ec842649d84230f3a24eed5',
            # 'HUMAN_ID': False,
            # 'flavor_id': u'6d4d37b9-0480-4a8c-b8c9-f77deaad73f9',
            #  'request_ids': [], 'human_id': None}),
            _get_resource = cloud.get_flavor
            _list_resource_access = cloud.list_flavor_access
            _add_resource_access = cloud.add_flavor_access
            _remove_resource_access = cloud.remove_flavor_access
        elif resource_type == 'cinder_volume_type':
            # returns [Munch({
            # 'project_id': u'178cdb9955b047eea7afbe582038dc94',
            #  'properties': {'request_ids': [], 'NAME_ATTR': 'name',
            #  'human_id': None,
            # 'HUMAN_ID': False},
            #  'id': u'd5573023-b290-42c8-b232-7c5ca493667f'}),
            _get_resource = cloud.get_volume_type
            _list_resource_access = cloud.get_volume_type_access
            _add_resource_access = cloud.add_volume_type_access
            _remove_resource_access = cloud.remove_volume_type_access
        else:
            module.exit_json(changed=False,
                             resource_name=resource_name,
                             resource_type=resource_type,
                             error="Not implemented.")

        resource = _get_resource(resource_name)
        if not resource:
            module.exit_json(changed=False,
                             resource_name=resource_name,
                             resource_type=resource_type,
                             error="Not found.")
        resource_id = getattr(resource, 'id', resource['id'])
        # _list_resource_access returns a list of dicts containing 'project_id'
        acls = _list_resource_access(resource_id)

        if not all(acl.get('project_id') for acl in acls):
            module.exit_json(changed=False,
                             resource_name=resource_name,
                             resource_type=resource_type,
                             error="Missing project_id in resource output.")
        allowed_tenants = [acl['project_id'] for acl in acls]

        changed_access = any(
            (state == 'present'
             and target_project_id not in allowed_tenants, state == 'absent'
             and target_project_id in allowed_tenants))
        if module.check_mode or not changed_access:
            module.exit_json(changed=changed_access,
                             resource=resource,
                             id=resource_id)

        if state == 'present':
            _add_resource_access(resource_id, target_project_id)
        elif state == 'absent':
            _remove_resource_access(resource_id, target_project_id)

        module.exit_json(changed=True, resource=resource, id=resource_id)

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e), **module.params)
Beispiel #39
0
def main():
    argument_spec = openstack_full_argument_spec(
        security_group=dict(required=True),
        # NOTE(Shrews): None is an acceptable protocol value for
        # Neutron, but Nova will balk at this.
        protocol=dict(default=None,
                      choices=[None, 'tcp', 'udp', 'icmp', '112']),
        port_range_min=dict(required=False, type='int'),
        port_range_max=dict(required=False, type='int'),
        remote_ip_prefix=dict(required=False, default=None),
        remote_group=dict(required=False, default=None),
        ethertype=dict(default='IPv4',
                       choices=['IPv4', 'IPv6']),
        direction=dict(default='ingress',
                       choices=['egress', 'ingress']),
        state=dict(default='present',
                   choices=['absent', 'present']),
        project=dict(default=None),
    )

    module_kwargs = openstack_module_kwargs(
        mutually_exclusive=[
            ['remote_ip_prefix', 'remote_group'],
        ]
    )

    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

    state = module.params['state']
    security_group = module.params['security_group']
    remote_group = module.params['remote_group']
    project = module.params['project']
    changed = False

    sdk, cloud = openstack_cloud_from_module(module)
    try:
        if project is not None:
            proj = cloud.get_project(project)
            if proj is None:
                module.fail_json(msg='Project %s could not be found' % project)
            project_id = proj['id']
        else:
            project_id = cloud.current_project_id

        if project_id:
            filters = {'tenant_id': project_id}
        else:
            filters = None

        secgroup = cloud.get_security_group(security_group, filters=filters)

        if remote_group:
            remotegroup = cloud.get_security_group(remote_group,
                                                   filters=filters)
        else:
            remotegroup = {'id': None}

        if module.check_mode:
            module.exit_json(changed=_system_state_change(module, secgroup, remotegroup))

        if state == 'present':
            if not secgroup:
                module.fail_json(msg='Could not find security group %s' %
                                 security_group)

            rule = _find_matching_rule(module, secgroup, remotegroup)
            if not rule:
                kwargs = {}
                if project_id:
                    kwargs['project_id'] = project_id
                rule = cloud.create_security_group_rule(
                    secgroup['id'],
                    port_range_min=module.params['port_range_min'],
                    port_range_max=module.params['port_range_max'],
                    protocol=module.params['protocol'],
                    remote_ip_prefix=module.params['remote_ip_prefix'],
                    remote_group_id=remotegroup['id'],
                    direction=module.params['direction'],
                    ethertype=module.params['ethertype'],
                    **kwargs
                )
                changed = True
            module.exit_json(changed=changed, rule=rule, id=rule['id'])

        if state == 'absent' and secgroup:
            rule = _find_matching_rule(module, secgroup, remotegroup)
            if rule:
                cloud.delete_security_group_rule(rule['id'])
                changed = True

        module.exit_json(changed=changed)

    except sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Beispiel #40
0
def main():
    argument_spec = openstack_full_argument_spec(
        name=dict(required=True),
        zone_type=dict(required=False, choice=['primary', 'secondary']),
        email=dict(required=False, default=None),
        description=dict(required=False, default=None),
        ttl=dict(required=False, default=None, type='int'),
        masters=dict(required=False, default=None, type='list'),
        state=dict(default='present', choices=['absent', 'present']),
    )

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

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

    shade, cloud = openstack_cloud_from_module(module, min_version='1.8.0')
    try:
        zone = cloud.get_zone(name)

        if state == 'present':
            zone_type = module.params.get('zone_type')
            email = module.params.get('email')
            description = module.params.get('description')
            ttl = module.params.get('ttl')
            masters = module.params.get('masters')

            if module.check_mode:
                module.exit_json(changed=_system_state_change(state, email,
                                                              description, ttl,
                                                              masters, zone))

            if zone is None:
                zone = cloud.create_zone(
                    name=name, zone_type=zone_type, email=email,
                    description=description, ttl=ttl, masters=masters)
                changed = True
            else:
                if masters is None:
                    masters = []

                pre_update_zone = zone
                changed = _system_state_change(state, email,
                                               description, ttl,
                                               masters, pre_update_zone)
                if changed:
                    zone = cloud.update_zone(
                        name, email=email,
                        description=description,
                        ttl=ttl, masters=masters)
            module.exit_json(changed=changed, zone=zone)

        elif state == 'absent':
            if module.check_mode:
                module.exit_json(changed=_system_state_change(state, None,
                                                              None, None,
                                                              None, zone))

            if zone is None:
                changed = False
            else:
                cloud.delete_zone(name)
                changed = True
            module.exit_json(changed=changed)

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Beispiel #41
0
def main():
    argument_spec = openstack_full_argument_spec(
        reuse=dict(type='bool', default=True),
        state=dict(default='present', choices=['absent', 'present']),
        eip_id=dict(type='str'))

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec, **module_kwargs)

    state = module.params['state']

    cloud = connect_from_ansible(module)
    try:
        if state == 'present':

            # find the external network the EIP belongs to
            external_networks = list(
                cloud.network.networks(
                    is_router_external=True,
                    project_id=cloud.session.get_project_id()))
            if not external_networks:
                module.fail_json(msg="No external network for project.")
            external_network = external_networks[0]

            # try to find a free eip first
            eip = None
            if module.params['reuse']:
                eips = cloud.network.ips(
                    floating_network_id=external_network.id,
                    project_id=cloud.session.get_project_id())
                eips = list(filter(lambda ip: ip.port_id is None, eips))
                if eips:
                    eip = eips[0]
                changed = False
            if not eip:
                # if none found: allocate a new EIP
                eip = cloud.network.create_ip(
                    floating_network_id=external_network.id)
                changed = True
            module.exit_json(changed=changed, eip=eip.copy(), id=eip.id)

        elif state == 'absent':
            eip_id = module.params['eip_id']
            eip = cloud.network.get_ip(eip_id)
            if not eip:
                module.exit_json(changed=False)
            else:
                cloud.network.delete_ip(eip_id)
                module.exit_json(changed=True)

        elif state == 'unbind':
            eip_id = module.params['eip_id']
            eip = cloud.network.get_ip(eip_id)
            if not eip:
                module.exit_json(changed=False)
            else:
                cloud.network.delete_port(eip.port_id)
                module.exit_json(changed=True)

    except exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Beispiel #42
0
def main():
    argument_spec = openstack_full_argument_spec(
        role=dict(required=True),
        user=dict(required=False),
        group=dict(required=False),
        project=dict(required=False),
        domain=dict(required=False),
        state=dict(default='present', choices=['absent', 'present']),
    )

    module_kwargs = openstack_module_kwargs(
        required_one_of=[['user', 'group']])
    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

    # role grant/revoke API introduced in 1.5.0
    if not HAS_SHADE or (StrictVersion(shade.__version__) <
                         StrictVersion('1.5.0')):
        module.fail_json(
            msg='shade 1.5.0 or higher is required for this module')

    role = module.params.pop('role')
    user = module.params.pop('user')
    group = module.params.pop('group')
    project = module.params.pop('project')
    domain = module.params.pop('domain')
    state = module.params.pop('state')

    try:
        cloud = shade.operator_cloud(**module.params)

        filters = {}

        r = cloud.get_role(role)
        if r is None:
            module.fail_json(msg="Role %s is not valid" % role)
        filters['role'] = r['id']

        if user:
            u = cloud.get_user(user)
            if u is None:
                module.fail_json(msg="User %s is not valid" % user)
            filters['user'] = u['id']
        if group:
            g = cloud.get_group(group)
            if g is None:
                module.fail_json(msg="Group %s is not valid" % group)
            filters['group'] = g['id']
        if domain:
            d = cloud.get_domain(domain)
            if d is None:
                module.fail_json(msg="Domain %s is not valid" % domain)
            filters['domain'] = d['id']
        if project:
            if domain:
                p = cloud.get_project(project, domain_id=filters['domain'])
            else:
                p = cloud.get_project(project)

            if p is None:
                module.fail_json(msg="Project %s is not valid" % project)
            filters['project'] = p['id']

        assignment = cloud.list_role_assignments(filters=filters)

        if module.check_mode:
            module.exit_json(changed=_system_state_change(state, assignment))

        changed = False

        if state == 'present':
            if not assignment:
                kwargs = _build_kwargs(user, group, project, domain)
                cloud.grant_role(role, **kwargs)
                changed = True

        elif state == 'absent':
            if assignment:
                kwargs = _build_kwargs(user, group, project, domain)
                cloud.revoke_role(role, **kwargs)
                changed = True

        module.exit_json(changed=changed)

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
def main():
    argument_spec = openstack_full_argument_spec(
        name=dict(required=True),
        metadata=dict(required=False, default=None, type='dict'),
        availability_zone=dict(required=False, default=None),
        hosts=dict(required=False, default=None, type='list'),
        state=dict(default='present', choices=['absent', 'present']),
    )

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

    name = module.params['name']
    metadata = module.params['metadata']
    availability_zone = module.params['availability_zone']
    hosts = module.params['hosts']
    state = module.params['state']

    if metadata is not None:
        metadata.pop('availability_zone', None)

    shade, cloud = openstack_cloud_from_module(module, min_version='1.9.0')
    try:
        aggregates = cloud.search_aggregates(name_or_id=name)

        if len(aggregates) == 1:
            aggregate = aggregates[0]
        elif len(aggregates) == 0:
            aggregate = None
        else:
            raise Exception("Should not happen")

        if module.check_mode:
            module.exit_json(changed=_system_state_change(module, aggregate))

        if state == 'present':
            if aggregate is None:
                aggregate = cloud.create_aggregate(name=name,
                                                   availability_zone=availability_zone)
                if hosts:
                    for h in hosts:
                        cloud.add_host_to_aggregate(aggregate.id, h)
                if metadata:
                    cloud.set_aggregate_metadata(aggregate.id, metadata)
                changed = True
            else:
                if _needs_update(module, aggregate):
                    if availability_zone is not None:
                        aggregate = cloud.update_aggregate(aggregate.id, name=name,
                                                           availability_zone=availability_zone)
                    if metadata is not None:
                        metas = metadata
                        for i in (set(aggregate.metadata.keys()) - set(metadata.keys())):
                            if i != 'availability_zone':
                                metas[i] = None
                        cloud.set_aggregate_metadata(aggregate.id, metas)
                    if hosts is not None:
                        for i in (set(aggregate.hosts) - set(hosts)):
                            cloud.remove_host_from_aggregate(aggregate.id, i)
                        for i in (set(hosts) - set(aggregate.hosts)):
                            cloud.add_host_to_aggregate(aggregate.id, i)
                    changed = True
                else:
                    changed = False
            module.exit_json(changed=changed)

        elif state == 'absent':
            if aggregate is None:
                changed = False
            else:
                cloud.delete_aggregate(aggregate.id)
                changed = True
            module.exit_json(changed=changed)

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Beispiel #44
0
def main():
    argument_spec = openstack_full_argument_spec(
        zone=dict(required=True),
        name=dict(required=True),
        recordset_type=dict(required=False),
        records=dict(required=False, type='list'),
        description=dict(required=False, default=None),
        ttl=dict(required=False, default=None, type='int'),
        state=dict(default='present', choices=['absent', 'present']),
    )

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           required_if=[('state', 'present',
                                         ['recordset_type', 'records'])],
                           supports_check_mode=True,
                           **module_kwargs)

    zone = module.params.get('zone')
    name = module.params.get('name')
    state = module.params.get('state')

    shade, cloud = openstack_cloud_from_module(module, min_version='1.9.0')
    try:
        recordset_type = module.params.get('recordset_type')
        recordset_filter = {'type': recordset_type}

        recordsets = cloud.search_recordsets(zone,
                                             name_or_id=name + '.' + zone,
                                             filters=recordset_filter)

        if len(recordsets) == 1:
            recordset = recordsets[0]
            try:
                recordset_id = recordset['id']
            except KeyError as e:
                module.fail_json(msg=str(e))
        else:
            # recordsets is filtered by type and should never be more than 1 return
            recordset = None

        if state == 'present':
            records = module.params.get('records')
            description = module.params.get('description')
            ttl = module.params.get('ttl')

            if module.check_mode:
                module.exit_json(changed=_system_state_change(
                    state, records, description, ttl, zone, recordset))

            if recordset is None:
                recordset = cloud.create_recordset(
                    zone=zone,
                    name=name,
                    recordset_type=recordset_type,
                    records=records,
                    description=description,
                    ttl=ttl)
                changed = True
            else:
                if records is None:
                    records = []

                pre_update_recordset = recordset
                changed = _system_state_change(state, records, description,
                                               ttl, zone, pre_update_recordset)
                if changed:
                    zone = cloud.update_recordset(zone,
                                                  recordset_id,
                                                  records=records,
                                                  description=description,
                                                  ttl=ttl)

            module.exit_json(changed=changed, recordset=recordset)

        elif state == 'absent':
            if module.check_mode:
                module.exit_json(changed=_system_state_change(
                    state, None, None, None, None, recordset))

            if recordset is None:
                changed = False
            else:
                cloud.delete_recordset(zone, recordset_id)
                changed = True
            module.exit_json(changed=changed)

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
def main():
    argument_spec = openstack_full_argument_spec(
        name=dict(required=True),
        metadata=dict(required=False, default=None, type='dict'),
        availability_zone=dict(required=False, default=None),
        hosts=dict(required=False, default=None, type='list'),
        state=dict(default='present', choices=['absent', 'present']),
    )

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

    name = module.params['name']
    metadata = module.params['metadata']
    availability_zone = module.params['availability_zone']
    hosts = module.params['hosts']
    state = module.params['state']

    if metadata is not None:
        metadata.pop('availability_zone', None)

    sdk, cloud = openstack_cloud_from_module(module)
    try:
        aggregates = cloud.search_aggregates(name_or_id=name)

        if len(aggregates) == 1:
            aggregate = aggregates[0]
        elif len(aggregates) == 0:
            aggregate = None
        else:
            raise Exception("Should not happen")

        if module.check_mode:
            module.exit_json(changed=_system_state_change(module, aggregate))

        if state == 'present':
            if aggregate is None:
                aggregate = cloud.create_aggregate(name=name,
                                                   availability_zone=availability_zone)
                if hosts:
                    for h in hosts:
                        cloud.add_host_to_aggregate(aggregate.id, h)
                if metadata:
                    cloud.set_aggregate_metadata(aggregate.id, metadata)
                changed = True
            else:
                if _needs_update(module, aggregate):
                    if availability_zone is not None:
                        aggregate = cloud.update_aggregate(aggregate.id, name=name,
                                                           availability_zone=availability_zone)
                    if metadata is not None:
                        metas = metadata
                        for i in (set(aggregate.metadata.keys()) - set(metadata.keys())):
                            if i != 'availability_zone':
                                metas[i] = None
                        cloud.set_aggregate_metadata(aggregate.id, metas)
                    if hosts is not None:
                        for i in (set(aggregate.hosts) - set(hosts)):
                            cloud.remove_host_from_aggregate(aggregate.id, i)
                        for i in (set(hosts) - set(aggregate.hosts)):
                            cloud.add_host_to_aggregate(aggregate.id, i)
                    changed = True
                else:
                    changed = False
            module.exit_json(changed=changed)

        elif state == 'absent':
            if aggregate is None:
                changed = False
            else:
                cloud.delete_aggregate(aggregate.id)
                changed = True
            module.exit_json(changed=changed)

    except sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Beispiel #46
0
def main():
    argument_spec = openstack_full_argument_spec(
        name=dict(required=True),
        shared=dict(default=False, type='bool'),
        admin_state_up=dict(default=True, type='bool'),
        external=dict(default=False, type='bool'),
        provider_physical_network=dict(required=False),
        provider_network_type=dict(required=False),
        provider_segmentation_id=dict(required=False, type='int'),
        state=dict(default='present', choices=['absent', 'present']),
        project=dict(default=None),
        port_security_enabled=dict(type='bool'),
        mtu=dict(required=False, type='int'))

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec, **module_kwargs)

    state = module.params['state']
    name = module.params['name']
    shared = module.params['shared']
    admin_state_up = module.params['admin_state_up']
    external = module.params['external']
    provider_physical_network = module.params['provider_physical_network']
    provider_network_type = module.params['provider_network_type']
    provider_segmentation_id = module.params['provider_segmentation_id']
    project = module.params.get('project')
    port_security_enabled = module.params.get('port_security_enabled')
    mtu = module.params.get('mtu')

    sdk, cloud = openstack_cloud_from_module(module)
    try:
        if project is not None:
            proj = cloud.get_project(project)
            if proj is None:
                module.fail_json(msg='Project %s could not be found' % project)
            project_id = proj['id']
            filters = {'tenant_id': project_id}
        else:
            project_id = None
            filters = None
        net = cloud.get_network(name, filters=filters)

        if state == 'present':
            if not net:
                provider = {}
                if provider_physical_network:
                    provider['physical_network'] = provider_physical_network
                if provider_network_type:
                    provider['network_type'] = provider_network_type
                if provider_segmentation_id:
                    provider['segmentation_id'] = provider_segmentation_id

                if project_id is not None:
                    net = cloud.create_network(
                        name,
                        shared,
                        admin_state_up,
                        external,
                        provider,
                        project_id,
                        port_security_enabled=port_security_enabled,
                        mtu_size=mtu)
                else:
                    net = cloud.create_network(
                        name,
                        shared,
                        admin_state_up,
                        external,
                        provider,
                        port_security_enabled=port_security_enabled,
                        mtu_size=mtu)
                changed = True
            else:
                changed = False
            module.exit_json(changed=changed, network=net, id=net['id'])

        elif state == 'absent':
            if not net:
                module.exit_json(changed=False)
            else:
                cloud.delete_network(name)
                module.exit_json(changed=True)

    except sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
def main():

    argument_spec = openstack_full_argument_spec(
        id=dict(required=True),
        ttl=dict(default=7, type='int', min=1),
        state=dict(default='present', choices=['expired', 'present']),
        _cache_dir=dict(required=True),
        _cache_file=dict(required=True),
        _chunk_size=dict(default=64 * 1024, type='int'),
        _prefetched_path=dict(default=None),
        scp_continue_on_error=dict(default=False, type='bool'))
    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec, **module_kwargs)

    image_id = module.params['id']
    cache_dir = module.params['_cache_dir']
    cache_file = module.params['_cache_file']
    chunk_size = module.params['_chunk_size']
    prefetched_path = module.params['_prefetched_path']
    scp_continue = module.params['scp_continue_on_error']

    ttl_days = module.params['ttl']

    result = dict(changed=False,
                  actions=[],
                  image=None,
                  cache_file='',
                  exists_in_cache=False,
                  mtime=0)

    sdk, cloud = openstack_cloud_from_module(module, min_version='0.11.3')

    try:
        result['exists_in_cache'] = exists_in_cache = os.path.exists(
            cache_file)
        if exists_in_cache:
            result['cache_file'] = cache_file

        image = cloud.image.find_image(name_or_id=image_id)
        exists_in_glance = image is not None
        if exists_in_glance:
            result['image'] = image.to_dict()

        if module.params['state'] == 'present':
            if not exists_in_cache:

                if not exists_in_glance:
                    module.fail_json(msg="Image not found in glance: %s" %
                                     image_id)

                md5 = hashlib.md5()
                if prefetched_path:
                    result['actions'].append(
                        {'name': 'Verify pre-fetched image checksum'})
                    with open(prefetched_path, 'rb') as prefetched_image_file:
                        while True:
                            chunk = prefetched_image_file.read(chunk_size)
                            if not chunk:
                                break
                            md5.update(chunk)
                    prefetched_checksum = md5.hexdigest()
                    if prefetched_checksum == image.checksum:
                        result['actions'].append({
                            'name':
                            'Verify pre-fetched image',
                            'result':
                            True,
                            'expected_md5':
                            image.checksum,
                            'actual_md5':
                            prefetched_checksum
                        })
                        # FIXME: chown to the container nova uid (42436)
                        # until we can run within the container
                        os.chown(prefetched_path, 42436, 42436)
                        os.rename(prefetched_path, cache_file)
                    else:
                        result['actions'].append({
                            'name':
                            'Verify pre-fetched image',
                            'result':
                            False,
                            'expected_md5':
                            image.checksum,
                            'actual_md5':
                            prefetched_checksum
                        })
                        if not scp_continue:
                            module.fail_json(
                                msg="Pre-fetched image checksum failed")
                        # Ignore it and download direct from glance.
                        # As we did not create it we should not remove it.
                        prefetched_path = ''

                if not prefetched_path:
                    with tempfile.NamedTemporaryFile(
                            'wb', dir=cache_dir,
                            delete=False) as temp_cache_file:
                        try:
                            md5 = hashlib.md5()
                            image_stream = cloud.image.download_image(
                                image, stream=True)
                            try:
                                for chunk in image_stream.iter_content(
                                        chunk_size=chunk_size):
                                    md5.update(chunk)
                                    temp_cache_file.write(chunk)
                            finally:
                                image_stream.close()
                                temp_cache_file.close()

                            download_checksum = md5.hexdigest()
                            if download_checksum != image.checksum:
                                result['actions'].append({
                                    'name':
                                    'Verify downloaded image',
                                    'result':
                                    False,
                                    'expected_md5':
                                    image.checksum,
                                    'actual_md5':
                                    download_checksum
                                })
                                module.fail_json(
                                    msg="Image data does not match checksum")
                            result['actions'].append({
                                'name':
                                'Verify downloaded image',
                                'result':
                                True,
                                'expected_md5':
                                image.checksum,
                                'actual_md5':
                                download_checksum
                            })

                            # FIXME: chown to the container nova uid (42436)
                            #        until we can run within the container
                            os.chown(temp_cache_file.name, 42436, 42436)
                            os.rename(temp_cache_file.name, cache_file)
                            result['changed'] = True
                        finally:
                            try:
                                os.unlink(temp_cache_file.name)
                            except Exception:
                                pass

            # Set the mtime in the future to prevent nova cleanup
            cache_file_stat = os.stat(cache_file)
            expiry_ts = ttl_to_ts(ttl_days)
            now = time.time()
            if cache_file_stat.st_mtime != expiry_ts:
                os.utime(cache_file, (now, expiry_ts))
                result['actions'].append({
                    'name': 'Update mtime',
                    'from': cache_file_stat.st_mtime,
                    'to': expiry_ts
                })
                result['changed'] = True

        else:  # expired
            if not exists_in_cache:
                result['changed'] = False
            else:
                # Set the mtime to epoch to enable nova cleanup
                now = time.time()
                ts = 0
                cache_file_stat = os.stat(cache_file)
                if cache_file_stat.st_mtime > ts:
                    os.utime(cache_file, (now, ts))
                    result['actions'].append({
                        'name': 'Update mtime',
                        'from': cache_file_stat.st_mtime,
                        'to': ts
                    })
                    result['changed'] = True

                cache_file_stat = os.stat(cache_file)
                result['mtime'] = cache_file_stat.st_mtime
                result['expires'] = time.strftime(
                    "%a, %d %b %Y %H:%M:%S %z",
                    time.localtime(cache_file_stat.st_mtime))

        module.exit_json(**result)

    except sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e), extra_data=e.extra_data)
Beispiel #48
0
def main():
    argument_spec = openstack_full_argument_spec(
        name=dict(required=True),
        password=dict(required=False, default=None, no_log=True),
        email=dict(required=False, default=None),
        default_project=dict(required=False, default=None),
        description=dict(type='str'),
        domain=dict(required=False, default=None),
        enabled=dict(default=True, type='bool'),
        state=dict(default='present', choices=['absent', 'present']),
        update_password=dict(default='always', choices=['always',
                                                        'on_create']),
    )

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec, **module_kwargs)

    if not HAS_SHADE:
        module.fail_json(msg='shade is required for this module')

    name = module.params['name']
    password = module.params.pop('password')
    email = module.params['email']
    default_project = module.params['default_project']
    domain = module.params['domain']
    enabled = module.params['enabled']
    state = module.params['state']
    update_password = module.params['update_password']
    description = module.params['description']

    if description and StrictVersion(
            shade.__version__) < StrictVersion('1.13.0'):
        module.fail_json(
            msg=
            "To utilize description, the installed version of the shade library MUST be >=1.13.0"
        )

    try:
        cloud = shade.openstack_cloud(**module.params)
        user = cloud.get_user(name)

        domain_id = None
        if domain:
            opcloud = shade.operator_cloud(**module.params)
            domain_id = _get_domain_id(opcloud, domain)

        if state == 'present':
            if update_password in ('always', 'on_create'):
                if not password:
                    msg = "update_password is %s but a password value is missing" % update_password
                    module.fail_json(msg=msg)
            default_project_id = None
            if default_project:
                default_project_id = _get_default_project_id(
                    cloud, default_project, module)

            if user is None:
                if description is not None:
                    user = cloud.create_user(
                        name=name,
                        password=password,
                        email=email,
                        default_project=default_project_id,
                        domain_id=domain_id,
                        enabled=enabled,
                        description=description)
                else:
                    user = cloud.create_user(
                        name=name,
                        password=password,
                        email=email,
                        default_project=default_project_id,
                        domain_id=domain_id,
                        enabled=enabled)
                changed = True
            else:
                params_dict = {
                    'email': email,
                    'enabled': enabled,
                    'password': password,
                    'update_password': update_password
                }
                if description is not None:
                    params_dict['description'] = description
                if domain_id is not None:
                    params_dict['domain_id'] = domain_id
                if default_project_id is not None:
                    params_dict['default_project_id'] = default_project_id

                if _needs_update(params_dict, user):
                    if update_password == 'always':
                        if description is not None:
                            user = cloud.update_user(
                                user['id'],
                                password=password,
                                email=email,
                                default_project=default_project_id,
                                domain_id=domain_id,
                                enabled=enabled,
                                description=description)
                        else:
                            user = cloud.update_user(
                                user['id'],
                                password=password,
                                email=email,
                                default_project=default_project_id,
                                domain_id=domain_id,
                                enabled=enabled)
                    else:
                        if description is not None:
                            user = cloud.update_user(
                                user['id'],
                                email=email,
                                default_project=default_project_id,
                                domain_id=domain_id,
                                enabled=enabled,
                                description=description)
                        else:
                            user = cloud.update_user(
                                user['id'],
                                email=email,
                                default_project=default_project_id,
                                domain_id=domain_id,
                                enabled=enabled)
                    changed = True
                else:
                    changed = False
            module.exit_json(changed=changed, user=user)

        elif state == 'absent':
            if user is None:
                changed = False
            else:
                cloud.delete_user(user['id'])
                changed = True
            module.exit_json(changed=changed)

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e), extra_data=e.extra_data)
Beispiel #49
0
def main():
    argument_spec = openstack_full_argument_spec(
        network=dict(required=False),
        name=dict(required=False),
        fixed_ips=dict(type='list', default=None),
        admin_state_up=dict(type='bool', default=None),
        mac_address=dict(default=None),
        security_groups=dict(default=None, type='list'),
        no_security_groups=dict(default=False, type='bool'),
        allowed_address_pairs=dict(type='list', default=None),
        extra_dhcp_opts=dict(type='list', default=None),
        device_owner=dict(default=None),
        device_id=dict(default=None),
        state=dict(default='present', choices=['absent', 'present']),
        vnic_type=dict(default=None,
                       choices=[
                           'normal', 'direct', 'direct-physical', 'macvtap',
                           'baremetal', 'virtio-forwarder'
                       ]),
        port_security_enabled=dict(default=None, type='bool'))

    module_kwargs = openstack_module_kwargs(mutually_exclusive=[
        ['no_security_groups', 'security_groups'],
    ])

    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

    name = module.params['name']
    state = module.params['state']

    sdk, cloud = openstack_cloud_from_module(module)
    try:
        if module.params['security_groups']:
            # translate security_groups to UUID's if names where provided
            module.params['security_groups'] = [
                get_security_group_id(module, cloud, v)
                for v in module.params['security_groups']
            ]

        # Neutron API accept 'binding:vnic_type' as an argument
        # for the port type.
        module.params['binding:vnic_type'] = module.params.pop('vnic_type')

        port = None
        network_id = None
        if name:
            port = cloud.get_port(name)

        if module.check_mode:
            module.exit_json(changed=_system_state_change(module, port, cloud))

        changed = False
        if state == 'present':
            if not port:
                network = module.params['network']
                if not network:
                    module.fail_json(
                        msg="Parameter 'network' is required in Port Create")
                port_kwargs = _compose_port_args(module, cloud)
                network_object = cloud.get_network(network)

                if network_object:
                    network_id = network_object['id']
                else:
                    module.fail_json(msg="Specified network was not found.")

                port = cloud.create_port(network_id, **port_kwargs)
                changed = True
            else:
                if _needs_update(module, port, cloud):
                    port_kwargs = _compose_port_args(module, cloud)
                    port = cloud.update_port(port['id'], **port_kwargs)
                    changed = True
            module.exit_json(changed=changed, id=port['id'], port=port)

        if state == 'absent':
            if port:
                cloud.delete_port(port['id'])
                changed = True
            module.exit_json(changed=changed)

    except sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Beispiel #50
0
def main():
    argument_spec = openstack_full_argument_spec(
        server=dict(required=True),
        state=dict(default='present', choices=['absent', 'present']),
        network=dict(required=False, default=None),
        floating_ip_address=dict(required=False, default=None),
        reuse=dict(required=False, type='bool', default=False),
        fixed_address=dict(required=False, default=None),
        nat_destination=dict(required=False,
                             default=None,
                             aliases=['fixed_network', 'internal_network']),
        wait=dict(required=False, type='bool', default=False),
        timeout=dict(required=False, type='int', default=60),
        purge=dict(required=False, type='bool', default=False),
    )

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec, **module_kwargs)

    if module.params['nat_destination']:
        min_version = '1.8.0'
    else:
        min_version = None

    server_name_or_id = module.params['server']
    state = module.params['state']
    network = module.params['network']
    floating_ip_address = module.params['floating_ip_address']
    reuse = module.params['reuse']
    fixed_address = module.params['fixed_address']
    nat_destination = module.params['nat_destination']
    wait = module.params['wait']
    timeout = module.params['timeout']
    purge = module.params['purge']

    shade, cloud = openstack_cloud_from_module(module, min_version=min_version)

    try:
        server = cloud.get_server(server_name_or_id)
        if server is None:
            module.fail_json(
                msg="server {0} not found".format(server_name_or_id))

        if state == 'present':
            # If f_ip already assigned to server, check that it matches
            # requirements.
            public_ip = cloud.get_server_public_ip(server)
            f_ip = _get_floating_ip(cloud,
                                    public_ip) if public_ip else public_ip
            if f_ip:
                if network:
                    network_id = cloud.get_network(name_or_id=network)["id"]
                else:
                    network_id = None
                # check if we have floting ip on given nat_destination network
                if nat_destination:
                    nat_floating_addrs = [
                        addr for addr in server.addresses.get(
                            cloud.get_network(nat_destination)['name'], [])
                        if addr.addr == public_ip
                        and addr['OS-EXT-IPS:type'] == 'floating'
                    ]

                    if len(nat_floating_addrs) == 0:
                        module.fail_json(
                            msg="server {server} already has a "
                            "floating-ip on a different "
                            "nat-destination than '{nat_destination}'".format(
                                server=server_name_or_id,
                                nat_destination=nat_destination))

                if all([
                        fixed_address, f_ip.fixed_ip_address == fixed_address,
                        network, f_ip.network != network_id
                ]):
                    # Current state definitely conflicts with requirements
                    module.fail_json(
                        msg="server {server} already has a "
                        "floating-ip on requested "
                        "interface but it doesn't match "
                        "requested network {network}: {fip}".format(
                            server=server_name_or_id,
                            network=network,
                            fip=remove_values(f_ip, module.no_log_values)))
                if not network or f_ip.network == network_id:
                    # Requirements are met
                    module.exit_json(changed=False, floating_ip=f_ip)

                # Requirements are vague enough to ignore existing f_ip and try
                # to create a new f_ip to the server.

            server = cloud.add_ips_to_server(server=server,
                                             ips=floating_ip_address,
                                             ip_pool=network,
                                             reuse=reuse,
                                             fixed_address=fixed_address,
                                             wait=wait,
                                             timeout=timeout,
                                             nat_destination=nat_destination)
            fip_address = cloud.get_server_public_ip(server)
            # Update the floating IP status
            f_ip = _get_floating_ip(cloud, fip_address)
            module.exit_json(changed=True, floating_ip=f_ip)

        elif state == 'absent':
            if floating_ip_address is None:
                if not server_name_or_id:
                    module.fail_json(
                        msg="either server or floating_ip_address are required"
                    )
                server = cloud.get_server(server_name_or_id)
                floating_ip_address = cloud.get_server_public_ip(server)

            f_ip = _get_floating_ip(cloud, floating_ip_address)

            if not f_ip:
                # Nothing to detach
                module.exit_json(changed=False)
            changed = False
            if f_ip["fixed_ip_address"]:
                cloud.detach_ip_from_server(server_id=server['id'],
                                            floating_ip_id=f_ip['id'])
                # Update the floating IP status
                f_ip = cloud.get_floating_ip(id=f_ip['id'])
                changed = True
            if purge:
                cloud.delete_floating_ip(f_ip['id'])
                module.exit_json(changed=True)
            module.exit_json(changed=changed, floating_ip=f_ip)

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e), extra_data=e.extra_data)
def main():
    argument_spec = openstack_full_argument_spec(state=dict(
        type='str', default='present', choices=['absent', 'present']),
                                                 name=dict(type='str',
                                                           required=True),
                                                 description=dict(type='str'),
                                                 spec=dict(type='str',
                                                           default="1"),
                                                 vpc_id=dict(type='str'),
                                                 subnet_id=dict(type='str'))

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           supports_check_mode=False,
                           **module_kwargs)

    state = module.params['state']
    name = module.params['name']

    cloud = connect_from_ansible(module)
    try:
        cloud.add_service(nat_service.NatService("nat"))
        natgw = cloud.nat.find_nat(name)

        # FIXME
        # if module.check_mode:
        #    module.exit_json(changed=_system_state_change(module, subnet,
        #                                              cloud))

        if state == 'present':
            if not natgw:
                natgw = cloud.nat.create_nat(
                    name=name,
                    description=module.params['description'],
                    spec=module.params['spec'],
                    vpc_id=module.params['vpc_id'],
                    subnet_id=module.params['subnet_id'],
                )
                changed = True
            elif (_can_update(module, cloud, natgw)
                  and _needs_update(module, cloud, natgw)):
                cloud.nat.update_nat(name=name,
                                     description=module.params['description'],
                                     spec=module.params['spec'])
                changed = True
            else:
                changed = False

            if changed and module.params['wait']:
                cloud.nat.wait_for_status(natgw)
            module.exit_json(changed=changed, nat=natgw.copy(), id=natgw.id)

        elif state == 'absent':
            if not natgw:
                changed = False
            else:
                changed = True
                cloud.nat.delete_nat(natgw)
                if module.params['wait']:
                    cloud.nat.wait_for_delete(natgw)
            module.exit_json(changed=changed)

    except exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Beispiel #52
0
def main():
    argument_spec = openstack_full_argument_spec(
        name=dict(required=True),
        description=dict(required=False, default=None),
        domain_id=dict(required=False, default=None, aliases=['domain']),
        enabled=dict(default=True, type='bool'),
        state=dict(default='present', choices=['absent', 'present']))

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

    if not HAS_SHADE:
        module.fail_json(msg='shade is required for this module')

    name = module.params['name']
    description = module.params['description']
    domain = module.params.pop('domain_id')
    enabled = module.params['enabled']
    state = module.params['state']

    if domain and StrictVersion(shade.__version__) < StrictVersion('1.8.0'):
        module.fail_json(msg="The domain argument requires shade >=1.8.0")

    try:
        if domain:
            opcloud = shade.operator_cloud(**module.params)
            try:
                # We assume admin is passing domain id
                dom = opcloud.get_domain(domain)['id']
                domain = dom
            except:
                # If we fail, maybe admin is passing a domain name.
                # Note that domains have unique names, just like id.
                try:
                    dom = opcloud.search_domains(
                        filters={'name': domain})[0]['id']
                    domain = dom
                except:
                    # Ok, let's hope the user is non-admin and passing a sane id
                    pass

        cloud = shade.openstack_cloud(**module.params)

        if domain:
            project = cloud.get_project(name, domain_id=domain)
        else:
            project = cloud.get_project(name)

        if module.check_mode:
            module.exit_json(changed=_system_state_change(module, project))

        if state == 'present':
            if project is None:
                project = cloud.create_project(name=name,
                                               description=description,
                                               domain_id=domain,
                                               enabled=enabled)
                changed = True
            else:
                if _needs_update(module, project):
                    project = cloud.update_project(project['id'],
                                                   description=description,
                                                   enabled=enabled)
                    changed = True
                else:
                    changed = False
            module.exit_json(changed=changed, project=project)

        elif state == 'absent':
            if project is None:
                changed = False
            else:
                cloud.delete_project(project['id'])
                changed = True
            module.exit_json(changed=changed)

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=e.message, extra_data=e.extra_data)
Beispiel #53
0
def main():
    argument_spec = openstack_full_argument_spec(
        server=dict(required=True),
        state=dict(default='present', choices=['absent', 'present']),
        network=dict(required=False, default=None),
        floating_ip_address=dict(required=False, default=None),
        reuse=dict(required=False, type='bool', default=False),
        fixed_address=dict(required=False, default=None),
        nat_destination=dict(required=False, default=None,
                             aliases=['fixed_network', 'internal_network']),
        wait=dict(required=False, type='bool', default=False),
        timeout=dict(required=False, type='int', default=60),
        purge=dict(required=False, type='bool', default=False),
    )

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec, **module_kwargs)

    if module.params['nat_destination']:
        min_version = '1.8.0'
    else:
        min_version = None

    server_name_or_id = module.params['server']
    state = module.params['state']
    network = module.params['network']
    floating_ip_address = module.params['floating_ip_address']
    reuse = module.params['reuse']
    fixed_address = module.params['fixed_address']
    nat_destination = module.params['nat_destination']
    wait = module.params['wait']
    timeout = module.params['timeout']
    purge = module.params['purge']

    shade, cloud = openstack_cloud_from_module(module, min_version=min_version)

    try:
        server = cloud.get_server(server_name_or_id)
        if server is None:
            module.fail_json(
                msg="server {0} not found".format(server_name_or_id))

        if state == 'present':
            # If f_ip already assigned to server, check that it matches
            # requirements.
            public_ip = cloud.get_server_public_ip(server)
            f_ip = _get_floating_ip(cloud, public_ip) if public_ip else public_ip
            if f_ip:
                if network:
                    network_id = cloud.get_network(name_or_id=network)["id"]
                else:
                    network_id = None
                # check if we have floting ip on given nat_destination network
                if nat_destination:
                    nat_floating_addrs = [addr for addr in server.addresses.get(
                        cloud.get_network(nat_destination)['name'], [])
                        if addr.addr == public_ip and
                        addr['OS-EXT-IPS:type'] == 'floating']

                    if len(nat_floating_addrs) == 0:
                        module.fail_json(msg="server {server} already has a "
                                             "floating-ip on a different "
                                             "nat-destination than '{nat_destination}'"
                                         .format(server=server_name_or_id,
                                                 nat_destination=nat_destination))

                if all([fixed_address, f_ip.fixed_ip_address == fixed_address,
                        network, f_ip.network != network_id]):
                    # Current state definitely conflicts with requirements
                    module.fail_json(msg="server {server} already has a "
                                         "floating-ip on requested "
                                         "interface but it doesn't match "
                                         "requested network {network}: {fip}"
                                     .format(server=server_name_or_id,
                                             network=network,
                                             fip=remove_values(f_ip,
                                                               module.no_log_values)))
                if not network or f_ip.network == network_id:
                    # Requirements are met
                    module.exit_json(changed=False, floating_ip=f_ip)

                # Requirements are vague enough to ignore existing f_ip and try
                # to create a new f_ip to the server.

            server = cloud.add_ips_to_server(
                server=server, ips=floating_ip_address, ip_pool=network,
                reuse=reuse, fixed_address=fixed_address, wait=wait,
                timeout=timeout, nat_destination=nat_destination)
            fip_address = cloud.get_server_public_ip(server)
            # Update the floating IP status
            f_ip = _get_floating_ip(cloud, fip_address)
            module.exit_json(changed=True, floating_ip=f_ip)

        elif state == 'absent':
            if floating_ip_address is None:
                if not server_name_or_id:
                    module.fail_json(msg="either server or floating_ip_address are required")
                server = cloud.get_server(server_name_or_id)
                floating_ip_address = cloud.get_server_public_ip(server)

            f_ip = _get_floating_ip(cloud, floating_ip_address)

            if not f_ip:
                # Nothing to detach
                module.exit_json(changed=False)
            changed = False
            if f_ip["fixed_ip_address"]:
                cloud.detach_ip_from_server(
                    server_id=server['id'], floating_ip_id=f_ip['id'])
                # Update the floating IP status
                f_ip = cloud.get_floating_ip(id=f_ip['id'])
                changed = True
            if purge:
                cloud.delete_floating_ip(f_ip['id'])
                module.exit_json(changed=True)
            module.exit_json(changed=changed, floating_ip=f_ip)

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e), extra_data=e.extra_data)
Beispiel #54
0
def main():

    argument_spec = openstack_full_argument_spec(
        name=dict(required=True),
        state=dict(default='present', choices=['absent', 'present']),
        backup_gigabytes=dict(required=False, type='int', default=None),
        backups=dict(required=False, type='int', default=None),
        cores=dict(required=False, type='int', default=None),
        fixed_ips=dict(required=False, type='int', default=None),
        floating_ips=dict(required=False,
                          type='int',
                          default=None,
                          aliases=['compute_floating_ips']),
        floatingip=dict(required=False,
                        type='int',
                        default=None,
                        aliases=['network_floating_ips']),
        gigabytes=dict(required=False, type='int', default=None),
        gigabytes_types=dict(required=False, type='dict', default={}),
        injected_file_size=dict(required=False, type='int', default=None),
        injected_files=dict(required=False, type='int', default=None),
        injected_path_size=dict(required=False, type='int', default=None),
        instances=dict(required=False, type='int', default=None),
        key_pairs=dict(required=False, type='int', default=None),
        loadbalancer=dict(required=False, type='int', default=None),
        network=dict(required=False, type='int', default=None),
        per_volume_gigabytes=dict(required=False, type='int', default=None),
        pool=dict(required=False, type='int', default=None),
        port=dict(required=False, type='int', default=None),
        project=dict(required=False, type='int', default=None),
        properties=dict(required=False, type='int', default=None),
        ram=dict(required=False, type='int', default=None),
        rbac_policy=dict(required=False, type='int', default=None),
        router=dict(required=False, type='int', default=None),
        security_group_rule=dict(required=False, type='int', default=None),
        security_group=dict(required=False, type='int', default=None),
        server_group_members=dict(required=False, type='int', default=None),
        server_groups=dict(required=False, type='int', default=None),
        snapshots=dict(required=False, type='int', default=None),
        snapshots_types=dict(required=False, type='dict', default={}),
        subnet=dict(required=False, type='int', default=None),
        subnetpool=dict(required=False, type='int', default=None),
        volumes=dict(required=False, type='int', default=None),
        volumes_types=dict(required=False, type='dict', default={}))

    module = AnsibleModule(argument_spec, supports_check_mode=True)

    if not HAS_SHADE:
        module.fail_json(msg='shade is required for this module')

    try:
        cloud_params = dict(module.params)
        cloud = shade.operator_cloud(**cloud_params)

        #In order to handle the different volume types we update module params after.
        dynamic_types = [
            'gigabytes_types',
            'snapshots_types',
            'volumes_types',
        ]

        for dynamic_type in dynamic_types:
            for k, v in module.params[dynamic_type].items():
                module.params[k] = int(v)

        #Get current quota values
        project_quota_output = _get_quotas(module, cloud, cloud_params['name'])
        changes_required = False

        if module.params['state'] == "absent":
            #If a quota state is set to absent we should assume there will be changes.
            #The default quota values are not accessible so we can not determine if
            #no changes will occur or not.
            if module.check_mode:
                module.exit_json(changed=True)

            #Calling delete_network_quotas when a quota has not been set results
            #in an error, according to the shade docs it should return the
            #current quota.
            #The following error string is returned:
            #network client call failed: Quota for tenant 69dd91d217e949f1a0b35a4b901741dc could not be found.
            neutron_msg1 = "network client call failed: Quota for tenant"
            neutron_msg2 = "could not be found"

            for quota_type in project_quota_output.keys():
                quota_call = getattr(cloud, 'delete_%s_quotas' % (quota_type))
                try:
                    quota_call(cloud_params['name'])
                except shade.OpenStackCloudException as e:
                    error_msg = str(e)
                    if error_msg.find(neutron_msg1) > -1 and error_msg.find(
                            neutron_msg2) > -1:
                        pass
                    else:
                        module.fail_json(msg=str(e), extra_data=e.extra_data)

            project_quota_output = _get_quotas(module, cloud,
                                               cloud_params['name'])
            changes_required = True

        elif module.params['state'] == "present":
            if module.check_mode:
                module.exit_json(
                    changed=_system_state_change(module, project_quota_output))

            changes_required, quota_change_request = _system_state_change_details(
                module, project_quota_output)

            if changes_required:
                for quota_type in quota_change_request.keys():
                    quota_call = getattr(cloud, 'set_%s_quotas' % (quota_type))
                    quota_call(cloud_params['name'],
                               **quota_change_request[quota_type])

                #Get quota state post changes for validation
                project_quota_update = _get_quotas(module, cloud,
                                                   cloud_params['name'])

                if project_quota_output == project_quota_update:
                    module.fail_json(msg='Could not apply quota update')

                project_quota_output = project_quota_update

        module.exit_json(changed=changes_required,
                         openstack_quotas=project_quota_output)

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e), extra_data=e.extra_data)
def main():
    argument_spec = openstack_full_argument_spec(
        security_group=dict(required=True),
        # NOTE(Shrews): None is an acceptable protocol value for
        # Neutron, but Nova will balk at this.
        protocol=dict(default=None,
                      choices=[None, 'tcp', 'udp', 'icmp', '112']),
        port_range_min=dict(required=False, type='int'),
        port_range_max=dict(required=False, type='int'),
        remote_ip_prefix=dict(required=False, default=None),
        remote_group=dict(required=False, default=None),
        ethertype=dict(default='IPv4',
                       choices=['IPv4', 'IPv6']),
        direction=dict(default='ingress',
                       choices=['egress', 'ingress']),
        state=dict(default='present',
                   choices=['absent', 'present']),
    )

    module_kwargs = openstack_module_kwargs(
        mutually_exclusive=[
            ['remote_ip_prefix', 'remote_group'],
        ]
    )

    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

    state = module.params['state']
    security_group = module.params['security_group']
    remote_group = module.params['remote_group']
    changed = False

    shade, cloud = openstack_cloud_from_module(module)
    try:
        secgroup = cloud.get_security_group(security_group)

        if remote_group:
            remotegroup = cloud.get_security_group(remote_group)
        else:
            remotegroup = {'id': None}

        if module.check_mode:
            module.exit_json(changed=_system_state_change(module, secgroup, remotegroup))

        if state == 'present':
            if not secgroup:
                module.fail_json(msg='Could not find security group %s' %
                                 security_group)

            rule = _find_matching_rule(module, secgroup, remotegroup)
            if not rule:
                rule = cloud.create_security_group_rule(
                    secgroup['id'],
                    port_range_min=module.params['port_range_min'],
                    port_range_max=module.params['port_range_max'],
                    protocol=module.params['protocol'],
                    remote_ip_prefix=module.params['remote_ip_prefix'],
                    remote_group_id=remotegroup['id'],
                    direction=module.params['direction'],
                    ethertype=module.params['ethertype']
                )
                changed = True
            module.exit_json(changed=changed, rule=rule, id=rule['id'])

        if state == 'absent' and secgroup:
            rule = _find_matching_rule(module, secgroup, remotegroup)
            if rule:
                cloud.delete_security_group_rule(rule['id'])
                changed = True

            module.exit_json(changed=changed)

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Beispiel #56
0
def main():
    argument_spec = openstack_full_argument_spec(
        server=dict(required=True),
        state=dict(default='present', choices=['absent', 'present']),
        network=dict(required=False, default=None),
        floating_ip_address=dict(required=False, default=None),
        reuse=dict(required=False, type='bool', default=False),
        fixed_address=dict(required=False, default=None),
        nat_destination=dict(required=False,
                             default=None,
                             aliases=['fixed_network', 'internal_network']),
        wait=dict(required=False, type='bool', default=False),
        timeout=dict(required=False, type='int', default=60),
        purge=dict(required=False, type='bool', default=False),
    )

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec, **module_kwargs)

    if not HAS_SHADE:
        module.fail_json(msg='shade is required for this module')

    if (module.params['nat_destination']
            and StrictVersion(shade.__version__) < StrictVersion('1.8.0')):
        module.fail_json(
            msg="To utilize nat_destination, the installed version of"
            "the shade library MUST be >= 1.8.0")

    server_name_or_id = module.params['server']
    state = module.params['state']
    network = module.params['network']
    floating_ip_address = module.params['floating_ip_address']
    reuse = module.params['reuse']
    fixed_address = module.params['fixed_address']
    nat_destination = module.params['nat_destination']
    wait = module.params['wait']
    timeout = module.params['timeout']
    purge = module.params['purge']

    cloud = shade.openstack_cloud(**module.params)

    try:
        server = cloud.get_server(server_name_or_id)
        if server is None:
            module.fail_json(
                msg="server {0} not found".format(server_name_or_id))

        if state == 'present':
            # If f_ip already assigned to server, check that it matches
            # requirements.
            public_ip = cloud.get_server_public_ip(server)
            f_ip = _get_floating_ip(cloud,
                                    public_ip) if public_ip else public_ip
            if f_ip:
                if network:
                    network_id = cloud.get_network(name_or_id=network)["id"]
                else:
                    network_id = None
                if all([
                    (fixed_address and f_ip.fixed_ip_address == fixed_address)
                        or (nat_destination
                            and f_ip.internal_network == fixed_address),
                        network, f_ip.network != network_id
                ]):
                    # Current state definitely conflicts with requirements
                    module.fail_json(
                        msg="server {server} already has a "
                        "floating-ip on requested "
                        "interface but it doesn't match "
                        "requested network {network}: {fip}".format(
                            server=server_name_or_id,
                            network=network,
                            fip=remove_values(f_ip, module.no_log_values)))
                if not network or f_ip.network == network_id:
                    # Requirements are met
                    module.exit_json(changed=False, floating_ip=f_ip)

                # Requirements are vague enough to ignore existing f_ip and try
                # to create a new f_ip to the server.

            server = cloud.add_ips_to_server(server=server,
                                             ips=floating_ip_address,
                                             ip_pool=network,
                                             reuse=reuse,
                                             fixed_address=fixed_address,
                                             wait=wait,
                                             timeout=timeout,
                                             nat_destination=nat_destination)
            fip_address = cloud.get_server_public_ip(server)
            # Update the floating IP status
            f_ip = _get_floating_ip(cloud, fip_address)
            module.exit_json(changed=True, floating_ip=f_ip)

        elif state == 'absent':
            if floating_ip_address is None:
                if not server_name_or_id:
                    module.fail_json(
                        msg="either server or floating_ip_address are required"
                    )
                server = cloud.get_server(server_name_or_id)
                floating_ip_address = cloud.get_server_public_ip(server)

            f_ip = _get_floating_ip(cloud, floating_ip_address)

            if not f_ip:
                # Nothing to detach
                module.exit_json(changed=False)
            changed = False
            if f_ip["fixed_ip_address"]:
                cloud.detach_ip_from_server(server_id=server['id'],
                                            floating_ip_id=f_ip['id'])
                # Update the floating IP status
                f_ip = cloud.get_floating_ip(id=f_ip['id'])
                changed = True
            if purge:
                cloud.delete_floating_ip(f_ip['id'])
                module.exit_json(changed=True)
            module.exit_json(changed=changed, floating_ip=f_ip)

    except shade.OpenStackCloudException as e:
        module.fail_json(msg=str(e), extra_data=e.extra_data)
Beispiel #57
0
def main():
    argument_spec = openstack_full_argument_spec(
        password=dict(required=True, type='str'),
        project=dict(required=True, type='str'),
        role=dict(required=True, type='str'),
        user=dict(required=True, type='str')
    )
    module = AnsibleModule(argument_spec)

    try:
        password = module.params.pop('password')
        project_name = module.params.pop('project')
        role_name = module.params.pop('role')
        user_name = module.params.pop('user')

        changed = False
        project = None
        role = None
        user = None

        cloud = shade.OperatorCloud(**module.params)

        for _project in cloud.search_projects():
            if _project.name == project_name:
                project = _project

        for _role in cloud.search_roles():
            if _role.name == role_name:
                role = _role

        for _user in cloud.search_users():
            if _user.name == user_name:
                user = _user

        if not project:
            changed = True
            project = cloud.create_project(project_name,
                                           domain_id='default')

        if not role:
            changed = True
            role = cloud.create_role(role_name)

        if not user:
            changed = True
            user = cloud.create_user(user_name,
                                     password=password,
                                     default_project=project,
                                     domain_id='default')
        role_assignments = cloud.keystone_client.role_assignments
        assignment = role_assignments.list(user=user,
                                           project=project,
                                           role=role)
        if not assignment:
            changed = True
            cloud.grant_role(role,
                             user=user,
                             project=project)

        module.exit_json(changed=changed)
    except Exception:
        module.exit_json(failed=True, changed=True,
                         msg=repr(traceback.format_exc()))
Beispiel #58
0
def main():
    argument_spec = openstack_full_argument_spec(
        description=dict(default=None),
        enabled=dict(default=True, type='bool'),
        name=dict(required=True),
        service_type=dict(required=True),
        state=dict(default='present', choices=['absent', 'present']),
    )

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

    description = module.params['description']
    enabled = module.params['enabled']
    name = module.params['name']
    state = module.params['state']
    service_type = module.params['service_type']

    sdk, cloud = openstack_cloud_from_module(module)
    try:
        services = cloud.search_services(name_or_id=name,
                                         filters=dict(type=service_type))

        if len(services) > 1:
            module.fail_json(msg='Service name %s and type %s are not unique' %
                             (name, service_type))
        elif len(services) == 1:
            service = services[0]
        else:
            service = None

        if module.check_mode:
            module.exit_json(changed=_system_state_change(module, service))

        if state == 'present':
            if service is None:
                service = cloud.create_service(name=name, description=description,
                                               type=service_type, enabled=True)
                changed = True
            else:
                if _needs_update(module, service):
                    service = cloud.update_service(
                        service.id, name=name, type=service_type, enabled=enabled,
                        description=description)
                    changed = True
                else:
                    changed = False
            module.exit_json(changed=changed, service=service, id=service.id)

        elif state == 'absent':
            if service is None:
                changed = False
            else:
                cloud.delete_service(service.id)
                changed = True
            module.exit_json(changed=changed)

    except sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Beispiel #59
0
def main():
    argument_spec = openstack_full_argument_spec(
        name=dict(required=True),
        password=dict(required=False, default=None, no_log=True),
        email=dict(required=False, default=None),
        default_project=dict(required=False, default=None),
        description=dict(type='str'),
        domain=dict(required=False, default=None),
        enabled=dict(default=True, type='bool'),
        state=dict(default='present', choices=['absent', 'present']),
        update_password=dict(default=None, choices=['always', 'on_create']),
    )

    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec, **module_kwargs)

    name = module.params['name']
    password = module.params.get('password')
    email = module.params['email']
    default_project = module.params['default_project']
    domain = module.params['domain']
    enabled = module.params['enabled']
    state = module.params['state']
    update_password = module.params['update_password']
    description = module.params['description']

    sdk, cloud = openstack_cloud_from_module(module)
    try:
        user = cloud.get_user(name)

        domain_id = None
        if domain:
            domain_id = _get_domain_id(cloud, domain)

        if state == 'present':
            if update_password in ('always', 'on_create'):
                if not password:
                    msg = "update_password is %s but a password value is missing" % update_password
                    module.fail_json(msg=msg)
            default_project_id = None
            if default_project:
                default_project_id = _get_default_project_id(
                    cloud, default_project, module)

            if user is None:
                if description is not None:
                    user = cloud.create_user(
                        name=name,
                        password=password,
                        email=email,
                        default_project=default_project_id,
                        domain_id=domain_id,
                        enabled=enabled,
                        description=description)
                else:
                    user = cloud.create_user(
                        name=name,
                        password=password,
                        email=email,
                        default_project=default_project_id,
                        domain_id=domain_id,
                        enabled=enabled)
                changed = True
            else:
                params_dict = {
                    'email': email,
                    'enabled': enabled,
                    'password': password,
                    'update_password': update_password
                }
                if description is not None:
                    params_dict['description'] = description
                if domain_id is not None:
                    params_dict['domain_id'] = domain_id
                if default_project_id is not None:
                    params_dict['default_project_id'] = default_project_id

                if _needs_update(params_dict, user):
                    if update_password == 'always':
                        if description is not None:
                            user = cloud.update_user(
                                user['id'],
                                password=password,
                                email=email,
                                default_project=default_project_id,
                                domain_id=domain_id,
                                enabled=enabled,
                                description=description)
                        else:
                            user = cloud.update_user(
                                user['id'],
                                password=password,
                                email=email,
                                default_project=default_project_id,
                                domain_id=domain_id,
                                enabled=enabled)
                    else:
                        if description is not None:
                            user = cloud.update_user(
                                user['id'],
                                email=email,
                                default_project=default_project_id,
                                domain_id=domain_id,
                                enabled=enabled,
                                description=description)
                        else:
                            user = cloud.update_user(
                                user['id'],
                                email=email,
                                default_project=default_project_id,
                                domain_id=domain_id,
                                enabled=enabled)
                    changed = True
                else:
                    changed = False
            module.exit_json(changed=changed, user=user)

        elif state == 'absent':
            if user is None:
                changed = False
            else:
                cloud.delete_user(user['id'])
                changed = True
            module.exit_json(changed=changed)

    except sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e), extra_data=e.extra_data)
Beispiel #60
0
def main():

    argument_spec = openstack_full_argument_spec(
        name=dict(required=True),
        image=dict(default=None),
        image_exclude=dict(default='(deprecated)'),
        flavor=dict(default=None),
        flavor_ram=dict(default=None, type='int'),
        flavor_include=dict(default=None),
        key_name=dict(default=None),
        security_groups=dict(default=['default'], type='list'),
        network=dict(default=None),
        nics=dict(default=[], type='list'),
        meta=dict(default=None, type='raw'),
        userdata=dict(default=None, aliases=['user_data']),
        config_drive=dict(default=False, type='bool'),
        auto_ip=dict(default=True,
                     type='bool',
                     aliases=['auto_floating_ip', 'public_ip']),
        floating_ips=dict(default=None, type='list'),
        floating_ip_pools=dict(default=None, type='list'),
        volume_size=dict(default=False, type='int'),
        boot_from_volume=dict(default=False, type='bool'),
        boot_volume=dict(default=None, aliases=['root_volume']),
        terminate_volume=dict(default=False, type='bool'),
        volumes=dict(default=[], type='list'),
        scheduler_hints=dict(default=None, type='dict'),
        state=dict(default='present', choices=['absent', 'present']),
        delete_fip=dict(default=False, type='bool'),
        reuse_ips=dict(default=True, type='bool'),
    )
    module_kwargs = openstack_module_kwargs(
        mutually_exclusive=[
            ['auto_ip', 'floating_ips'],
            ['auto_ip', 'floating_ip_pools'],
            ['floating_ips', 'floating_ip_pools'],
            ['flavor', 'flavor_ram'],
            ['image', 'boot_volume'],
            ['boot_from_volume', 'boot_volume'],
            ['nics', 'network'],
        ],
        required_if=[
            ('boot_from_volume', True, ['volume_size', 'image']),
        ],
    )
    module = AnsibleModule(argument_spec, **module_kwargs)

    state = module.params['state']
    image = module.params['image']
    boot_volume = module.params['boot_volume']
    flavor = module.params['flavor']
    flavor_ram = module.params['flavor_ram']

    if state == 'present':
        if not (image or boot_volume):
            module.fail_json(
                msg="Parameter 'image' or 'boot_volume' is required "
                "if state == 'present'")
        if not flavor and not flavor_ram:
            module.fail_json(
                msg="Parameter 'flavor' or 'flavor_ram' is required "
                "if state == 'present'")

    sdk, cloud = openstack_cloud_from_module(module)
    try:
        if state == 'present':
            _get_server_state(module, cloud)
            _create_server(module, cloud)
        elif state == 'absent':
            _get_server_state(module, cloud)
            _delete_server(module, cloud)
    except sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e), extra_data=e.extra_data)