def run_module():
    result = dict(
        success=False,
        changed=False,
        error="",
    )

    argument_spec = openstack_full_argument_spec(
        **yaml.safe_load(DOCUMENTATION)['options']
    )

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

    try:
        _, conn = openstack_cloud_from_module(module)

        tripleo = tc.TripleOCommon(session=conn.session)
        heat_client = tripleo.get_orchestration_client()

        result['stacks'] = list(get_overclouds(heat_client))
        result['success'] = True
        result['changed'] = False
    except Exception as err:
        result['error'] = str(err)
        result['msg'] = ("Error getting overclouds: %s" % err)
        module.fail_json(**result)

    # in the event of a successful module execution, you will want to
    # simple AnsibleModule.exit_json(), passing the key/value results
    module.exit_json(**result)
Esempio n. 2
0
def main():

    argument_spec = openstack_full_argument_spec(
        image=dict(required=False),
        properties=dict(default=None, type='dict'),
    )
    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec, **module_kwargs)
    is_old_facts = module._name == 'openstack.cloud.image_facts'
    if is_old_facts:
        module.deprecate(
            "The 'openstack.cloud.image_facts' module has been renamed to 'openstack.cloud.image_info', "
            "and the renamed one no longer returns ansible_facts",
            version='2.13')

    sdk, cloud = openstack_cloud_from_module(module)
    try:
        if module.params['image']:
            image = cloud.get_image(module.params['image'])
            if is_old_facts:
                module.exit_json(changed=False,
                                 ansible_facts=dict(openstack_image=image))
            else:
                module.exit_json(changed=False, openstack_image=image)
        else:
            images = cloud.search_images(filters=module.params['properties'])
            if is_old_facts:
                module.exit_json(changed=False,
                                 ansible_facts=dict(openstack_image=images))
            else:
                module.exit_json(changed=False, openstack_image=images)

    except sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
def run_module():
    result = dict(success=False, changed=False, error="", vip_data=list())

    argument_spec = openstack_full_argument_spec(
        **yaml.safe_load(DOCUMENTATION)['options'])

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

    stack = module.params['stack_name']

    try:
        _, conn = openstack_cloud_from_module(module)
        net_resources = n_utils.get_overcloud_network_resources(conn, stack)
        find_net_vips(conn, net_resources, result['vip_data'])
        find_ctlplane_vip(conn, result['vip_data'])

        result['changed'] = True if result['vip_data'] else False
        result['success'] = True if result['vip_data'] else False
        module.exit_json(**result)
    except Exception as err:
        result['error'] = str(err)
        result['msg'] = ("Error getting Virtual IPs data from overcloud stack "
                         "{stack_name}: %{error}".format(stack_name=stack,
                                                         error=err))
        module.fail_json(**result)
Esempio n. 4
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', elements='str'),
        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)

    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)

    sdk, cloud = openstack_cloud_from_module(module)
    try:
        stack = cloud.get_stack(name)

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

        if state == 'present':
            parameters = module.params['parameters']
            if module.params['tag']:
                parameters['tags'] = module.params['tag']
                min_version = '0.28.0'
                if StrictVersion(sdk.version.__version__) < StrictVersion(min_version) and stack:
                    module.warn("To update tags using openstack.cloud.stack module, the"
                                "installed version of the openstacksdk"
                                "library MUST be >={min_version}"
                                "".format(min_version=min_version))
            if not stack:
                stack = _create_stack(module, stack, cloud, sdk, parameters)
            else:
                stack = _update_stack(module, stack, cloud, sdk, parameters)
            module.exit_json(changed=True,
                             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 sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=to_native(e))
def run_module():
    result = dict(success=False, changed=False, error="", env=dict())

    argument_spec = openstack_full_argument_spec(
        **yaml.safe_load(DOCUMENTATION)['options'])

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

    stack = module.params['stack_name']
    vip_data = module.params['vip_data']
    templates = module.params['templates']

    try:
        _, conn = openstack_cloud_from_module(module)
        net_maps = n_utils.create_name_id_maps(conn)
        populate_net_vip_env(conn, stack, net_maps, vip_data, result['env'],
                             templates)

        result['changed'] = True if result['env'] else False
        result['success'] = True if result['env'] else False
        module.exit_json(**result)
    except Exception as err:
        result['error'] = err
        result['msg'] = ("Error getting Virtual IPs data from overcloud stack "
                         "{stack_name}: %{error}".format(stack_name=stack,
                                                         error=err))
        module.fail_json(**result)
Esempio n. 6
0
def main():
    argument_spec = ironic_argument_spec(
        uuid=dict(required=False),
        name=dict(required=False),
        mac=dict(required=False),
        timeout=dict(default=1200, type='int', required=False),
    )
    module_kwargs = openstack_module_kwargs()
    module = IronicModule(argument_spec, **module_kwargs)

    sdk, cloud = openstack_cloud_from_module(module)
    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 sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
def main():
    result = dict(
        success=False,
        changed=False,
        error=None,
        environment={}
    )
    module = AnsibleModule(
        openstack_full_argument_spec(
            **yaml.safe_load(DOCUMENTATION)['options']
        ),
        **openstack_module_kwargs()
    )
    container = module.params.get('container')
    env_files = module.params.get('env_files')
    try:
        if container:
            _, conn = openstack_cloud_from_module(module)
            tripleo = tc.TripleOCommon(session=conn.session)
            heat = tripleo.get_orchestration_client()
            env = heat.environment(container)
        else:
            _, env = template_utils.process_multiple_environments_and_files(
                env_paths=env_files)
        result['environment'] = env
        result['changed'] = True
        result['success'] = True
    except Exception as ex:
        result['error'] = str(ex)
        result['msg'] = 'Error buiding environment: {}'.format(
            ex)
        module.fail_json(**result)

    module.exit_json(**result)
Esempio n. 8
0
def run_module():
    result = dict(
        success=False,
        changed=False,
        error="",
    )

    argument_spec = openstack_full_argument_spec(
        **yaml.safe_load(DOCUMENTATION)['options']
    )

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

    net_data = module.params['net_data']
    error_messages = network_data_v2.validate_json_schema(net_data)
    if error_messages:
        module.fail_json(msg='\n\n'.join(error_messages))

    try:
        _, conn = openstack_cloud_from_module(module)
        changed = unprovision_subnet_and_network(conn, net_data)
        result['changed'] = changed if changed else result['changed']
        result['success'] = True
        module.exit_json(**result)

    except Exception as err:
        result['error'] = str(err)
        result['msg'] = ("Error overcloud network unprovisioning failed!")
        module.fail_json(**result)
Esempio n. 9
0
def run_module():
    result = dict(
        success=False,
        changed=False,
        error="",
        environment={},
    )

    argument_spec = openstack_full_argument_spec(
        **yaml.safe_load(DOCUMENTATION)['options'])

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

    environment = result['environment'] = module.params['environment']
    instances = module.params['instances']
    node_port_map = module.params['node_port_map']
    ctlplane_network = module.params['ctlplane_network']

    try:
        update_environment(environment, ctlplane_network, node_port_map,
                           instances)
        result['success'] = True
        module.exit_json(**result)

    except Exception as err:
        result['error'] = str(err)
        result['msg'] = ("Error overcloud network provision failed!")
        module.fail_json(**result)
def main():
    argument_spec = openstack_full_argument_spec(
        size=dict(default=None, type='int'),
        volume_type=dict(default=None),
        display_name=dict(required=True, aliases=['name']),
        display_description=dict(default=None, aliases=['description']),
        image=dict(default=None),
        snapshot_id=dict(default=None),
        volume=dict(default=None),
        state=dict(default='present', choices=['absent', 'present']),
        scheduler_hints=dict(default=None, type='dict'),
        metadata=dict(default=None, type='dict'),
        bootable=dict(type='bool', default=False))
    module_kwargs = openstack_module_kwargs(mutually_exclusive=[
        ['image', 'snapshot_id', 'volume'],
    ], )
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

    state = module.params['state']

    if state == 'present' and not module.params['size']:
        module.fail_json(msg="Size is required when state is 'present'")

    sdk, cloud = openstack_cloud_from_module(module)
    try:
        if state == 'present':
            _present_volume(module, cloud)
        if state == 'absent':
            _absent_volume(module, cloud, sdk)
    except sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
def main():
    """ Module entry point """

    argument_spec = openstack_full_argument_spec(name=dict(aliases=['id']), )
    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

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

    sdk, cloud = openstack_cloud_from_module(module, min_version="0.44")

    if name:
        try:
            mapping = normalize_mapping(cloud.identity.get_mapping(name))
        except sdk.exceptions.ResourceNotFound:
            module.fail_json(msg='Failed to find mapping')
        except sdk.exceptions.OpenStackCloudException as ex:
            module.fail_json(msg='Failed to get mapping: {0}'.format(str(ex)))
        module.exit_json(changed=False, mappings=[mapping])

    else:
        try:
            mappings = list(map(normalize_mapping, cloud.identity.mappings()))
        except sdk.exceptions.OpenStackCloudException as ex:
            module.fail_json(
                msg='Failed to list mappings: {0}'.format(str(ex)))
        module.exit_json(changed=False, mappings=mappings)
Esempio n. 12
0
def main():
    argument_spec = openstack_full_argument_spec(
        port=dict(required=False),
        filters=dict(type='dict', required=False),
    )
    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec, **module_kwargs)
    is_old_facts = module._name == 'os_port_facts'
    if is_old_facts:
        module.deprecate(
            "The 'os_port_facts' module has been renamed to 'os_port_info', "
            "and the renamed one no longer returns ansible_facts",
            version='2.13')

    port = module.params.get('port')
    filters = module.params.get('filters')

    sdk, cloud = openstack_cloud_from_module(module)
    try:
        ports = cloud.search_ports(port, filters)
        if is_old_facts:
            module.exit_json(changed=False,
                             ansible_facts=dict(openstack_ports=ports))
        else:
            module.exit_json(changed=False, openstack_ports=ports)

    except sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Esempio n. 13
0
def run_module():
    result = dict(success=False, error="", fernet_keys={})

    argument_spec = openstack_full_argument_spec(
        **yaml.safe_load(DOCUMENTATION)['options'])

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

    try:
        container = module.params.get('container')
        _, conn = openstack_cloud_from_module(module)
        tripleo = tc.TripleOCommon(session=conn.session)

        heat = tripleo.get_orchestration_client()
        # if the user is working with this module in only check mode we do not
        # want to make any changes to the environment, just return the current
        # state with no modifications
        if module.check_mode:
            module.exit_json(**result)
        fernet_keys = plan_utils.rotate_fernet_keys(heat, container)
        result['success'] = True
        result['fernet_keys'] = fernet_keys
    except Exception as err:
        result['error'] = str(err)
        result['msg'] = ("Error rotating fernet keys for plan %s: %s" %
                         (container, err))
        module.fail_json(**result)

    # in the event of a successful module execution, you will want to
    # simple AnsibleModule.exit_json(), passing the key/value results
    module.exit_json(**result)
Esempio n. 14
0
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']

    sdk, 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 sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Esempio n. 15
0
def run_module():
    module_args = dict(
        project=dict(type='str', required=True),
        ceph_cluster=dict(type='str', required=True),
        items=dict(default=[], type=list),
    )

    argument_spec = openstack_full_argument_spec(image=dict(required=False), )
    module_args.update(argument_spec)
    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(module_args, **module_kwargs)

    # if the user is working with this module in only check mode we do not
    # want to make any changes to the environment, just return the current
    # state with no modifications
    if module.check_mode:
        module.exit_json(msg="Operation skipped - running in check mode",
                         changed=True)

    mode = module.params.get("mode")
    objects = osp_copy_volume_to_image(module)

    result = dict(changed=True, failed=False, objects=objects)

    module.exit_json(**result)
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)

    sdk, cloud = openstack_cloud_from_module(module)

    state = module.params['state']

    try:
        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 (sdk.exceptions.OpenStackCloudException,
            sdk.exceptions.ResourceTimeout) as e:
        module.fail_json(msg=e.message)
Esempio n. 17
0
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)
    is_old_facts = module._name == 'openstack.cloud.compute_flavor_facts'
    if is_old_facts:
        module.deprecate("The 'openstack.cloud.compute_flavor_facts' module has been renamed to 'openstack.cloud.compute_flavor_info', "
                         "and the renamed one no longer returns ansible_facts", version='2.0.0',
                         collection_name='openstack.cloud')

    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

    sdk, cloud = openstack_cloud_from_module(module)
    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]

        if is_old_facts:
            module.exit_json(changed=False,
                             ansible_facts=dict(openstack_flavors=flavors))
        else:
            module.exit_json(changed=False,
                             openstack_flavors=flavors)

    except sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Esempio n. 18
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',
                                               'replace']),
    )

    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']:
        with open(module.params['public_key_file']) as public_key_fh:
            public_key = public_key_fh.read().rstrip()

    sdk, 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 in ('present', 'replace'):
            if keypair and keypair['name'] == name:
                if public_key and (public_key != keypair['public_key']):
                    if state == 'present':
                        module.fail_json(
                            msg="Key name %s present but key hash not the same"
                            " as offered. Delete key first." % name)
                    else:
                        cloud.delete_keypair(name)
                        keypair = cloud.create_keypair(name, public_key)
                        changed = True
                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 sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
def run_module():
    result = dict(
        success=False,
        changed=False,
        error="",
        passwords={}
    )

    argument_spec = openstack_full_argument_spec(
        **yaml.safe_load(DOCUMENTATION)['options']
    )

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

    try:
        container = module.params.get('container')
        rotate_passwords = module.params.get('rotate_passwords')
        password_list = module.params.get('password_list')
        password_file = module.params.get('password_file')
        _, conn = openstack_cloud_from_module(module)
        tripleo = tc.TripleOCommon(session=conn.session)
        swift = tripleo.get_object_client()
        heat = tripleo.get_orchestration_client()

        # Which file to look for passwords
        if not password_file:
            password_file = os.path.join(
                constants.DEFAULT_WORKING_DIR_FORMAT.format(container),
                constants.PASSWORDS_ENV_FORMAT.format(container))
        # Check whether the password file exists
        if os.path.exists(password_file):
            with open(password_file, 'r') as f:
                passwords_env = yaml.safe_load(f.read())
        else:
            passwords_env = None

        rotated_passwords = plan_utils.generate_passwords(
            swift, heat, container=container,
            rotate_passwords=rotate_passwords,
            rotate_pw_list=password_list,
            passwords_env=passwords_env
        )
        result['success'] = True
        result['passwords'] = rotated_passwords
        result['changed'] = True
    except Exception as err:
        result['error'] = str(err)
        result['msg'] = ("Error rotating passwords for plan %s: %s" % (
            container, err))
        module.fail_json(**result)

    # in the event of a successful module execution, you will want to
    # simple AnsibleModule.exit_json(), passing the key/value results
    module.exit_json(**result)
Esempio n. 20
0
def main():
    argument_spec = openstack_full_argument_spec(
        name=dict(required=True),
        state=dict(default='present', choices=['absent', 'present']),
        pool=dict(required=True),
        address=dict(default=None),
        protocol_port=dict(default=80, type='int'),
        subnet_id=dict(default=None),
    )
    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec, **module_kwargs)
    sdk, cloud = openstack_cloud_from_module(module)
    name = module.params['name']
    pool = module.params['pool']

    try:
        changed = False

        pool_ret = cloud.load_balancer.find_pool(name_or_id=pool)
        if not pool_ret:
            module.fail_json(msg='pool %s is not found' % pool)

        pool_id = pool_ret.id
        member = cloud.load_balancer.find_member(name, pool_id)

        if module.params['state'] == 'present':
            if not member:
                member = cloud.load_balancer.create_member(
                    pool_ret,
                    address=module.params['address'],
                    name=name,
                    protocol_port=module.params['protocol_port'],
                    subnet_id=module.params['subnet_id'])
                changed = True

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

            if module.params['wait']:
                member = _wait_for_member_status(module, cloud, pool_id,
                                                 member.id, "ACTIVE",
                                                 ["ERROR"])

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

        elif module.params['state'] == 'absent':
            if member:
                cloud.load_balancer.delete_member(member, pool_ret)
                changed = True

            module.exit_json(changed=changed)
    except sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e), extra_data=e.extra_data)
Esempio n. 21
0
def run_module():
    result = dict(
        success=False,
        changed=False,
        error="",
        environment={},
    )

    argument_spec = openstack_full_argument_spec(
        **yaml.safe_load(DOCUMENTATION)['options'])

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

    networks_data = module.params['net_data']
    templates = module.params['templates']

    try:
        _, conn = openstack_cloud_from_module(module)
        net_ip_version_map = dict()
        net_cidr_map = dict()
        net_attr_map = dict()
        for net_data in networks_data:
            name_lower = net_data.get('name_lower', net_data['name'].lower())
            net_attr_map[name_lower] = dict()

            set_composable_network_attrs(module,
                                         conn,
                                         name_lower,
                                         net_data,
                                         attrs=net_attr_map[name_lower],
                                         cidr_map=net_cidr_map,
                                         ip_version_map=net_ip_version_map)

        result['environment'] = {
            'resource_registry': {
                'OS::TripleO::Network':
                os.path.join(templates, 'network/deployed_networks.yaml'),
            },
            'parameter_defaults': {
                'DeployedNetworkEnvironment': {
                    'net_ip_version_map': net_ip_version_map,
                    'net_cidr_map': net_cidr_map,
                    'net_attributes_map': net_attr_map,
                }
            }
        }
        result['success'] = True

        module.exit_json(**result)

    except Exception as err:
        result['error'] = str(err)
        result['msg'] = "Error overcloud network provision failed!"
        module.fail_json(**result)
Esempio n. 22
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')

    sdk, 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 sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
def main():
    argument_spec = openstack_full_argument_spec(
        **yaml.safe_load(DOCUMENTATION)['options'])
    module_kwargs = openstack_module_kwargs()
    module = AnsibleModule(argument_spec,
                           supports_check_mode=False,
                           **module_kwargs)
    log_stream = _configure_logging(module.params['log_level'])
    sdk, cloud = openstack_cloud_from_module(module)
    quiet = module.params['quiet']
    failed_nodes = []
    passed_nodes = []
    try:
        result = introspect(cloud,
                            node_uuids=module.params["node_uuids"],
                            node_timeout=module.params["node_timeout"],
                            retry_timeout=module.params["retry_timeout"],
                            max_retries=module.params["max_retries"],
                            concurrency=module.params["concurrency"],
                            fetch_data=not quiet)
    except Exception as e:
        # This should not happen, but handle it anyway
        LOG.error('Unexpected error: %s', e)
        module.fail_json(msg=str(e),
                         failed_nodes=module.params["node_uuids"],
                         passed_nodes=[],
                         logging=log_stream.getvalue().split('\n'))

    for node_uuid, result in result.items():
        if result['failed']:
            failed_nodes.append(node_uuid)
        else:
            passed_nodes.append(node_uuid)

    failed = len(failed_nodes)

    if failed > 0:
        message = (
            "Introspection completed with failures. %s node(s) failed." %
            failed)
        module.log("os_tripleo_baremetal_node_introspection ERROR %s" %
                   message)
    else:
        message = "Introspection completed successfully: %s nodes" % len(
            passed_nodes)
        module.log("os_tripleo_baremetal_node_introspection INFO %s" % message)

    module.exit_json(changed=True,
                     failed=failed > 0,
                     introspection_data=result if not quiet else {},
                     failed_nodes=failed_nodes,
                     passed_nodes=passed_nodes,
                     msg=message,
                     logging=log_stream.getvalue().split('\n'))
def run_module():
    result = dict(
        success=False,
        changed=False,
        error="",
    )

    argument_spec = openstack_full_argument_spec(
        **yaml.safe_load(DOCUMENTATION)['options'])

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

    concurrency = module.params['concurrency']
    stack = module.params.get('stack_name')
    vip_data = module.params.get('vip_data')

    try:
        _, conn = openstack_cloud_from_module(module)
        net_maps = n_utils.create_name_id_maps(conn)
        validate_vip_nets_in_net_map(vip_data, net_maps)

        # no limit on concurrency, create a worker for every vip
        if concurrency < 1:
            concurrency = len(vip_data) if len(vip_data) > 0 else 1

        exceptions = list()
        provision_jobs = list()
        managed_ports = list()
        with futures.ThreadPoolExecutor(max_workers=concurrency) as p:
            for vip_spec in vip_data:
                provision_jobs.append(
                    p.submit(provision_vip_port, conn, stack, net_maps,
                             vip_spec, managed_ports))

        for job in futures.as_completed(provision_jobs):
            e = job.exception()
            if e:
                exceptions.append(e)

        if exceptions:
            raise exceptions[0]

        remove_obsolete_ports(conn, stack, managed_ports)

        result['success'] = True
        module.exit_json(**result)
    except Exception as err:
        result['error'] = str(err)
        result['msg'] = ("Error provisioning Virtual IPs for overcloud stack "
                         "{stack_name}: {error}".format(stack_name=stack,
                                                        error=err))
        module.fail_json(**result)
Esempio n. 25
0
def run_module():
    result = dict(success=False, error="", nodes=[])

    argument_spec = openstack_full_argument_spec(
        **yaml.safe_load(DOCUMENTATION)['options'])

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

    _, conn = openstack_cloud_from_module(module)
    tripleo = tc.TripleOCommon(session=conn.session)

    # if the user is working with this module in only check mode we do not
    # want to make any changes to the environment, just return the current
    # state with no modifications
    if module.check_mode:
        module.exit_json(**result)

    nodes_json = module.params['nodes_json']

    for node in nodes_json:
        caps = node.get('capabilities', {})
        caps = nodes.capabilities_to_dict(caps)
        if module.params['instance_boot_option'] is not None:
            caps.setdefault('boot_option',
                            module.params['instance_boot_option'])
        node['capabilities'] = nodes.dict_to_capabilities(caps)

    baremetal_client = tripleo.get_baremetal_client()
    image_client = tripleo.get_image_client()

    try:
        registered_nodes = nodes.register_all_nodes(
            nodes_json,
            client=baremetal_client,
            remove=module.params['remove'],
            glance_client=image_client,
            kernel_name=module.params['kernel_name'],
            ramdisk_name=module.params['ramdisk_name'])
        result['success'] = True
        result['nodes'] = [
            dict(uuid=node.uuid, provision_state=node.provision_state)
            for node in registered_nodes
        ]
    except Exception as exc:
        # LOG.exception("Error registering nodes with ironic.")
        result['error'] = str(exc)
        module.fail_json(msg='Validation Failed', **result)

    # in the event of a successful module execution, you will want to
    # simple AnsibleModule.exit_json(), passing the key/value results
    module.exit_json(**result)
def main():
    """ Module entry point """

    argument_spec = openstack_full_argument_spec(
        name=dict(required=True, aliases=['id']),
        state=dict(default='present', choices=['absent', 'present']),
        rules=dict(type='list',
                   elements='dict',
                   options=dict(local=dict(required=True,
                                           type='list',
                                           elements='dict'),
                                remote=dict(required=True,
                                            type='list',
                                            elements='dict'))),
    )
    module_kwargs = openstack_module_kwargs(required_if=[('state', 'present',
                                                          ['rules'])])
    module = AnsibleModule(argument_spec,
                           supports_check_mode=True,
                           **module_kwargs)

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

    sdk, cloud = openstack_cloud_from_module(module, min_version="0.44")

    try:
        mapping = cloud.identity.get_mapping(name)
    except sdk.exceptions.ResourceNotFound:
        mapping = None
    except sdk.exceptions.OpenStackCloudException as ex:
        module.fail_json(msg='Failed to fetch mapping: {0}'.format(str(ex)))

    if state == 'absent':
        if mapping is not None:
            changed = delete_mapping(module, sdk, cloud, mapping)
        module.exit_json(changed=changed)

    # state == 'present'
    else:
        if len(module.params.get('rules')) < 1:
            module.fail_json(msg='At least one rule must be passed')

        if mapping is None:
            (changed, mapping) = create_mapping(module, sdk, cloud, name)
            mapping = normalize_mapping(mapping)
            module.exit_json(changed=changed, mapping=mapping)
        else:
            (changed, new_mapping) = update_mapping(module, sdk, cloud,
                                                    mapping)
            new_mapping = normalize_mapping(new_mapping)
            module.exit_json(mapping=new_mapping, changed=changed)
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', 'none']
            and module.params['ironic_url'] is None
            and not module.params['cloud']
            and not (module.params['auth']
                     and module.params['auth'].get('endpoint'))):
        module.fail_json(msg="Authentication appears to be disabled, "
                         "Please define either ironic_url, or cloud, "
                         "or auth.endpoint")

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

    sdk, cloud = openstack_cloud_from_module(module)
    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 sdk.exceptions.OpenStackCloudException as e:
        module.fail_json(msg=str(e))
Esempio n. 28
0
def main():

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

    sdk, 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())
Esempio n. 29
0
def main():
    """ Module entry point """

    argument_spec = openstack_full_argument_spec(
        name=dict(required=True, aliases=['id']),
        state=dict(default='present', choices=['absent', 'present']),
        idp_id=dict(required=True, aliases=['idp_name']),
        mapping_id=dict(aliases=['mapping_name']),
    )
    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')
    idp = module.params.get('idp_id')
    changed = False

    sdk, cloud = openstack_cloud_from_module(module, min_version="0.44")

    try:
        protocol = cloud.identity.get_federation_protocol(idp, name)
    except sdk.exceptions.ResourceNotFound:
        protocol = None
    except sdk.exceptions.OpenStackCloudException as ex:
        module.fail_json(msg='Failed to get protocol: {0}'.format(str(ex)))

    if state == 'absent':
        if protocol is not None:
            changed = delete_protocol(module, sdk, cloud, protocol)
        module.exit_json(changed=changed)

    # state == 'present'
    else:
        if protocol is None:
            if module.params.get('mapping_id') is None:
                module.fail_json(
                    msg='A mapping_id must be passed when creating'
                    ' a protocol')
            (changed, protocol) = create_protocol(module, sdk, cloud, name)
            protocol = normalize_protocol(protocol)
            module.exit_json(changed=changed, protocol=protocol)

        else:
            (changed, new_protocol) = update_protocol(module, sdk, cloud,
                                                      protocol)
            new_protocol = normalize_protocol(new_protocol)
            module.exit_json(changed=changed, protocol=new_protocol)
def main():
    """ Module entry point """

    argument_spec = openstack_full_argument_spec(
        name=dict(required=True, aliases=['id']),
        state=dict(default='present', choices=['absent', 'present']),
        description=dict(),
        domain_id=dict(),
        enabled=dict(type='bool', aliases=['is_enabled']),
        remote_ids=dict(type='list', elements='str'),
    )
    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')
    changed = False

    sdk, cloud = openstack_cloud_from_module(module, min_version="0.44")

    try:
        idp = cloud.identity.get_identity_provider(name)
    except sdk.exceptions.ResourceNotFound:
        idp = None
    except sdk.exceptions.OpenStackCloudException as ex:
        module.fail_json(
            msg='Failed to get identity provider: {0}'.format(str(ex)))

    if state == 'absent':
        if idp is not None:
            changed = delete_identity_provider(module, sdk, cloud, idp)
        module.exit_json(changed=changed)

    # state == 'present'
    else:
        if idp is None:
            if module.params.get('domain_id') is None:
                module.fail_json(msg='A domain_id must be passed when creating'
                                 ' an identity provider')
            (changed, idp) = create_identity_provider(module, sdk, cloud, name)
            idp = normalize_idp(idp)
            module.exit_json(changed=changed, identity_provider=idp)

        (changed, new_idp) = update_identity_provider(module, sdk, cloud, idp)
        new_idp = normalize_idp(new_idp)
        module.exit_json(changed=changed, identity_provider=new_idp)