示例#1
0
def main():
    argument_spec = dict(
        vrf=dict(required=True),
        interface=dict(type='str', required=True),
        state=dict(default='present',
                   choices=['present', 'absent'],
                   required=False),
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()
    results = {'changed': False, 'commands': [], 'warnings': warnings}

    vrf = module.params['vrf']
    interface = module.params['interface'].lower()
    state = module.params['state']

    device_info = get_capabilities(module)
    network_api = device_info.get('network_api', 'nxapi')

    current_vrfs = get_vrf_list(module)
    if vrf not in current_vrfs:
        warnings.append("The VRF is not present/active on the device. "
                        "Use nxos_vrf to fix this.")

    intf_type = get_interface_type(interface)
    if (intf_type != 'ethernet' and network_api == 'cliconf'):
        if is_default(interface, module) == 'DNE':
            module.fail_json(msg="interface does not exist on switch. Verify "
                             "switch platform or create it first with "
                             "nxos_interface if it's a logical interface")

    mode = get_interface_mode(interface, intf_type, module)
    if mode == 'layer2':
        module.fail_json(msg='Ensure interface is a Layer 3 port before '
                         'configuring a VRF on an interface. You can '
                         'use nxos_interface')

    current_vrf = get_interface_info(interface, module)
    existing = dict(interface=interface, vrf=current_vrf)
    changed = False

    if not existing['vrf']:
        pass
    elif vrf != existing['vrf'] and state == 'absent':
        module.fail_json(msg='The VRF you are trying to remove '
                         'from the interface does not exist '
                         'on that interface.',
                         interface=interface,
                         proposed_vrf=vrf,
                         existing_vrf=existing['vrf'])

    commands = []
    if existing:
        if state == 'absent':
            if existing and vrf == existing['vrf']:
                command = 'no vrf member {0}'.format(vrf)
                commands.append(command)

        elif state == 'present':
            if existing['vrf'] != vrf:
                command = 'vrf member {0}'.format(vrf)
                commands.append(command)

    if commands:
        commands.insert(0, 'interface {0}'.format(interface))

    if commands:
        if module.check_mode:
            module.exit_json(changed=True, commands=commands)
        else:
            load_config(module, commands)
            changed = True
            if 'configure' in commands:
                commands.pop(0)

    results['commands'] = commands
    results['changed'] = changed

    module.exit_json(**results)
示例#2
0
def main():
    module = AnsibleModule(argument_spec=dict(
        src=dict(type='path'),
        deployment=dict(type='str', required=True),
        deploy_path=dict(type='path', default=DEFAULT_DEPLOY_PATH),
        state=dict(type='str',
                   choices=['absent', 'present'],
                   default='present'),
    ),
                           required_if=[('state', 'present', ('src', ))],
                           supports_check_mode=True)

    result = dict(changed=False)

    src = module.params['src']
    deployment = module.params['deployment']
    deploy_path = module.params['deploy_path']
    state = module.params['state']

    if not os.path.exists(deploy_path):
        module.fail_json(msg="deploy_path does not exist.")

    if state == 'absent' and src:
        module.warn('Parameter src is ignored when state=absent')
    elif state == 'present' and not os.path.exists(src):
        module.fail_json(msg='Source file %s does not exist.' % src)

    deployed = is_deployed(deploy_path, deployment)

    # === when check_mode ===
    if module.check_mode:
        if state == 'present':
            if not deployed:
                result['changed'] = True

            elif deployed:
                if module.sha1(src) != module.sha1(
                        os.path.join(deploy_path, deployment)):
                    result['changed'] = True

        elif state == 'absent' and deployed:
            result['changed'] = True

        module.exit_json(**result)
    # =======================

    if state == 'present' and not deployed:
        if is_failed(deploy_path, deployment):
            # Clean up old failed deployment
            os.remove(os.path.join(deploy_path, "%s.failed" % deployment))

        shutil.copyfile(src, os.path.join(deploy_path, deployment))
        while not deployed:
            deployed = is_deployed(deploy_path, deployment)
            if is_failed(deploy_path, deployment):
                module.fail_json(msg='Deploying %s failed.' % deployment)
            time.sleep(1)
        result['changed'] = True

    if state == 'present' and deployed:
        if module.sha1(src) != module.sha1(
                os.path.join(deploy_path, deployment)):
            os.remove(os.path.join(deploy_path, "%s.deployed" % deployment))
            shutil.copyfile(src, os.path.join(deploy_path, deployment))
            deployed = False
            while not deployed:
                deployed = is_deployed(deploy_path, deployment)
                if is_failed(deploy_path, deployment):
                    module.fail_json(msg='Deploying %s failed.' % deployment)
                time.sleep(1)
            result['changed'] = True

    if state == 'absent' and deployed:
        os.remove(os.path.join(deploy_path, "%s.deployed" % deployment))
        while deployed:
            deployed = not is_undeployed(deploy_path, deployment)
            if is_failed(deploy_path, deployment):
                module.fail_json(msg='Undeploying %s failed.' % deployment)
            time.sleep(1)
        result['changed'] = True

    module.exit_json(**result)
示例#3
0
def main():
    arg_spec = dict(
        name=dict(default=None),
        path=dict(default=None, type='path'),
        version=dict(default=None),
        production=dict(default='no', type='bool'),
        executable=dict(default=None, type='path'),
        registry=dict(default=None),
        state=dict(default='present', choices=['present', 'absent', 'latest']),
        ignore_scripts=dict(default=False, type='bool'),
    )
    arg_spec['global'] = dict(default='no', type='bool')
    module = AnsibleModule(
        argument_spec=arg_spec,
        supports_check_mode=True
    )

    name = module.params['name']
    path = module.params['path']
    version = module.params['version']
    globally = module.params['global']
    production = module.params['production']
    executable = module.params['executable']
    registry = module.params['registry']
    state = module.params['state']
    ignore_scripts = module.params['ignore_scripts']

    # When installing globally, users should not be able to define a path for installation.
    # Require a path if global is False, though!
    if path is None and globally is False:
        module.fail_json(msg='Path must be specified when not using global arg')
    elif path and globally is True:
        module.fail_json(msg='Cannot specify path if doing global installation')

    if state == 'absent' and not name:
        module.fail_json(msg='Package must be explicitly named when uninstalling.')
    if state == 'latest':
        version = 'latest'

    # When installing globally, use the defined path for global node_modules
    if globally:
        path = Yarn.DEFAULT_GLOBAL_INSTALLATION_PATH

    yarn = Yarn(module,
                name=name,
                path=path,
                version=version,
                globally=globally,
                production=production,
                executable=executable,
                registry=registry,
                ignore_scripts=ignore_scripts)

    changed = False
    out = ''
    err = ''
    if state == 'present':

        if not name:
            changed = True
            out, err = yarn.install()
        else:
            installed, missing = yarn.list()
            if len(missing):
                changed = True
                out, err = yarn.install()

    elif state == 'latest':

        if not name:
            changed = True
            out, err = yarn.install()
        else:
            installed, missing = yarn.list()
            outdated = yarn.list_outdated()
            if len(missing):
                changed = True
                out, err = yarn.install()
            if len(outdated):
                changed = True
                out, err = yarn.update()
    else:
        # state == absent
        installed, missing = yarn.list()
        if name in installed:
            changed = True
            out, err = yarn.uninstall()

    module.exit_json(changed=changed, out=out, err=err)
def main():
    fields = {
        "host": {
            "required": False,
            "type": "str"
        },
        "username": {
            "required": False,
            "type": "str"
        },
        "password": {
            "required": False,
            "type": "str",
            "default": "",
            "no_log": True
        },
        "vdom": {
            "required": False,
            "type": "str",
            "default": "root"
        },
        "https": {
            "required": False,
            "type": "bool",
            "default": True
        },
        "ssl_verify": {
            "required": False,
            "type": "bool",
            "default": True
        },
        "system_fips_cc": {
            "required": False,
            "type": "dict",
            "default": None,
            "options": {
                "entropy_token": {
                    "required": False,
                    "type": "str",
                    "choices": ["enable", "disable", "dynamic"]
                },
                "key_generation_self_test": {
                    "required": False,
                    "type": "str",
                    "choices": ["enable", "disable"]
                },
                "self_test_period": {
                    "required": False,
                    "type": "int"
                }
            }
        }
    }

    module = AnsibleModule(argument_spec=fields, supports_check_mode=False)

    # legacy_mode refers to using fortiosapi instead of HTTPAPI
    legacy_mode = 'host' in module.params and module.params['host'] is not None and \
                  'username' in module.params and module.params['username'] is not None and \
                  'password' in module.params and module.params['password'] is not None

    if not legacy_mode:
        if module._socket_path:
            connection = Connection(module._socket_path)
            fos = FortiOSHandler(connection)

            is_error, has_changed, result = fortios_system(module.params, fos)
        else:
            module.fail_json(**FAIL_SOCKET_MSG)
    else:
        try:
            from fortiosapi import FortiOSAPI
        except ImportError:
            module.fail_json(msg="fortiosapi module is required")

        fos = FortiOSAPI()

        login(module.params, fos)
        is_error, has_changed, result = fortios_system(module.params, fos)
        fos.logout()

    if not is_error:
        module.exit_json(changed=has_changed, meta=result)
    else:
        module.fail_json(msg="Error in repo", meta=result)
def main():
    module = AnsibleModule(
        argument_spec=dict(type=dict(required=True, type='str'),
                           zone=dict(required=True,
                                     aliases=['name'],
                                     type='str'),
                           nameserver=dict(default=[], type='list'),
                           interfaces=dict(default=[], type='list'),
                           refresh=dict(default=3600, type='int'),
                           retry=dict(default=1800, type='int'),
                           expire=dict(default=604800, type='int'),
                           ttl=dict(default=600, type='int'),
                           contact=dict(default='', type='str'),
                           mx=dict(default=[], type='list'),
                           state=dict(default='present',
                                      choices=['present', 'absent'],
                                      type='str')),
        supports_check_mode=True,
        required_if=([('state', 'present', ['nameserver', 'interfaces'])]))
    type = module.params['type']
    zone = module.params['zone']
    nameserver = module.params['nameserver']
    interfaces = module.params['interfaces']
    refresh = module.params['refresh']
    retry = module.params['retry']
    expire = module.params['expire']
    ttl = module.params['ttl']
    contact = module.params['contact']
    mx = module.params['mx']
    state = module.params['state']
    changed = False
    diff = None

    obj = list(
        ldap_search('(&(objectClass=dNSZone)(zoneName={0}))'.format(zone),
                    attr=['dNSZone']))

    exists = bool(len(obj))
    container = 'cn=dns,{0}'.format(base_dn())
    dn = 'zoneName={0},{1}'.format(zone, container)
    if contact == '':
        contact = 'root@{0}.'.format(zone)

    if state == 'present':
        try:
            if not exists:
                obj = umc_module_for_add('dns/{0}'.format(type), container)
            else:
                obj = umc_module_for_edit('dns/{0}'.format(type), dn)
            obj['zone'] = zone
            obj['nameserver'] = nameserver
            obj['a'] = interfaces
            obj['refresh'] = convert_time(refresh)
            obj['retry'] = convert_time(retry)
            obj['expire'] = convert_time(expire)
            obj['ttl'] = convert_time(ttl)
            obj['contact'] = contact
            obj['mx'] = mx
            diff = obj.diff()
            if exists:
                for k in obj.keys():
                    if obj.hasChanged(k):
                        changed = True
            else:
                changed = True
            if not module.check_mode:
                if not exists:
                    obj.create()
                elif changed:
                    obj.modify()
        except Exception as e:
            module.fail_json(
                msg='Creating/editing dns zone {0} failed: {1}'.format(
                    zone, e))

    if state == 'absent' and exists:
        try:
            obj = umc_module_for_edit('dns/{0}'.format(type), dn)
            if not module.check_mode:
                obj.remove()
            changed = True
        except Exception as e:
            module.fail_json(
                msg='Removing dns zone {0} failed: {1}'.format(zone, e))

    module.exit_json(changed=changed, diff=diff, zone=zone)
def main():
    """main entry point for execution
    """
    backup_spec = dict(
        filename=dict(),
        dir_path=dict(type='path')
    )
    argument_spec = dict(
        backup=dict(default=False, type='bool'),
        backup_options=dict(type='dict', options=backup_spec),
        config=dict(type='str'),
        commit=dict(type='bool'),
        replace=dict(type='str'),
        rollback=dict(type='int'),
        commit_comment=dict(type='str'),
        defaults=dict(default=False, type='bool'),
        multiline_delimiter=dict(type='str'),
        diff_replace=dict(choices=['line', 'block', 'config']),
        diff_match=dict(choices=['line', 'strict', 'exact', 'none']),
        diff_ignore_lines=dict(type='list')
    )

    mutually_exclusive = [('config', 'rollback')]
    required_one_of = [['backup', 'config', 'rollback']]

    module = AnsibleModule(argument_spec=argument_spec,
                           mutually_exclusive=mutually_exclusive,
                           required_one_of=required_one_of,
                           supports_check_mode=True)

    result = {'changed': False}

    connection = Connection(module._socket_path)
    capabilities = module.from_json(connection.get_capabilities())

    if capabilities:
        device_operations = capabilities.get('device_operations', dict())
        validate_args(module, device_operations)
    else:
        device_operations = dict()

    if module.params['defaults']:
        if 'get_default_flag' in capabilities.get('rpc'):
            flags = connection.get_default_flag()
        else:
            flags = 'all'
    else:
        flags = []

    candidate = module.params['config']
    candidate = to_text(candidate, errors='surrogate_then_replace') if candidate else None
    running = connection.get_config(flags=flags)
    rollback_id = module.params['rollback']

    if module.params['backup']:
        result['__backup__'] = running

    if candidate or rollback_id or module.params['replace']:
        try:
            result.update(run(module, device_operations, connection, candidate, running, rollback_id))
        except Exception as exc:
            module.fail_json(msg=to_text(exc))

    module.exit_json(**result)
def main():
    fields = {
        "host": {"required": False, "type": "str"},
        "username": {"required": False, "type": "str"},
        "password": {"required": False, "type": "str", "default": "", "no_log": True},
        "vdom": {"required": False, "type": "str", "default": "root"},
        "https": {"required": False, "type": "bool", "default": True},
        "ssl_verify": {"required": False, "type": "bool", "default": True},
        "state": {"required": False, "type": "str",
                  "choices": ["present", "absent"]},
        "firewall_proxy_address": {
            "required": False, "type": "dict", "default": None,
            "options": {
                "state": {"required": False, "type": "str",
                          "choices": ["present", "absent"]},
                "case_sensitivity": {"required": False, "type": "str",
                                     "choices": ["disable", "enable"]},
                "category": {"required": False, "type": "list",
                             "options": {
                                 "id": {"required": True, "type": "int"}
                             }},
                "color": {"required": False, "type": "int"},
                "comment": {"required": False, "type": "str"},
                "header": {"required": False, "type": "str"},
                "header_group": {"required": False, "type": "list",
                                 "options": {
                                     "case_sensitivity": {"required": False, "type": "str",
                                                          "choices": ["disable", "enable"]},
                                     "header": {"required": False, "type": "str"},
                                     "header_name": {"required": False, "type": "str"},
                                     "id": {"required": True, "type": "int"}
                                 }},
                "header_name": {"required": False, "type": "str"},
                "host": {"required": False, "type": "str"},
                "host_regex": {"required": False, "type": "str"},
                "method": {"required": False, "type": "str",
                           "choices": ["get", "post", "put",
                                       "head", "connect", "trace",
                                       "options", "delete"]},
                "name": {"required": True, "type": "str"},
                "path": {"required": False, "type": "str"},
                "query": {"required": False, "type": "str"},
                "referrer": {"required": False, "type": "str",
                             "choices": ["enable", "disable"]},
                "tagging": {"required": False, "type": "list",
                            "options": {
                                "category": {"required": False, "type": "str"},
                                "name": {"required": True, "type": "str"},
                                "tags": {"required": False, "type": "list",
                                         "options": {
                                             "name": {"required": True, "type": "str"}
                                         }}
                            }},
                "type": {"required": False, "type": "str",
                         "choices": ["host-regex", "url", "category",
                                     "method", "ua", "header",
                                     "src-advanced", "dst-advanced"]},
                "ua": {"required": False, "type": "str",
                       "choices": ["chrome", "ms", "firefox",
                                   "safari", "other"]},
                "uuid": {"required": False, "type": "str"},
                "visibility": {"required": False, "type": "str",
                               "choices": ["enable", "disable"]}

            }
        }
    }

    module = AnsibleModule(argument_spec=fields,
                           supports_check_mode=False)

    # legacy_mode refers to using fortiosapi instead of HTTPAPI
    legacy_mode = 'host' in module.params and module.params['host'] is not None and \
                  'username' in module.params and module.params['username'] is not None and \
                  'password' in module.params and module.params['password'] is not None

    if not legacy_mode:
        if module._socket_path:
            connection = Connection(module._socket_path)
            fos = FortiOSHandler(connection)

            is_error, has_changed, result = fortios_firewall(module.params, fos)
        else:
            module.fail_json(**FAIL_SOCKET_MSG)
    else:
        try:
            from fortiosapi import FortiOSAPI
        except ImportError:
            module.fail_json(msg="fortiosapi module is required")

        fos = FortiOSAPI()

        login(module.params, fos)
        is_error, has_changed, result = fortios_firewall(module.params, fos)
        fos.logout()

    if not is_error:
        module.exit_json(changed=has_changed, meta=result)
    else:
        module.fail_json(msg="Error in repo", meta=result)
def main():
    argument_spec = ucs_argument_spec
    argument_spec.update(
        org_dn=dict(type='str', default='org-root'),
        name=dict(type='str', required=True),
        description=dict(type='str', aliases=['descr'], default=''),
        fabric=dict(type='str', default='A', choices=['A', 'B', 'A-B', 'B-A']),
        redundancy_type=dict(type='str', default='none', choices=['none', 'primary', 'secondary']),
        peer_redundancy_template=dict(type='str', aliases=['peer_redundancy_templ'], default=''),
        target=dict(type='str', default='adapter', choices=['adapter', 'vm']),
        template_type=dict(type='str', default='initial-template', choices=['initial-template', 'updating-template']),
        vlans_list=dict(type='list'),
        cdn_source=dict(type='str', default='vnic-name', choices=['vnic-name', 'user-defined']),
        cdn_name=dict(type='str', default=''),
        mtu=dict(type='str', default='1500'),
        mac_pool=dict(type='str', default=''),
        qos_policy=dict(type='str', default=''),
        network_control_policy=dict(type='str', default=''),
        pin_group=dict(type='str', default=''),
        stats_policy=dict(type='str', default='default'),
        state=dict(type='str', default='present', choices=['present', 'absent']),
    )

    module = AnsibleModule(
        argument_spec,
        supports_check_mode=True,
        required_if=[
            ['cdn_source', 'user-defined', ['cdn_name']],
        ],
    )
    ucs = UCSModule(module)

    err = False

    # UCSModule creation above verifies ucsmsdk is present and exits on failure.  Additional imports are done below.
    from ucsmsdk.mometa.vnic.VnicLanConnTempl import VnicLanConnTempl
    from ucsmsdk.mometa.vnic.VnicEtherIf import VnicEtherIf

    changed = False
    try:
        mo_exists = False
        props_match = False
        # dn is <org_dn>/lan-conn-templ-<name>
        dn = module.params['org_dn'] + '/lan-conn-templ-' + module.params['name']

        mo = ucs.login_handle.query_dn(dn)
        if mo:
            mo_exists = True

        if module.params['state'] == 'absent':
            # mo must exist but all properties do not have to match
            if mo_exists:
                if not module.check_mode:
                    ucs.login_handle.remove_mo(mo)
                    ucs.login_handle.commit()
                changed = True
        else:
            # set default params for lists which can't be done in the argument_spec
            if module.params.get('vlans_list'):
                for vlan in module.params['vlans_list']:
                    if not vlan.get('native'):
                        vlan['native'] = 'no'
                    if not vlan.get('state'):
                        vlan['state'] = 'present'
            # for target 'adapter', change to internal UCS Manager spelling 'adaptor'
            if module.params['target'] == 'adapter':
                module.params['target'] = 'adaptor'
            if mo_exists:
                # check top-level mo props
                kwargs = dict(descr=module.params['description'])
                kwargs['switch_id'] = module.params['fabric']
                kwargs['redundancy_pair_type'] = module.params['redundancy_type']
                kwargs['peer_redundancy_templ_name'] = module.params['peer_redundancy_template']
                kwargs['ident_pool_name'] = module.params['mac_pool']
                # do not check shared props if this is a secondary template
                if module.params['redundancy_type'] != 'secondary':
                    kwargs['target'] = module.params['target']
                    kwargs['templ_type'] = module.params['template_type']
                    kwargs['cdn_source'] = module.params['cdn_source']
                    kwargs['admin_cdn_name'] = module.params['cdn_name']
                    kwargs['mtu'] = module.params['mtu']
                    kwargs['qos_policy_name'] = module.params['qos_policy']
                    kwargs['nw_ctrl_policy_name'] = module.params['network_control_policy']
                    kwargs['pin_to_group_name'] = module.params['pin_group']
                    kwargs['stats_policy_name'] = module.params['stats_policy']
                if mo.check_prop_match(**kwargs):
                    # top-level props match, check next level mo/props
                    if not module.params.get('vlans_list'):
                        props_match = True
                    else:
                        # check vlan props
                        for vlan in module.params['vlans_list']:
                            child_dn = dn + '/if-' + str(vlan['name'])
                            mo_1 = ucs.login_handle.query_dn(child_dn)
                            if vlan['state'] == 'absent':
                                if mo_1:
                                    props_match = False
                                    break
                            else:
                                if mo_1:
                                    kwargs = dict(default_net=vlan['native'])
                                    if mo_1.check_prop_match(**kwargs):
                                        props_match = True
                                else:
                                    props_match = False
                                    break

            if not props_match:
                if not module.check_mode:
                    # create if mo does not already exist
                    # secondary template only sets non shared props
                    if module.params['redundancy_type'] == 'secondary':
                        mo = VnicLanConnTempl(
                            parent_mo_or_dn=module.params['org_dn'],
                            name=module.params['name'],
                            descr=module.params['description'],
                            switch_id=module.params['fabric'],
                            redundancy_pair_type=module.params['redundancy_type'],
                            peer_redundancy_templ_name=module.params['peer_redundancy_template'],
                            ident_pool_name=module.params['mac_pool'],
                        )
                    else:
                        mo = VnicLanConnTempl(
                            parent_mo_or_dn=module.params['org_dn'],
                            name=module.params['name'],
                            descr=module.params['description'],
                            switch_id=module.params['fabric'],
                            redundancy_pair_type=module.params['redundancy_type'],
                            peer_redundancy_templ_name=module.params['peer_redundancy_template'],
                            target=module.params['target'],
                            templ_type=module.params['template_type'],
                            cdn_source=module.params['cdn_source'],
                            admin_cdn_name=module.params['cdn_name'],
                            mtu=module.params['mtu'],
                            ident_pool_name=module.params['mac_pool'],
                            qos_policy_name=module.params['qos_policy'],
                            nw_ctrl_policy_name=module.params['network_control_policy'],
                            pin_to_group_name=module.params['pin_group'],
                            stats_policy_name=module.params['stats_policy'],
                        )

                    if module.params.get('vlans_list'):
                        for vlan in module.params['vlans_list']:
                            if vlan['state'] == 'absent':
                                child_dn = dn + '/if-' + str(vlan['name'])
                                mo_1 = ucs.login_handle.query_dn(child_dn)
                                ucs.login_handle.remove_mo(mo_1)
                            else:
                                mo_1 = VnicEtherIf(
                                    parent_mo_or_dn=mo,
                                    name=str(vlan['name']),
                                    default_net=vlan['native'],
                                )

                    ucs.login_handle.add_mo(mo, True)
                    ucs.login_handle.commit()
                changed = True

    except Exception as e:
        err = True
        ucs.result['msg'] = "setup error: %s " % str(e)

    ucs.result['changed'] = changed
    if err:
        module.fail_json(**ucs.result)
    module.exit_json(**ucs.result)
def run_module():
    # available arguments/parameters that a user can pass
    module_args = dict(
        state=dict(type='str', default='present', choices=['present', 'absent', 'opened', 'closed']),
        device=dict(type='str'),
        name=dict(type='str'),
        keyfile=dict(type='path'),
        new_keyfile=dict(type='path'),
        remove_keyfile=dict(type='path'),
        passphrase=dict(type='str', no_log=True),
        new_passphrase=dict(type='str', no_log=True),
        remove_passphrase=dict(type='str', no_log=True),
        force_remove_last_key=dict(type='bool', default=False),
        keysize=dict(type='int'),
        label=dict(type='str'),
        uuid=dict(type='str'),
        type=dict(type='str', choices=['luks1', 'luks2']),
    )

    mutually_exclusive = [
        ('keyfile', 'passphrase'),
        ('new_keyfile', 'new_passphrase'),
        ('remove_keyfile', 'remove_passphrase')
    ]

    # seed the result dict in the object
    result = dict(
        changed=False,
        name=None
    )

    module = AnsibleModule(argument_spec=module_args,
                           supports_check_mode=True,
                           mutually_exclusive=mutually_exclusive)

    if module.params['device'] is not None:
        try:
            statinfo = os.stat(module.params['device'])
            mode = statinfo.st_mode
            if not stat.S_ISBLK(mode) and not stat.S_ISCHR(mode):
                raise Exception('{0} is not a device'.format(module.params['device']))
        except Exception as e:
            module.fail_json(msg=str(e))

    crypt = CryptHandler(module)
    conditions = ConditionsHandler(module, crypt)

    # conditions not allowed to run
    if module.params['label'] is not None and module.params['type'] == 'luks1':
        module.fail_json(msg='You cannot combine type luks1 with the label option.')

    # The conditions are in order to allow more operations in one run.
    # (e.g. create luks and add a key to it)

    # luks create
    if conditions.luks_create():
        if not module.check_mode:
            try:
                crypt.run_luks_create(conditions.device,
                                      module.params['keyfile'],
                                      module.params['passphrase'],
                                      module.params['keysize'])
            except ValueError as e:
                module.fail_json(msg="luks_device error: %s" % e)
        result['changed'] = True
        if module.check_mode:
            module.exit_json(**result)

    # luks open

    name = conditions.opened_luks_name()
    if name is not None:
        result['name'] = name

    if conditions.luks_open():
        name = module.params['name']
        if name is None:
            try:
                name = crypt.generate_luks_name(conditions.device)
            except ValueError as e:
                module.fail_json(msg="luks_device error: %s" % e)
        if not module.check_mode:
            try:
                crypt.run_luks_open(conditions.device,
                                    module.params['keyfile'],
                                    module.params['passphrase'],
                                    name)
            except ValueError as e:
                module.fail_json(msg="luks_device error: %s" % e)
        result['name'] = name
        result['changed'] = True
        if module.check_mode:
            module.exit_json(**result)

    # luks close
    if conditions.luks_close():
        if conditions.device is not None:
            try:
                name = crypt.get_container_name_by_device(
                    conditions.device)
            except ValueError as e:
                module.fail_json(msg="luks_device error: %s" % e)
        else:
            name = module.params['name']
        if not module.check_mode:
            try:
                crypt.run_luks_close(name)
            except ValueError as e:
                module.fail_json(msg="luks_device error: %s" % e)
        result['name'] = name
        result['changed'] = True
        if module.check_mode:
            module.exit_json(**result)

    # luks add key
    if conditions.luks_add_key():
        if not module.check_mode:
            try:
                crypt.run_luks_add_key(conditions.device,
                                       module.params['keyfile'],
                                       module.params['passphrase'],
                                       module.params['new_keyfile'],
                                       module.params['new_passphrase'])
            except ValueError as e:
                module.fail_json(msg="luks_device error: %s" % e)
        result['changed'] = True
        if module.check_mode:
            module.exit_json(**result)

    # luks remove key
    if conditions.luks_remove_key():
        if not module.check_mode:
            try:
                last_key = module.params['force_remove_last_key']
                crypt.run_luks_remove_key(conditions.device,
                                          module.params['remove_keyfile'],
                                          module.params['remove_passphrase'],
                                          force_remove_last_key=last_key)
            except ValueError as e:
                module.fail_json(msg="luks_device error: %s" % e)
        result['changed'] = True
        if module.check_mode:
            module.exit_json(**result)

    # luks remove
    if conditions.luks_remove():
        if not module.check_mode:
            try:
                crypt.run_luks_remove(conditions.device)
            except ValueError as e:
                module.fail_json(msg="luks_device error: %s" % e)
        result['changed'] = True
        if module.check_mode:
            module.exit_json(**result)

    # Success - return result
    module.exit_json(**result)
def main():
    argument_spec = rax_argument_spec()
    argument_spec.update(
        dict(
            address=dict(),
            condition=dict(choices=['enabled', 'disabled', 'draining']),
            load_balancer_id=dict(required=True, type='int'),
            node_id=dict(type='int'),
            port=dict(type='int'),
            state=dict(default='present', choices=['present', 'absent']),
            type=dict(choices=['primary', 'secondary']),
            virtualenv=dict(type='path'),
            wait=dict(default=False, type='bool'),
            wait_timeout=dict(default=30, type='int'),
            weight=dict(type='int'),
        ))

    module = AnsibleModule(
        argument_spec=argument_spec,
        required_together=rax_required_together(),
    )

    if not HAS_PYRAX:
        module.fail_json(msg='pyrax is required for this module')

    address = module.params['address']
    condition = (module.params['condition']
                 and module.params['condition'].upper())
    load_balancer_id = module.params['load_balancer_id']
    node_id = module.params['node_id']
    port = module.params['port']
    state = module.params['state']
    typ = module.params['type'] and module.params['type'].upper()
    virtualenv = module.params['virtualenv']
    wait = module.params['wait']
    wait_timeout = module.params['wait_timeout'] or 1
    weight = module.params['weight']

    if virtualenv:
        try:
            _activate_virtualenv(virtualenv)
        except IOError as e:
            module.fail_json(msg='Failed to activate virtualenv %s (%s)' %
                             (virtualenv, e))

    setup_rax_module(module, pyrax)

    if not pyrax.cloud_loadbalancers:
        module.fail_json(msg='Failed to instantiate client. This '
                         'typically indicates an invalid region or an '
                         'incorrectly capitalized region name.')

    try:
        lb = pyrax.cloud_loadbalancers.get(load_balancer_id)
    except pyrax.exc.PyraxException as e:
        module.fail_json(msg='%s' % e.message)

    node = _get_node(lb, node_id, address, port)

    result = rax_clb_node_to_dict(node)

    if state == 'absent':
        if not node:  # Removing a non-existent node
            module.exit_json(changed=False, state=state)
        try:
            lb.delete_node(node)
            result = {}
        except pyrax.exc.NotFound:
            module.exit_json(changed=False, state=state)
        except pyrax.exc.PyraxException as e:
            module.fail_json(msg='%s' % e.message)
    else:  # present
        if not node:
            if node_id:  # Updating a non-existent node
                msg = 'Node %d not found' % node_id
                if lb.nodes:
                    msg += (' (available nodes: %s)' %
                            ', '.join([str(x.id) for x in lb.nodes]))
                module.fail_json(msg=msg)
            else:  # Creating a new node
                try:
                    node = pyrax.cloudloadbalancers.Node(address=address,
                                                         port=port,
                                                         condition=condition,
                                                         weight=weight,
                                                         type=typ)
                    resp, body = lb.add_nodes([node])
                    result.update(body['nodes'][0])
                except pyrax.exc.PyraxException as e:
                    module.fail_json(msg='%s' % e.message)
        else:  # Updating an existing node
            mutable = {
                'condition': condition,
                'type': typ,
                'weight': weight,
            }

            for name, value in mutable.items():
                if value is None or value == getattr(node, name):
                    mutable.pop(name)

            if not mutable:
                module.exit_json(changed=False, state=state, node=result)

            try:
                # The diff has to be set explicitly to update node's weight and
                # type; this should probably be fixed in pyrax
                lb.update_node(node, diff=mutable)
                result.update(mutable)
            except pyrax.exc.PyraxException as e:
                module.fail_json(msg='%s' % e.message)

    if wait:
        pyrax.utils.wait_until(lb,
                               "status",
                               "ACTIVE",
                               interval=1,
                               attempts=wait_timeout)
        if lb.status != 'ACTIVE':
            module.fail_json(
                msg='Load balancer not active after %ds (current status: %s)' %
                (wait_timeout, lb.status.lower()))

    kwargs = {'node': result} if result else {}
    module.exit_json(changed=True, state=state, **kwargs)
def main():
    argument_spec = ec2_argument_spec()
    argument_spec.update(
        dict(distribution_id=dict(required=False, type='str'),
             invalidation_id=dict(required=False, type='str'),
             origin_access_identity_id=dict(required=False, type='str'),
             domain_name_alias=dict(required=False, type='str'),
             all_lists=dict(required=False, default=False, type='bool'),
             distribution=dict(required=False, default=False, type='bool'),
             distribution_config=dict(required=False,
                                      default=False,
                                      type='bool'),
             origin_access_identity=dict(required=False,
                                         default=False,
                                         type='bool'),
             origin_access_identity_config=dict(required=False,
                                                default=False,
                                                type='bool'),
             invalidation=dict(required=False, default=False, type='bool'),
             streaming_distribution=dict(required=False,
                                         default=False,
                                         type='bool'),
             streaming_distribution_config=dict(required=False,
                                                default=False,
                                                type='bool'),
             list_origin_access_identities=dict(required=False,
                                                default=False,
                                                type='bool'),
             list_distributions=dict(required=False,
                                     default=False,
                                     type='bool'),
             list_distributions_by_web_acl_id=dict(required=False,
                                                   default=False,
                                                   type='bool'),
             list_invalidations=dict(required=False,
                                     default=False,
                                     type='bool'),
             list_streaming_distributions=dict(required=False,
                                               default=False,
                                               type='bool'),
             summary=dict(required=False, default=False, type='bool')))

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=False)
    is_old_facts = module._name == 'cloudfront_facts'
    if is_old_facts:
        module.deprecate(
            "The 'cloudfront_facts' module has been renamed to 'cloudfront_info', "
            "and the renamed one no longer returns ansible_facts",
            version='2.13')

    if not HAS_BOTO3:
        module.fail_json(msg='boto3 is required.')

    service_mgr = CloudFrontServiceManager(module)

    distribution_id = module.params.get('distribution_id')
    invalidation_id = module.params.get('invalidation_id')
    origin_access_identity_id = module.params.get('origin_access_identity_id')
    web_acl_id = module.params.get('web_acl_id')
    domain_name_alias = module.params.get('domain_name_alias')
    all_lists = module.params.get('all_lists')
    distribution = module.params.get('distribution')
    distribution_config = module.params.get('distribution_config')
    origin_access_identity = module.params.get('origin_access_identity')
    origin_access_identity_config = module.params.get(
        'origin_access_identity_config')
    invalidation = module.params.get('invalidation')
    streaming_distribution = module.params.get('streaming_distribution')
    streaming_distribution_config = module.params.get(
        'streaming_distribution_config')
    list_origin_access_identities = module.params.get(
        'list_origin_access_identities')
    list_distributions = module.params.get('list_distributions')
    list_distributions_by_web_acl_id = module.params.get(
        'list_distributions_by_web_acl_id')
    list_invalidations = module.params.get('list_invalidations')
    list_streaming_distributions = module.params.get(
        'list_streaming_distributions')
    summary = module.params.get('summary')

    aliases = []
    result = {'cloudfront': {}}
    facts = {}

    require_distribution_id = (distribution or distribution_config
                               or invalidation or streaming_distribution
                               or streaming_distribution_config
                               or list_invalidations)

    # set default to summary if no option specified
    summary = summary or not (
        distribution or distribution_config or origin_access_identity or
        origin_access_identity_config or invalidation or streaming_distribution
        or streaming_distribution_config or list_origin_access_identities
        or list_distributions_by_web_acl_id or list_invalidations
        or list_streaming_distributions or list_distributions)

    # validations
    if require_distribution_id and distribution_id is None and domain_name_alias is None:
        module.fail_json(
            msg=
            'Error distribution_id or domain_name_alias have not been specified.'
        )
    if (invalidation and invalidation_id is None):
        module.fail_json(msg='Error invalidation_id has not been specified.')
    if (origin_access_identity or origin_access_identity_config
        ) and origin_access_identity_id is None:
        module.fail_json(
            msg='Error origin_access_identity_id has not been specified.')
    if list_distributions_by_web_acl_id and web_acl_id is None:
        module.fail_json(msg='Error web_acl_id has not been specified.')

    # get distribution id from domain name alias
    if require_distribution_id and distribution_id is None:
        distribution_id = service_mgr.get_distribution_id_from_domain_name(
            domain_name_alias)
        if not distribution_id:
            module.fail_json(
                msg=
                'Error unable to source a distribution id from domain_name_alias'
            )

    # set appropriate cloudfront id
    if distribution_id and not list_invalidations:
        facts = {distribution_id: {}}
        aliases = service_mgr.get_aliases_from_distribution_id(distribution_id)
        for alias in aliases:
            facts.update({alias: {}})
        if invalidation_id:
            facts.update({invalidation_id: {}})
    elif distribution_id and list_invalidations:
        facts = {distribution_id: {}}
        aliases = service_mgr.get_aliases_from_distribution_id(distribution_id)
        for alias in aliases:
            facts.update({alias: {}})
    elif origin_access_identity_id:
        facts = {origin_access_identity_id: {}}
    elif web_acl_id:
        facts = {web_acl_id: {}}

    # get details based on options
    if distribution:
        facts_to_set = service_mgr.get_distribution(distribution_id)
    if distribution_config:
        facts_to_set = service_mgr.get_distribution_config(distribution_id)
    if origin_access_identity:
        facts[origin_access_identity_id].update(
            service_mgr.get_origin_access_identity(origin_access_identity_id))
    if origin_access_identity_config:
        facts[origin_access_identity_id].update(
            service_mgr.get_origin_access_identity_config(
                origin_access_identity_id))
    if invalidation:
        facts_to_set = service_mgr.get_invalidation(distribution_id,
                                                    invalidation_id)
        facts[invalidation_id].update(facts_to_set)
    if streaming_distribution:
        facts_to_set = service_mgr.get_streaming_distribution(distribution_id)
    if streaming_distribution_config:
        facts_to_set = service_mgr.get_streaming_distribution_config(
            distribution_id)
    if list_invalidations:
        facts_to_set = {
            'invalidations': service_mgr.list_invalidations(distribution_id)
        }
    if 'facts_to_set' in vars():
        facts = set_facts_for_distribution_id_and_alias(
            facts_to_set, facts, distribution_id, aliases)

    # get list based on options
    if all_lists or list_origin_access_identities:
        facts[
            'origin_access_identities'] = service_mgr.list_origin_access_identities(
            )
    if all_lists or list_distributions:
        facts['distributions'] = service_mgr.list_distributions()
    if all_lists or list_streaming_distributions:
        facts[
            'streaming_distributions'] = service_mgr.list_streaming_distributions(
            )
    if list_distributions_by_web_acl_id:
        facts[
            'distributions_by_web_acl_id'] = service_mgr.list_distributions_by_web_acl_id(
                web_acl_id)
    if list_invalidations:
        facts['invalidations'] = service_mgr.list_invalidations(
            distribution_id)

    # default summary option
    if summary:
        facts['summary'] = service_mgr.summary()

    result['changed'] = False
    result['cloudfront'].update(facts)
    if is_old_facts:
        module.exit_json(msg="Retrieved CloudFront facts.",
                         ansible_facts=result)
    else:
        module.exit_json(msg="Retrieved CloudFront info.", **result)
示例#12
0
def main():
    module = AnsibleModule(argument_spec=dict(state=dict(
        default="present",
        choices=["present", "latest", "absent"],
        required=False),
                                              name=dict(aliases=["pkg"],
                                                        required=True,
                                                        type='list'),
                                              cached=dict(default=False,
                                                          type='bool'),
                                              annotation=dict(default="",
                                                              required=False),
                                              pkgsite=dict(default="",
                                                           required=False),
                                              rootdir=dict(default="",
                                                           required=False,
                                                           type='path'),
                                              chroot=dict(default="",
                                                          required=False,
                                                          type='path'),
                                              jail=dict(default="",
                                                        required=False,
                                                        type='str'),
                                              autoremove=dict(default=False,
                                                              type='bool')),
                           supports_check_mode=True,
                           mutually_exclusive=[["rootdir", "chroot", "jail"]])

    pkgng_path = module.get_bin_path('pkg', True)

    p = module.params

    pkgs = p["name"]

    changed = False
    msgs = []
    dir_arg = ""

    if p["rootdir"] != "":
        old_pkgng = pkgng_older_than(module, pkgng_path, [1, 5, 0])
        if old_pkgng:
            module.fail_json(
                msg="To use option 'rootdir' pkg version must be 1.5 or greater"
            )
        else:
            dir_arg = "--rootdir %s" % (p["rootdir"])

    if p["chroot"] != "":
        dir_arg = '--chroot %s' % (p["chroot"])

    if p["jail"] != "":
        dir_arg = '--jail %s' % (p["jail"])

    if p["state"] in ("present", "latest"):
        _changed, _msg = install_packages(module, pkgng_path, pkgs,
                                          p["cached"], p["pkgsite"], dir_arg,
                                          p["state"])
        changed = changed or _changed
        msgs.append(_msg)

    elif p["state"] == "absent":
        _changed, _msg = remove_packages(module, pkgng_path, pkgs, dir_arg)
        changed = changed or _changed
        msgs.append(_msg)

    if p["autoremove"]:
        _changed, _msg = autoremove_packages(module, pkgng_path, dir_arg)
        changed = changed or _changed
        msgs.append(_msg)

    if p["annotation"]:
        _changed, _msg = annotate_packages(module, pkgng_path, pkgs,
                                           p["annotation"], dir_arg)
        changed = changed or _changed
        msgs.append(_msg)

    module.exit_json(changed=changed, msg=", ".join(msgs))
def main():
    fields = {
        "host": {
            "required": False,
            "type": "str"
        },
        "username": {
            "required": False,
            "type": "str"
        },
        "password": {
            "required": False,
            "type": "str",
            "default": "",
            "no_log": True
        },
        "vdom": {
            "required": False,
            "type": "str",
            "default": "root"
        },
        "https": {
            "required": False,
            "type": "bool",
            "default": True
        },
        "ssl_verify": {
            "required": False,
            "type": "bool",
            "default": True
        },
        "state": {
            "required": True,
            "type": "str",
            "choices": ["present", "absent"]
        },
        "switch_controller_qos_ip_dscp_map": {
            "required": False,
            "type": "dict",
            "default": None,
            "options": {
                "description": {
                    "required": False,
                    "type": "str"
                },
                "map": {
                    "required": False,
                    "type": "list",
                    "options": {
                        "cos_queue": {
                            "required": False,
                            "type": "int"
                        },
                        "diffserv": {
                            "required":
                            False,
                            "type":
                            "str",
                            "choices": [
                                "CS0", "CS1", "AF11", "AF12", "AF13", "CS2",
                                "AF21", "AF22", "AF23", "CS3", "AF31", "AF32",
                                "AF33", "CS4", "AF41", "AF42", "AF43", "CS5",
                                "EF", "CS6", "CS7"
                            ]
                        },
                        "ip_precedence": {
                            "required":
                            False,
                            "type":
                            "str",
                            "choices": [
                                "network-control", "internetwork-control",
                                "critic-ecp", "flashoverride", "flash",
                                "immediate", "priority", "routine"
                            ]
                        },
                        "name": {
                            "required": True,
                            "type": "str"
                        },
                        "value": {
                            "required": False,
                            "type": "str"
                        }
                    }
                },
                "name": {
                    "required": True,
                    "type": "str"
                }
            }
        }
    }

    module = AnsibleModule(argument_spec=fields, supports_check_mode=False)

    # legacy_mode refers to using fortiosapi instead of HTTPAPI
    legacy_mode = 'host' in module.params and module.params['host'] is not None and \
                  'username' in module.params and module.params['username'] is not None and \
                  'password' in module.params and module.params['password'] is not None

    if not legacy_mode:
        if module._socket_path:
            connection = Connection(module._socket_path)
            fos = FortiOSHandler(connection)

            is_error, has_changed, result = fortios_switch_controller_qos(
                module.params, fos)
        else:
            module.fail_json(**FAIL_SOCKET_MSG)
    else:
        try:
            from fortiosapi import FortiOSAPI
        except ImportError:
            module.fail_json(msg="fortiosapi module is required")

        fos = FortiOSAPI()

        login(module.params, fos)
        is_error, has_changed, result = fortios_switch_controller_qos(
            module.params, fos)
        fos.logout()

    if not is_error:
        module.exit_json(changed=has_changed, meta=result)
    else:
        module.fail_json(msg="Error in repo", meta=result)
def main():
    """ Initiates module."""
    module = AnsibleModule(argument_spec=dict(
        balancer_vhost=dict(required=True, default=None, type='str'),
        balancer_url_suffix=dict(default="/balancer-manager/", type='str'),
        member_host=dict(type='str'),
        state=dict(type='str'),
        tls=dict(default=False, type='bool'),
        validate_certs=dict(default=True, type='bool')),
                           supports_check_mode=True)

    if HAS_BEAUTIFULSOUP is False:
        module.fail_json(msg=missing_required_lib('BeautifulSoup'),
                         exception=BEAUTIFUL_SOUP_IMP_ERR)

    if module.params['state'] is not None:
        states = module.params['state'].split(',')
        if (len(states) > 1) and (("present" in states) or
                                  ("enabled" in states)):
            module.fail_json(
                msg=
                "state present/enabled is mutually exclusive with other states!"
            )
        else:
            for _state in states:
                if _state not in [
                        'present', 'absent', 'enabled', 'disabled', 'drained',
                        'hot_standby', 'ignore_errors'
                ]:
                    module.fail_json(
                        msg=
                        "State can only take values amongst 'present', 'absent', 'enabled', 'disabled', 'drained', 'hot_standby', 'ignore_errors'."
                    )
    else:
        states = ['None']

    mybalancer = Balancer(module.params['balancer_vhost'],
                          module.params['balancer_url_suffix'],
                          module=module,
                          tls=module.params['tls'])

    if module.params['member_host'] is None:
        json_output_list = []
        for member in mybalancer.members:
            json_output_list.append({
                "host": member.host,
                "status": member.status,
                "protocol": member.protocol,
                "port": member.port,
                "path": member.path,
                "attributes": member.attributes,
                "management_url": member.management_url,
                "balancer_url": member.balancer_url
            })
        module.exit_json(changed=False, members=json_output_list)
    else:
        changed = False
        member_exists = False
        member_status = {
            'disabled': False,
            'drained': False,
            'hot_standby': False,
            'ignore_errors': False
        }
        for mode in member_status.keys():
            for state in states:
                if mode == state:
                    member_status[mode] = True
                elif mode == 'disabled' and state == 'absent':
                    member_status[mode] = True

        for member in mybalancer.members:
            if str(member.host) == str(module.params['member_host']):
                member_exists = True
                if module.params['state'] is not None:
                    member_status_before = member.status
                    if not module.check_mode:
                        member_status_after = member.status = member_status
                    else:
                        member_status_after = member_status
                    if member_status_before != member_status_after:
                        changed = True
                json_output = {
                    "host": member.host,
                    "status": member.status,
                    "protocol": member.protocol,
                    "port": member.port,
                    "path": member.path,
                    "attributes": member.attributes,
                    "management_url": member.management_url,
                    "balancer_url": member.balancer_url
                }
        if member_exists:
            module.exit_json(changed=changed, member=json_output)
        else:
            module.fail_json(msg=str(module.params['member_host']) +
                             ' is not a member of the balancer ' +
                             str(module.params['balancer_vhost']) + '!')
示例#15
0
def main():
    module = AnsibleModule(argument_spec=dict(
        name=dict(required=True),
        template=dict(),
        recreate_instances=dict(type='bool', default=False),
        # Do not set a default size here.  For Create and some update
        # operations, it is required and should be explicitly set.
        # Below, we set it to the existing value if it has not been set.
        size=dict(type='int'),
        state=dict(choices=['absent', 'present'], default='present'),
        zone=dict(required=True),
        autoscaling=dict(type='dict', default=None),
        named_ports=dict(type='list', default=None),
        service_account_email=dict(),
        service_account_permissions=dict(type='list'),
        pem_file=dict(type='path'),
        credentials_file=dict(type='path'),
        project_id=dict(), ), )

    if not HAS_PYTHON26:
        module.fail_json(
            msg="GCE module requires python's 'ast' module, python v2.6+")
    if not HAS_LIBCLOUD:
        module.fail_json(
            msg='libcloud with GCE Managed Instance Group support (1.2+) required for this module.')

    gce = gce_connect(module)
    if not hasattr(gce, 'ex_create_instancegroupmanager'):
        module.fail_json(
            msg='libcloud with GCE Managed Instance Group support (1.2+) required for this module.',
            changed=False)

    params = {}
    params['state'] = module.params.get('state')
    params['zone'] = module.params.get('zone')
    params['name'] = module.params.get('name')
    params['size'] = module.params.get('size')
    params['template'] = module.params.get('template')
    params['recreate_instances'] = module.params.get('recreate_instances')
    params['autoscaling'] = module.params.get('autoscaling', None)
    params['named_ports'] = module.params.get('named_ports', None)

    (valid_autoscaling, as_msg) = _validate_autoscaling_params(params)
    if not valid_autoscaling:
        module.fail_json(msg=as_msg, changed=False)

    if params['named_ports'] is not None and not hasattr(
            gce, 'ex_instancegroup_set_named_ports'):
        module.fail_json(
            msg="Apache Libcloud 1.3.0+ is required to use 'named_ports' option",
            changed=False)

    (valid_named_ports, np_msg) = _validate_named_port_params(params)
    if not valid_named_ports:
        module.fail_json(msg=np_msg, changed=False)

    changed = False
    json_output = {'state': params['state'], 'zone': params['zone']}
    mig = get_mig(gce, params['name'], params['zone'])

    if not mig:
        if params['state'] == 'absent':
            # Doesn't exist in GCE, and state==absent.
            changed = False
            module.fail_json(
                msg="Cannot delete unknown managed instance group: %s" %
                (params['name']))
        else:
            # Create MIG
            req_create_fields = [
                {'name': 'template', 'required': True, 'type': str},
                {'name': 'size', 'required': True, 'type': int}
            ]  # yapf: disable

            (valid_create_fields, valid_create_msg) = _check_params(
                params, req_create_fields)
            if not valid_create_fields:
                module.fail_json(msg=valid_create_msg, changed=False)

            (changed, json_output['created_instances']) = create_mig(gce,
                                                                     params)
            if params['autoscaling'] and params['autoscaling'][
                    'enabled'] is True:
                # Fetch newly-created MIG and create Autoscaler for it.
                mig = get_mig(gce, params['name'], params['zone'])
                if not mig:
                    module.fail_json(
                        msg='Unable to fetch created MIG %s to create \
                        autoscaler in zone: %s' % (
                            params['name'], params['zone']), changed=False)

                if not create_autoscaler(gce, mig, params['autoscaling']):
                    module.fail_json(
                        msg='Unable to fetch MIG %s to create autoscaler \
                        in zone: %s' % (params['name'], params['zone']),
                        changed=False)

                json_output['created_autoscaler'] = True
            # Add named ports if available
            if params['named_ports']:
                mig = get_mig(gce, params['name'], params['zone'])
                if not mig:
                    module.fail_json(
                        msg='Unable to fetch created MIG %s to create \
                        autoscaler in zone: %s' % (
                            params['name'], params['zone']), changed=False)
                json_output['set_named_ports'] = update_named_ports(
                    mig, params['named_ports'])
                if json_output['set_named_ports']:
                    json_output['named_ports'] = params['named_ports']

    elif params['state'] == 'absent':
        # Delete MIG

        # First, check and remove the autoscaler, if present.
        # Note: multiple autoscalers can be associated to a single MIG.  We
        # only handle the one that is named, but we might want to think about this.
        if params['autoscaling']:
            autoscaler = get_autoscaler(gce, params['autoscaling']['name'],
                                        params['zone'])
            if not autoscaler:
                module.fail_json(msg='Unable to fetch autoscaler %s to delete \
                in zone: %s' % (params['autoscaling']['name'], params['zone']),
                    changed=False)

            changed = delete_autoscaler(autoscaler)
            json_output['deleted_autoscaler'] = changed

        # Now, delete the MIG.
        (changed, json_output['deleted_instances']) = delete_mig(mig)

    else:
        # Update MIG

        # If we're going to update a MIG, we need a size and template values.
        # If not specified, we use the values from the existing MIG.
        if not params['size']:
            params['size'] = mig.size

        if not params['template']:
            params['template'] = mig.template.name

        if params['template'] != mig.template.name:
            # Update Instance Template.
            new_template = gce.ex_get_instancetemplate(params['template'])
            mig.set_instancetemplate(new_template)
            json_output['updated_instancetemplate'] = True
            changed = True
        if params['recreate_instances'] is True:
            # Recreate Instances.
            (changed, json_output['recreated_instances']
             ) = recreate_instances_in_mig(mig)

        if params['size'] != mig.size:
            # Resize MIG.
            keystr = 'created' if params['size'] > mig.size else 'deleted'
            (changed, json_output['resize_%s_instances' %
                                  (keystr)]) = resize_mig(mig, params['size'])

        # Update Autoscaler
        if params['autoscaling']:
            autoscaler = get_autoscaler(gce, params['autoscaling']['name'],
                                        params['zone'])
            if not autoscaler:
                # Try to create autoscaler.
                # Note: this isn't perfect, if the autoscaler name has changed
                # we wouldn't know that here.
                if not create_autoscaler(gce, mig, params['autoscaling']):
                    module.fail_json(
                        msg='Unable to create autoscaler %s for existing MIG %s\
                        in zone: %s' % (params['autoscaling']['name'],
                                        params['name'], params['zone']),
                        changed=False)
                json_output['created_autoscaler'] = True
                changed = True
            else:
                if params['autoscaling']['enabled'] is False:
                    # Delete autoscaler
                    changed = delete_autoscaler(autoscaler)
                    json_output['delete_autoscaler'] = changed
                else:
                    # Update policy, etc.
                    changed = update_autoscaler(gce, autoscaler,
                                                params['autoscaling'])
                    json_output['updated_autoscaler'] = changed
        named_ports = params['named_ports'] or []
        json_output['updated_named_ports'] = update_named_ports(mig,
                                                                named_ports)
        if json_output['updated_named_ports']:
            json_output['named_ports'] = named_ports

    json_output['changed'] = changed
    json_output.update(params)
    module.exit_json(**json_output)
def main():
    fields = {
        "host": {"required": False, "type": "str"},
        "username": {"required": False, "type": "str"},
        "password": {"required": False, "type": "str", "default": "", "no_log": True},
        "vdom": {"required": False, "type": "str", "default": "root"},
        "https": {"required": False, "type": "bool", "default": True},
        "ssl_verify": {"required": False, "type": "bool", "default": True},
        "state": {"required": True, "type": "str",
                  "choices": ["present", "absent"]},
        "system_wccp": {
            "required": False, "type": "dict", "default": None,
            "options": {
                "assignment_bucket_format": {"required": False, "type": "str",
                                             "choices": ["wccp-v2", "cisco-implementation"]},
                "assignment_dstaddr_mask": {"required": False, "type": "str"},
                "assignment_method": {"required": False, "type": "str",
                                      "choices": ["HASH", "MASK", "any"]},
                "assignment_srcaddr_mask": {"required": False, "type": "str"},
                "assignment_weight": {"required": False, "type": "int"},
                "authentication": {"required": False, "type": "str",
                                   "choices": ["enable", "disable"]},
                "cache_engine_method": {"required": False, "type": "str",
                                        "choices": ["GRE", "L2"]},
                "cache_id": {"required": False, "type": "str"},
                "forward_method": {"required": False, "type": "str",
                                   "choices": ["GRE", "L2", "any"]},
                "group_address": {"required": False, "type": "str"},
                "password": {"required": False, "type": "str"},
                "ports": {"required": False, "type": "str"},
                "ports_defined": {"required": False, "type": "str",
                                  "choices": ["source", "destination"]},
                "primary_hash": {"required": False, "type": "str",
                                 "choices": ["src-ip", "dst-ip", "src-port",
                                             "dst-port"]},
                "priority": {"required": False, "type": "int"},
                "protocol": {"required": False, "type": "int"},
                "return_method": {"required": False, "type": "str",
                                  "choices": ["GRE", "L2", "any"]},
                "router_id": {"required": False, "type": "str"},
                "router_list": {"required": False, "type": "str"},
                "server_list": {"required": False, "type": "str"},
                "server_type": {"required": False, "type": "str",
                                "choices": ["forward", "proxy"]},
                "service_id": {"required": False, "type": "str"},
                "service_type": {"required": False, "type": "str",
                                 "choices": ["auto", "standard", "dynamic"]}

            }
        }
    }

    module = AnsibleModule(argument_spec=fields,
                           supports_check_mode=False)

    # legacy_mode refers to using fortiosapi instead of HTTPAPI
    legacy_mode = 'host' in module.params and module.params['host'] is not None and \
                  'username' in module.params and module.params['username'] is not None and \
                  'password' in module.params and module.params['password'] is not None

    if not legacy_mode:
        if module._socket_path:
            connection = Connection(module._socket_path)
            fos = FortiOSHandler(connection)

            is_error, has_changed, result = fortios_system(module.params, fos)
        else:
            module.fail_json(**FAIL_SOCKET_MSG)
    else:
        try:
            from fortiosapi import FortiOSAPI
        except ImportError:
            module.fail_json(msg="fortiosapi module is required")

        fos = FortiOSAPI()

        login(module.params, fos)
        is_error, has_changed, result = fortios_system(module.params, fos)
        fos.logout()

    if not is_error:
        module.exit_json(changed=has_changed, meta=result)
    else:
        module.fail_json(msg="Error in repo", meta=result)
def main():
    fields = {
        "host": {
            "required": False,
            "type": "str"
        },
        "username": {
            "required": False,
            "type": "str"
        },
        "password": {
            "required": False,
            "type": "str",
            "default": "",
            "no_log": True
        },
        "vdom": {
            "required": False,
            "type": "str",
            "default": "root"
        },
        "https": {
            "required": False,
            "type": "bool",
            "default": True
        },
        "ssl_verify": {
            "required": False,
            "type": "bool",
            "default": True
        },
        "log_fortianalyzer_override_setting": {
            "required": False,
            "type": "dict",
            "default": None,
            "options": {
                "__change_ip": {
                    "required": False,
                    "type": "int"
                },
                "certificate": {
                    "required": False,
                    "type": "str"
                },
                "conn_timeout": {
                    "required": False,
                    "type": "int"
                },
                "enc_algorithm": {
                    "required": False,
                    "type": "str",
                    "choices": ["high-medium", "high", "low"]
                },
                "faz_type": {
                    "required": False,
                    "type": "int"
                },
                "hmac_algorithm": {
                    "required": False,
                    "type": "str",
                    "choices": ["sha256", "sha1"]
                },
                "ips_archive": {
                    "required": False,
                    "type": "str",
                    "choices": ["enable", "disable"]
                },
                "mgmt_name": {
                    "required": False,
                    "type": "str"
                },
                "monitor_failure_retry_period": {
                    "required": False,
                    "type": "int"
                },
                "monitor_keepalive_period": {
                    "required": False,
                    "type": "int"
                },
                "override": {
                    "required": False,
                    "type": "str",
                    "choices": ["enable", "disable"]
                },
                "reliable": {
                    "required": False,
                    "type": "str",
                    "choices": ["enable", "disable"]
                },
                "server": {
                    "required": False,
                    "type": "str"
                },
                "source_ip": {
                    "required": False,
                    "type": "str"
                },
                "ssl_min_proto_version": {
                    "required": False,
                    "type": "str",
                    "choices":
                    ["default", "SSLv3", "TLSv1", "TLSv1-1", "TLSv1-2"]
                },
                "status": {
                    "required": False,
                    "type": "str",
                    "choices": ["enable", "disable"]
                },
                "upload_day": {
                    "required": False,
                    "type": "str"
                },
                "upload_interval": {
                    "required": False,
                    "type": "str",
                    "choices": ["daily", "weekly", "monthly"]
                },
                "upload_option": {
                    "required":
                    False,
                    "type":
                    "str",
                    "choices":
                    ["store-and-upload", "realtime", "1-minute", "5-minute"]
                },
                "upload_time": {
                    "required": False,
                    "type": "str"
                },
                "use_management_vdom": {
                    "required": False,
                    "type": "str",
                    "choices": ["enable", "disable"]
                }
            }
        }
    }

    module = AnsibleModule(argument_spec=fields, supports_check_mode=False)

    # legacy_mode refers to using fortiosapi instead of HTTPAPI
    legacy_mode = 'host' in module.params and module.params['host'] is not None and \
                  'username' in module.params and module.params['username'] is not None and \
                  'password' in module.params and module.params['password'] is not None

    if not legacy_mode:
        if module._socket_path:
            connection = Connection(module._socket_path)
            fos = FortiOSHandler(connection)

            is_error, has_changed, result = fortios_log_fortianalyzer(
                module.params, fos)
        else:
            module.fail_json(**FAIL_SOCKET_MSG)
    else:
        try:
            from fortiosapi import FortiOSAPI
        except ImportError:
            module.fail_json(msg="fortiosapi module is required")

        fos = FortiOSAPI()

        login(module.params, fos)
        is_error, has_changed, result = fortios_log_fortianalyzer(
            module.params, fos)
        fos.logout()

    if not is_error:
        module.exit_json(changed=has_changed, meta=result)
    else:
        module.fail_json(msg="Error in repo", meta=result)
示例#18
0
def main():
    """ This section is for arguments parsing """

    state_map = dict(present='role-create',
                     absent='role-delete',
                     update='role-modify')

    module = AnsibleModule(
        argument_spec=dict(
            pn_cliswitch=dict(required=False, type='str'),
            state=dict(required=True, type='str', choices=state_map.keys()),
            pn_scope=dict(required=False,
                          type='str',
                          choices=['local', 'fabric']),
            pn_access=dict(required=False,
                           type='str',
                           choices=['read-only', 'read-write']),
            pn_shell=dict(required=False, type='bool'),
            pn_sudo=dict(required=False, type='bool'),
            pn_running_config=dict(required=False, type='bool'),
            pn_name=dict(required=False, type='str'),
            pn_delete_from_users=dict(required=False, type='bool'),
        ),
        required_if=(
            ["state", "present", ["pn_name", "pn_scope"]],
            ["state", "absent", ["pn_name"]],
            ["state", "update", ["pn_name"]],
        ),
    )

    # Accessing the arguments
    cliswitch = module.params['pn_cliswitch']
    state = module.params['state']
    scope = module.params['pn_scope']
    access = module.params['pn_access']
    shell = module.params['pn_shell']
    sudo = module.params['pn_sudo']
    running_config = module.params['pn_running_config']
    name = module.params['pn_name']
    delete_from_users = module.params['pn_delete_from_users']

    command = state_map[state]

    # Building the CLI command string
    cli = pn_cli(module, cliswitch)

    ROLE_EXISTS = check_cli(module, cli)
    cli += ' %s name %s ' % (command, name)

    if shell is (False or '') and sudo is True:
        module.fail_json(failed=True, msg='sudo access requires shell access')

    if command == 'role-modify':
        if ROLE_EXISTS is False:
            module.fail_json(failed=True,
                             msg='Role with name %s does not exist' % name)

    if command == 'role-delete':
        if ROLE_EXISTS is False:
            module.exit_json(skipped=True,
                             msg='Role with name %s does not exist' % name)

    if command == 'role-create':
        if ROLE_EXISTS is True:
            module.exit_json(skipped=True,
                             msg='Role with name %s already exists' % name)

        if scope:
            cli += ' scope ' + scope

    if command != 'role-delete':
        if access:
            cli += ' access ' + access

        cli += booleanArgs(shell, 'shell', 'no-shell')
        cli += booleanArgs(sudo, 'sudo', 'no-sudo')
        cli += booleanArgs(running_config, 'running-config',
                           'no-running-config')

    if command == 'role-modify':
        if delete_from_users:
            cli += ' delete-from-users ' + delete_from_users

    run_cli(module, cli, state_map)
示例#19
0
def main():
    # The following example playbooks:
    #
    # - cronvar: name="SHELL" value="/bin/bash"
    #
    # - name: Set the email
    #   cronvar: name="EMAILTO" value="*****@*****.**"
    #
    # - name: Get rid of the old new host variable
    #   cronvar: name="NEW_HOST" state=absent
    #
    # Would produce:
    # SHELL = /bin/bash
    # EMAILTO = [email protected]

    module = AnsibleModule(
        argument_spec=dict(
            name=dict(type='str', required=True),
            value=dict(type='str'),
            user=dict(type='str'),
            cron_file=dict(type='str'),
            insertafter=dict(type='str'),
            insertbefore=dict(type='str'),
            state=dict(type='str',
                       default='present',
                       choices=['absent', 'present']),
            backup=dict(type='bool', default=False),
        ),
        mutually_exclusive=[['insertbefore', 'insertafter']],
        supports_check_mode=False,
    )

    name = module.params['name']
    value = module.params['value']
    user = module.params['user']
    cron_file = module.params['cron_file']
    insertafter = module.params['insertafter']
    insertbefore = module.params['insertbefore']
    state = module.params['state']
    backup = module.params['backup']
    ensure_present = state == 'present'

    changed = False
    res_args = dict()

    # Ensure all files generated are only writable by the owning user.  Primarily relevant for the cron_file option.
    os.umask(int('022', 8))
    cronvar = CronVar(module, user, cron_file)

    module.debug('cronvar instantiated - name: "%s"' % name)

    # --- user input validation ---

    if name is None and ensure_present:
        module.fail_json(
            msg="You must specify 'name' to insert a new cron variable")

    if value is None and ensure_present:
        module.fail_json(
            msg="You must specify 'value' to insert a new cron variable")

    if name is None and not ensure_present:
        module.fail_json(
            msg="You must specify 'name' to remove a cron variable")

    # if requested make a backup before making a change
    if backup:
        (_, backup_file) = tempfile.mkstemp(prefix='cronvar')
        cronvar.write(backup_file)

    if cronvar.cron_file and not name and not ensure_present:
        changed = cronvar.remove_job_file()
        module.exit_json(changed=changed, cron_file=cron_file, state=state)

    old_value = cronvar.find_variable(name)

    if ensure_present:
        if old_value is None:
            cronvar.add_variable(name, value, insertbefore, insertafter)
            changed = True
        elif old_value != value:
            cronvar.update_variable(name, value)
            changed = True
    else:
        if old_value is not None:
            cronvar.remove_variable(name)
            changed = True

    res_args = {"vars": cronvar.get_var_names(), "changed": changed}

    if changed:
        cronvar.write()

    # retain the backup only if crontab or cron file have changed
    if backup:
        if changed:
            res_args['backup_file'] = backup_file
        else:
            os.unlink(backup_file)

    if cron_file:
        res_args['cron_file'] = cron_file

    module.exit_json(**res_args)
示例#20
0
def main():
    """main entry point for module execution
    """
    argument_spec = dict(
        # { command: <str>, prompt: <str>, response: <str> }
        commands=dict(type='list', required=True),

        wait_for=dict(type='list'),
        match=dict(default='all', choices=['all', 'any']),

        retries=dict(default=10, type='int'),
        interval=dict(default=1, type='int')
    )

    argument_spec.update(dellos6_argument_spec)
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True)

    result = {'changed': False}

    warnings = list()
    check_args(module, warnings)
    commands = parse_commands(module, warnings)
    result['warnings'] = warnings

    wait_for = module.params['wait_for'] or list()

    try:
        conditionals = [Conditional(c) for c in wait_for]
    except AttributeError as exc:
        module.fail_json(msg=to_text(exc))
    retries = module.params['retries']
    interval = module.params['interval']
    match = module.params['match']

    while retries > 0:
        responses = run_commands(module, commands)

        for item in list(conditionals):
            if item(responses):
                if match == 'any':
                    conditionals = list()
                    break
                conditionals.remove(item)

        if not conditionals:
            break

        time.sleep(interval)
        retries -= 1

    if conditionals:
        failed_conditions = [item.raw for item in conditionals]
        msg = 'One or more conditional statements have not been satisfied'
        module.fail_json(msg=msg, failed_conditions=failed_conditions)

    result.update({
        'stdout': responses,
        'stdout_lines': list(to_lines(responses))
    })

    module.exit_json(**result)
示例#21
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(type='str', default='present', choices=['absent', 'present']),
        cluster=dict(type='str', required=True),
        name=dict(type='str', required=True),
        description=dict(type='str'),
        vm_enforcing=dict(type='bool'),
        vm_rule=dict(type='str', choices=['disabled', 'negative', 'positive']),
        host_enforcing=dict(type='bool'),
        host_rule=dict(type='str', choices=['disabled', 'negative', 'positive']),
        vms=dict(type='list'),
        hosts=dict(type='list'),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )

    check_sdk(module)
    try:
        auth = module.params.pop('auth')
        connection = create_connection(auth)
        # Check if unsupported parameters were passed:
        supported_41 = ('host_enforcing', 'host_rule', 'hosts')
        if not check_support(
            version='4.1',
            connection=connection,
            module=module,
            params=supported_41,
        ):
            module.fail_json(
                msg='Following parameters are supported since 4.1: {params}'.format(
                    params=supported_41,
                )
            )
        clusters_service = connection.system_service().clusters_service()
        vms_service = connection.system_service().vms_service()
        hosts_service = connection.system_service().hosts_service()
        cluster_name = module.params['cluster']
        cluster = search_by_name(clusters_service, cluster_name)
        if cluster is None:
            raise Exception("Cluster '%s' was not found." % cluster_name)
        cluster_service = clusters_service.cluster_service(cluster.id)
        affinity_groups_service = cluster_service.affinity_groups_service()

        # Fetch VM ids which should be assigned to affinity group:
        vm_ids = sorted([
            get_id_by_name(vms_service, vm_name)
            for vm_name in module.params['vms']
        ]) if module.params['vms'] is not None else None
        # Fetch host ids which should be assigned to affinity group:
        host_ids = sorted([
            get_id_by_name(hosts_service, host_name)
            for host_name in module.params['hosts']
        ]) if module.params['hosts'] is not None else None

        affinity_groups_module = AffinityGroupsModule(
            connection=connection,
            module=module,
            service=affinity_groups_service,
            vm_ids=vm_ids,
            host_ids=host_ids,
        )

        state = module.params['state']
        if state == 'present':
            ret = affinity_groups_module.create()
        elif state == 'absent':
            ret = affinity_groups_module.remove()

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=auth.get('token') is None)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            name=dict(required=True, type='str'),
            type=dict(default='ipv4',
                      type='str',
                      aliases=['tunnel_type'],
                      choices=SUPPORTED_TYPES),
            local_address=dict(type='str', aliases=['local']),
            remote_address=dict(type='str', aliases=['remote']),
            temporary=dict(default=False, type='bool'),
            state=dict(default='present', choices=['absent', 'present']),
        ),
        required_if=[
            ['state', 'present', ['local_address', 'remote_address']],
        ],
        supports_check_mode=True)

    iptun = IPTun(module)

    rc = None
    out = ''
    err = ''
    result = {}
    result['name'] = iptun.name
    result['type'] = iptun.type
    result['local_address'] = iptun.local_address
    result['remote_address'] = iptun.remote_address
    result['state'] = iptun.state
    result['temporary'] = iptun.temporary

    if iptun.state == 'absent':
        if iptun.iptun_exists():
            if module.check_mode:
                module.exit_json(changed=True)
            (rc, out, err) = iptun.delete_iptun()
            if rc != 0:
                module.fail_json(name=iptun.name, msg=err, rc=rc)
    elif iptun.state == 'present':
        if not iptun.iptun_exists():
            if module.check_mode:
                module.exit_json(changed=True)
            (rc, out, err) = iptun.create_iptun()

            if rc is not None and rc != 0:
                module.fail_json(name=iptun.name, msg=err, rc=rc)
        else:
            if iptun.iptun_needs_updating():
                (rc, out, err) = iptun.update_iptun()
                if rc != 0:
                    module.fail_json(
                        msg='Error while updating tunnel interface: "%s"' %
                        err,
                        name=iptun.name,
                        stderr=err,
                        rc=rc)

    if rc is None:
        result['changed'] = False
    else:
        result['changed'] = True

    if out:
        result['stdout'] = out
    if err:
        result['stderr'] = err

    module.exit_json(**result)
示例#23
0
def main():
    fields = {
        "host": {
            "required": False,
            "type": "str"
        },
        "username": {
            "required": False,
            "type": "str"
        },
        "password": {
            "required": False,
            "type": "str",
            "default": "",
            "no_log": True
        },
        "vdom": {
            "required": False,
            "type": "str",
            "default": "root"
        },
        "https": {
            "required": False,
            "type": "bool",
            "default": True
        },
        "ssl_verify": {
            "required": False,
            "type": "bool",
            "default": True
        },
        "state": {
            "required": False,
            "type": "str",
            "choices": ["present", "absent"]
        },
        "router_access_list": {
            "required": False,
            "type": "dict",
            "default": None,
            "options": {
                "state": {
                    "required": False,
                    "type": "str",
                    "choices": ["present", "absent"]
                },
                "comments": {
                    "required": False,
                    "type": "str"
                },
                "name": {
                    "required": True,
                    "type": "str"
                },
                "rule": {
                    "required": False,
                    "type": "list",
                    "options": {
                        "action": {
                            "required": False,
                            "type": "str",
                            "choices": ["permit", "deny"]
                        },
                        "exact_match": {
                            "required": False,
                            "type": "str",
                            "choices": ["enable", "disable"]
                        },
                        "flags": {
                            "required": False,
                            "type": "int"
                        },
                        "id": {
                            "required": True,
                            "type": "int"
                        },
                        "prefix": {
                            "required": False,
                            "type": "str"
                        },
                        "wildcard": {
                            "required": False,
                            "type": "str"
                        }
                    }
                }
            }
        }
    }

    module = AnsibleModule(argument_spec=fields, supports_check_mode=False)

    # legacy_mode refers to using fortiosapi instead of HTTPAPI
    legacy_mode = 'host' in module.params and module.params['host'] is not None and \
                  'username' in module.params and module.params['username'] is not None and \
                  'password' in module.params and module.params['password'] is not None

    if not legacy_mode:
        if module._socket_path:
            connection = Connection(module._socket_path)
            fos = FortiOSHandler(connection)

            is_error, has_changed, result = fortios_router(module.params, fos)
        else:
            module.fail_json(**FAIL_SOCKET_MSG)
    else:
        try:
            from fortiosapi import FortiOSAPI
        except ImportError:
            module.fail_json(msg="fortiosapi module is required")

        fos = FortiOSAPI()

        login(module.params, fos)
        is_error, has_changed, result = fortios_router(module.params, fos)
        fos.logout()

    if not is_error:
        module.exit_json(changed=has_changed, meta=result)
    else:
        module.fail_json(msg="Error in repo", meta=result)
示例#24
0
def main():

    module_specific_arguments = dict(
        policyname=dict(type='str'),
        url=dict(type='str'),
        rule=dict(type='str'),
        domain=dict(type='str'),
        action=dict(type='str'),
    )

    hand_inserted_arguments = dict()

    argument_spec = dict()

    argument_spec.update(netscaler_common_arguments)
    argument_spec.update(module_specific_arguments)
    argument_spec.update(hand_inserted_arguments)

    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    module_result = dict(
        changed=False,
        failed=False,
        loglines=loglines,
    )

    # Fail the module if imports failed
    if not PYTHON_SDK_IMPORTED:
        module.fail_json(msg='Could not load nitro python sdk')

    # Fallthrough to rest of execution
    client = get_nitro_client(module)

    try:
        client.login()
    except nitro_exception as e:
        msg = "nitro exception during login. errorcode=%s, message=%s" % (str(
            e.errorcode), e.message)
        module.fail_json(msg=msg)
    except Exception as e:
        if str(type(e)) == "<class 'requests.exceptions.ConnectionError'>":
            module.fail_json(msg='Connection error %s' % str(e))
        elif str(type(e)) == "<class 'requests.exceptions.SSLError'>":
            module.fail_json(msg='SSL Error %s' % str(e))
        else:
            module.fail_json(msg='Unexpected error during login %s' % str(e))

    readwrite_attrs = [
        'policyname',
        'url',
        'rule',
        'domain',
        'action',
    ]
    readonly_attrs = [
        'vstype',
        'hits',
        'bindhits',
        'labelname',
        'labeltype',
        'priority',
        'activepolicy',
        'cspolicytype',
    ]

    transforms = {}

    # Instantiate config proxy
    cspolicy_proxy = ConfigProxy(
        actual=cspolicy(),
        client=client,
        attribute_values_dict=module.params,
        readwrite_attrs=readwrite_attrs,
        readonly_attrs=readonly_attrs,
        transforms=transforms,
    )

    try:
        ensure_feature_is_enabled(client, 'CS')

        # Apply appropriate state
        if module.params['state'] == 'present':
            log('Sanity checks for state present')
            if not policy_exists(client, module):
                if not module.check_mode:
                    cspolicy_proxy.add()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            elif not policy_identical(client, module, cspolicy_proxy):
                if not module.check_mode:
                    cspolicy_proxy.update()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            else:
                module_result['changed'] = False

            # Sanity check for state
            if not module.check_mode:
                log('Sanity checks for state present')
                if not policy_exists(client, module):
                    module.fail_json(msg='Policy does not exist',
                                     **module_result)
                if not policy_identical(client, module, cspolicy_proxy):
                    module.fail_json(msg='Policy differs from configured',
                                     diff=diff_list(client, module,
                                                    cspolicy_proxy),
                                     **module_result)

        elif module.params['state'] == 'absent':
            log('Applying actions for state absent')
            if policy_exists(client, module):
                if not module.check_mode:
                    cspolicy_proxy.delete()
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            else:
                module_result['changed'] = False

            # Sanity check for state
            if not module.check_mode:
                log('Sanity checks for state absent')
                if policy_exists(client, module):
                    module.fail_json(msg='Policy still exists',
                                     **module_result)

    except nitro_exception as e:
        msg = "nitro exception errorcode=%s, message=%s" % (str(
            e.errorcode), e.message)
        module.fail_json(msg=msg, **module_result)

    client.logout()
    module.exit_json(**module_result)
示例#25
0
def main():
    """entry point for module execution
    """
    argument_spec = dict(
        source=dict(choices=['running', 'candidate', 'startup']),
        filter=dict(),
        display=dict(choices=['json', 'pretty', 'xml']),
        lock=dict(default='never', choices=['never', 'always',
                                            'if-supported']))

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

    capabilities = get_capabilities(module)
    operations = capabilities['device_operations']

    source = module.params['source']
    filter = module.params['filter']
    filter_type = get_filter_type(filter)
    lock = module.params['lock']
    display = module.params['display']

    if source == 'candidate' and not operations.get('supports_commit', False):
        module.fail_json(
            msg='candidate source is not supported on this device')

    if source == 'startup' and not operations.get('supports_startup', False):
        module.fail_json(msg='startup source is not supported on this device')

    if filter_type == 'xpath' and not operations.get('supports_xpath', False):
        module.fail_json(
            msg=
            "filter value '%s' of type xpath is not supported on this device" %
            filter)

    # If source is None, NETCONF <get> operation is issued, reading config/state data
    # from the running datastore. The python expression "(source or 'running')" results
    # in the value of source (if not None) or the value 'running' (if source is None).

    if lock == 'never':
        execute_lock = False
    elif (source or 'running') in operations.get('lock_datastore', []):
        # lock is requested (always/if-support) and supported => lets do it
        execute_lock = True
    else:
        # lock is requested (always/if-supported) but not supported => issue warning
        module.warn(
            "lock operation on '%s' source is not supported on this device" %
            (source or 'running'))
        execute_lock = (lock == 'always')

    if display == 'json' and not HAS_JXMLEASE:
        module.fail_json(
            msg='jxmlease is required to display response in json format'
            'but does not appear to be installed. '
            'It can be installed using `pip install jxmlease`')

    filter_spec = (filter_type, filter) if filter_type else None

    if source is not None:
        response = get_config(module, source, filter_spec, execute_lock)
    else:
        response = get(module, filter_spec, execute_lock)

    xml_resp = to_text(tostring(response))
    output = None

    if display == 'xml':
        output = remove_namespaces(xml_resp)
    elif display == 'json':
        try:
            output = jxmlease.parse(xml_resp)
        except Exception:
            raise ValueError(xml_resp)
    elif display == 'pretty':
        output = to_text(tostring(response, pretty_print=True))

    result = {'stdout': xml_resp, 'output': output}

    module.exit_json(**result)
示例#26
0
def main():
    """ main entry point for module execution
    """
    neighbors_spec = dict(host=dict(), port=dict())

    element_spec = dict(name=dict(),
                        description=dict(),
                        speed=dict(),
                        mtu=dict(),
                        enabled=dict(default=True, type='bool'),
                        tx_rate=dict(),
                        rx_rate=dict(),
                        neighbors=dict(type='list',
                                       elements='dict',
                                       options=neighbors_spec),
                        delay=dict(default=10, type='int'),
                        state=dict(default='present',
                                   choices=['present', 'absent', 'up',
                                            'down']))

    aggregate_spec = deepcopy(element_spec)
    aggregate_spec['name'] = dict(required=True)

    # remove default in aggregate spec, to handle common arguments
    remove_default_spec(aggregate_spec)

    argument_spec = dict(aggregate=dict(type='list',
                                        elements='dict',
                                        options=aggregate_spec), )

    argument_spec.update(element_spec)
    argument_spec.update(eos_argument_spec)

    required_one_of = [['name', 'aggregate']]
    mutually_exclusive = [['name', 'aggregate']]

    module = AnsibleModule(argument_spec=argument_spec,
                           required_one_of=required_one_of,
                           mutually_exclusive=mutually_exclusive,
                           supports_check_mode=True)

    warnings = list()
    result = {'changed': False}
    if warnings:
        result['warnings'] = warnings

    want = map_params_to_obj(module)
    have = map_config_to_obj(module)
    commands = map_obj_to_commands((want, have), module)
    result['commands'] = commands

    if commands:
        commit = not module.check_mode
        response = load_config(module, commands, commit=commit)
        if response.get('diff') and module._diff:
            result['diff'] = {'prepared': response.get('diff')}
        result['session_name'] = response.get('session')
        result['changed'] = True

    failed_conditions = check_declarative_intent_params(module, want, result)

    if failed_conditions:
        msg = 'One or more conditional statements have not been satisfied'
        module.fail_json(msg=msg, failed_conditions=failed_conditions)

    module.exit_json(**result)
示例#27
0
def main():
    fields = {
        "host": {"required": False, "type": "str"},
        "username": {"required": False, "type": "str"},
        "password": {"required": False, "type": "str", "default": "", "no_log": True},
        "vdom": {"required": False, "type": "str", "default": "root"},
        "https": {"required": False, "type": "bool", "default": True},
        "ssl_verify": {"required": False, "type": "bool", "default": True},
        "state": {"required": True, "type": "str",
                  "choices": ["present", "absent"]},
        "vpn_certificate_local": {
            "required": False, "type": "dict", "default": None,
            "options": {
                "auto_regenerate_days": {"required": False, "type": "int"},
                "auto_regenerate_days_warning": {"required": False, "type": "int"},
                "ca_identifier": {"required": False, "type": "str"},
                "certificate": {"required": False, "type": "str"},
                "cmp_path": {"required": False, "type": "str"},
                "cmp_regeneration_method": {"required": False, "type": "str",
                                            "choices": ["keyupate", "renewal"]},
                "cmp_server": {"required": False, "type": "str"},
                "cmp_server_cert": {"required": False, "type": "str"},
                "comments": {"required": False, "type": "str"},
                "csr": {"required": False, "type": "str"},
                "enroll_protocol": {"required": False, "type": "str",
                                    "choices": ["none", "scep", "cmpv2"]},
                "ike_localid": {"required": False, "type": "str"},
                "ike_localid_type": {"required": False, "type": "str",
                                     "choices": ["asn1dn", "fqdn"]},
                "last_updated": {"required": False, "type": "int"},
                "name": {"required": True, "type": "str"},
                "name_encoding": {"required": False, "type": "str",
                                  "choices": ["printable", "utf8"]},
                "password": {"required": False, "type": "str"},
                "private_key": {"required": False, "type": "str"},
                "range": {"required": False, "type": "str",
                          "choices": ["global", "vdom"]},
                "scep_password": {"required": False, "type": "str"},
                "scep_url": {"required": False, "type": "str"},
                "source": {"required": False, "type": "str",
                           "choices": ["factory", "user", "bundle"]},
                "source_ip": {"required": False, "type": "str"},
                "state": {"required": False, "type": "str"}

            }
        }
    }

    module = AnsibleModule(argument_spec=fields,
                           supports_check_mode=False)

    # legacy_mode refers to using fortiosapi instead of HTTPAPI
    legacy_mode = 'host' in module.params and module.params['host'] is not None and \
                  'username' in module.params and module.params['username'] is not None and \
                  'password' in module.params and module.params['password'] is not None

    if not legacy_mode:
        if module._socket_path:
            connection = Connection(module._socket_path)
            fos = FortiOSHandler(connection)

            is_error, has_changed, result = fortios_vpn_certificate(module.params, fos)
        else:
            module.fail_json(**FAIL_SOCKET_MSG)
    else:
        try:
            from fortiosapi import FortiOSAPI
        except ImportError:
            module.fail_json(msg="fortiosapi module is required")

        fos = FortiOSAPI()

        login(module.params, fos)
        is_error, has_changed, result = fortios_vpn_certificate(module.params, fos)
        fos.logout()

    if not is_error:
        module.exit_json(changed=has_changed, meta=result)
    else:
        module.fail_json(msg="Error in repo", meta=result)
class ISIS_Instance(object):
    """Manages ISIS Instance"""
    def __init__(self, argument_spec):
        self.spec = argument_spec
        self.module = None
        self.__init_module__()

        # module input info
        self.instance_id = self.module.params['instance_id']
        self.vpn_name = self.module.params['vpn_name']
        self.state = self.module.params['state']

        # state
        self.changed = False
        self.isis_dict = dict()
        self.updates_cmd = list()
        self.commands = list()
        self.results = dict()
        self.proposed = dict()
        self.existing = dict()
        self.end_state = dict()

    def __init_module__(self):
        """init module"""
        self.module = AnsibleModule(argument_spec=self.spec,
                                    supports_check_mode=True)

    def get_isis_dict(self):
        """isis config dict"""
        isis_dict = dict()
        isis_dict["instance"] = dict()
        conf_str = CE_NC_GET_ISIS % (
            (CE_NC_GET_ISIS_INSTANCE % self.instance_id))

        xml_str = get_nc_config(self.module, conf_str)
        if "<data/>" in xml_str:
            return isis_dict

        xml_str = xml_str.replace('\r', '').replace('\n', '').\
            replace('xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"', "").\
            replace('xmlns="http://www.huawei.com/netconf/vrp"', "")
        root = ElementTree.fromstring(xml_str)

        # get isis info
        glb = root.find("isiscomm/isSites/isSite")
        if glb:
            for attr in glb:
                isis_dict["instance"][attr.tag] = attr.text

        return isis_dict

    def config_session(self):
        """configures isis"""
        xml_str = ""
        instance = self.isis_dict["instance"]
        if not self.instance_id:
            return xml_str

        if self.state == "present":
            xml_str = "<instanceId>%s</instanceId>" % self.instance_id
            self.updates_cmd.append("isis %s" % self.instance_id)

            if self.vpn_name:
                xml_str += "<vpnName>%s</vpnName>" % self.vpn_name
                self.updates_cmd.append("vpn-instance %s" % self.vpn_name)
        else:
            # absent
            if self.instance_id and str(
                    self.instance_id) == instance.get("instanceId"):
                xml_str = "<instanceId>%s</instanceId>" % self.instance_id
                self.updates_cmd.append("undo isis %s" % self.instance_id)

        if self.state == "present":
            return '<isSites><isSite operation="merge">' + xml_str + '</isSite></isSites>'
        else:
            if xml_str:
                return '<isSites><isSite operation="delete">' + xml_str + '</isSite></isSites>'

    def netconf_load_config(self, xml_str):
        """load isis config by netconf"""

        if not xml_str:
            return

        xml_cfg = """
            <config>
            <isiscomm xmlns="http://www.huawei.com/netconf/vrp" content-version="1.0" format-version="1.0">
            %s
            </isiscomm>
            </config>""" % xml_str
        set_nc_config(self.module, xml_cfg)
        self.changed = True

    def check_params(self):
        """Check all input params"""

        # check instance id
        if not self.instance_id:
            self.module.fail_json(
                msg="Error: Missing required arguments: instance_id.")

        if self.instance_id:
            if self.instance_id < 1 or self.instance_id > 4294967295:
                self.module.fail_json(
                    msg="Error: Instance id is not ranges from 1 to 4294967295."
                )

        # check vpn_name
        if self.vpn_name:
            if not is_valid_ip_vpn(self.vpn_name):
                self.module.fail_json(
                    msg="Error: Session vpn_name is invalid.")

    def get_proposed(self):
        """get proposed info"""
        # base config
        self.proposed["instance_id"] = self.instance_id
        self.proposed["vpn_name"] = self.vpn_name
        self.proposed["state"] = self.state

    def get_existing(self):
        """get existing info"""

        if not self.isis_dict:
            self.existing["instance"] = None

        self.existing["instance"] = self.isis_dict.get("instance")

    def get_end_state(self):
        """get end state info"""

        isis_dict = self.get_isis_dict()
        if not isis_dict:
            self.end_state["instance"] = None

        self.end_state["instance"] = isis_dict.get("instance")

        if self.end_state == self.existing:
            self.changed = False

    def work(self):
        """worker"""
        self.check_params()
        self.isis_dict = self.get_isis_dict()
        self.get_existing()
        self.get_proposed()

        # deal present or absent
        xml_str = ''
        if self.instance_id:
            cfg_str = self.config_session()
            if cfg_str:
                xml_str += cfg_str

        # update to device
        if xml_str:
            self.netconf_load_config(xml_str)
            self.changed = True

        self.get_end_state()
        self.results['changed'] = self.changed
        self.results['proposed'] = self.proposed
        self.results['existing'] = self.existing
        self.results['end_state'] = self.end_state
        if self.changed:
            self.results['updates'] = self.updates_cmd
        else:
            self.results['updates'] = list()

        self.module.exit_json(**self.results)
示例#29
0
def main():
    argument_spec = get_default_argspec()
    argument_spec.update(
        dict(
            terms_agreed=dict(type='bool', default=False),
            state=dict(type='str',
                       required=True,
                       choices=['absent', 'present', 'changed_key']),
            allow_creation=dict(type='bool', default=True),
            contact=dict(type='list', elements='str', default=[]),
            new_account_key_src=dict(type='path'),
            new_account_key_content=dict(type='str', no_log=True),
        ))
    module = AnsibleModule(
        argument_spec=argument_spec,
        required_one_of=(['account_key_src', 'account_key_content'], ),
        mutually_exclusive=(
            ['account_key_src', 'account_key_content'],
            ['new_account_key_src', 'new_account_key_content'],
        ),
        required_if=(
            # Make sure that for state == changed_key, one of
            # new_account_key_src and new_account_key_content are specified
            [
                'state', 'changed_key',
                ['new_account_key_src', 'new_account_key_content'], True
            ], ),
        supports_check_mode=True,
    )
    handle_standard_module_arguments(module, needs_acme_v2=True)

    try:
        account = ACMEAccount(module)
        changed = False
        state = module.params.get('state')
        diff_before = {}
        diff_after = {}
        if state == 'absent':
            created, account_data = account.setup_account(allow_creation=False)
            if account_data:
                diff_before = dict(account_data)
                diff_before['public_account_key'] = account.key_data['jwk']
            if created:
                raise AssertionError('Unwanted account creation')
            if account_data is not None:
                # Account is not yet deactivated
                if not module.check_mode:
                    # Deactivate it
                    payload = {'status': 'deactivated'}
                    result, info = account.send_signed_request(
                        account.uri, payload)
                    if info['status'] != 200:
                        raise ModuleFailException(
                            'Error deactivating account: {0} {1}'.format(
                                info['status'], result))
                changed = True
        elif state == 'present':
            allow_creation = module.params.get('allow_creation')
            # Make sure contact is a list of strings (unfortunately, Ansible doesn't do that for us)
            contact = [str(v) for v in module.params.get('contact')]
            terms_agreed = module.params.get('terms_agreed')
            created, account_data = account.setup_account(
                contact,
                terms_agreed=terms_agreed,
                allow_creation=allow_creation,
            )
            if account_data is None:
                raise ModuleFailException(
                    msg='Account does not exist or is deactivated.')
            if created:
                diff_before = {}
            else:
                diff_before = dict(account_data)
                diff_before['public_account_key'] = account.key_data['jwk']
            updated = False
            if not created:
                updated, account_data = account.update_account(
                    account_data, contact)
            changed = created or updated
            diff_after = dict(account_data)
            diff_after['public_account_key'] = account.key_data['jwk']
        elif state == 'changed_key':
            # Parse new account key
            error, new_key_data = account.parse_key(
                module.params.get('new_account_key_src'),
                module.params.get('new_account_key_content'))
            if error:
                raise ModuleFailException(
                    "error while parsing account key: %s" % error)
            # Verify that the account exists and has not been deactivated
            created, account_data = account.setup_account(allow_creation=False)
            if created:
                raise AssertionError('Unwanted account creation')
            if account_data is None:
                raise ModuleFailException(
                    msg='Account does not exist or is deactivated.')
            diff_before = dict(account_data)
            diff_before['public_account_key'] = account.key_data['jwk']
            # Now we can start the account key rollover
            if not module.check_mode:
                # Compose inner signed message
                # https://tools.ietf.org/html/rfc8555#section-7.3.5
                url = account.directory['keyChange']
                protected = {
                    "alg": new_key_data['alg'],
                    "jwk": new_key_data['jwk'],
                    "url": url,
                }
                payload = {
                    "account": account.uri,
                    "newKey":
                    new_key_data['jwk'],  # specified in draft 12 and older
                    "oldKey": account.jwk,  # specified in draft 13 and newer
                }
                data = account.sign_request(protected, payload, new_key_data)
                # Send request and verify result
                result, info = account.send_signed_request(url, data)
                if info['status'] != 200:
                    raise ModuleFailException(
                        'Error account key rollover: {0} {1}'.format(
                            info['status'], result))
                if module._diff:
                    account.key_data = new_key_data
                    account.jws_header['alg'] = new_key_data['alg']
                    diff_after = account.get_account_data()
            elif module._diff:
                # Kind of fake diff_after
                diff_after = dict(diff_before)
            diff_after['public_account_key'] = new_key_data['jwk']
            changed = True
        result = {
            'changed': changed,
            'account_uri': account.uri,
        }
        if module._diff:
            result['diff'] = {
                'before': diff_before,
                'after': diff_after,
            }
        module.exit_json(**result)
    except ModuleFailException as e:
        e.do_fail(module)
def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(name=dict(type='str'),
                         name_match=dict(type='str',
                                         choices=['first', 'last'],
                                         default='first'),
                         uuid=dict(type='str'),
                         use_instance_uuid=dict(type='bool', default=False),
                         moid=dict(type='str'),
                         folder=dict(type='str'),
                         datacenter=dict(type='str', required=True),
                         tags=dict(type='bool', default=False),
                         schema=dict(type='str',
                                     choices=['summary', 'vsphere'],
                                     default='summary'),
                         properties=dict(type='list'))
    module = AnsibleModule(argument_spec=argument_spec,
                           required_one_of=[['name', 'uuid', 'moid']],
                           supports_check_mode=True)
    if module._name == 'vmware_guest_facts':
        module.deprecate(
            "The 'vmware_guest_facts' module has been renamed to 'vmware_guest_info'",
            version='2.13')

    if module.params.get('folder'):
        # FindByInventoryPath() does not require an absolute path
        # so we should leave the input folder path unmodified
        module.params['folder'] = module.params['folder'].rstrip('/')

    if module.params['schema'] != 'vsphere' and module.params.get(
            'properties'):
        module.fail_json(
            msg=
            "The option 'properties' is only valid when the schema is 'vsphere'"
        )

    pyv = PyVmomi(module)
    # Check if the VM exists before continuing
    vm = pyv.get_vm()

    # VM already exists
    if vm:
        try:
            if module.params['schema'] == 'summary':
                instance = pyv.gather_facts(vm)
            else:
                instance = pyv.to_json(vm, module.params['properties'])
            if module.params.get('tags'):
                if not HAS_VSPHERE:
                    module.fail_json(
                        msg=
                        "Unable to find 'vCloud Suite SDK' Python library which is required."
                        " Please refer this URL for installation steps"
                        " - https://code.vmware.com/web/sdk/60/vcloudsuite-python"
                    )

                vm_rest_client = VmwareTag(module)
                instance.update(tags=vm_rest_client.get_vm_tags(
                    vm_rest_client.tag_service,
                    vm_rest_client.tag_association_svc,
                    vm_mid=vm._moId))
            module.exit_json(instance=instance)
        except Exception as exc:
            module.fail_json(
                msg="Information gathering failed with exception %s" %
                to_text(exc))
    else:
        vm_id = (module.params.get('uuid') or module.params.get('name')
                 or module.params.get('moid'))
        module.fail_json(
            msg="Unable to gather information for non-existing VM %s" % vm_id)