Beispiel #1
0
def main():
    argument_spec = infinibox_argument_spec()
    argument_spec.update(
        dict(name=dict(required=True),
             state=dict(default='present', choices=['present', 'absent']),
             filesystem=dict(required=True),
             client_list=dict(type='list')))

    module = AnsibleModule(argument_spec, supports_check_mode=True)

    if not HAS_INFINISDK:
        module.fail_json(msg=missing_required_lib('infinisdk'))
    if not HAS_MUNCH:
        module.fail_json(msg=missing_required_lib('munch'),
                         exception=MUNCH_IMP_ERR)

    state = module.params['state']
    system = get_system(module)
    filesystem = get_filesystem(module, system)
    export = get_export(module, filesystem, system)

    if filesystem is None:
        module.fail_json(
            msg='Filesystem {0} not found'.format(module.params['filesystem']))

    if state == 'present':
        update_export(module, export, filesystem, system)
    elif export and state == 'absent':
        delete_export(module, export)
    elif export is None and state == 'absent':
        module.exit_json(changed=False)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            ignore_selinux_state=dict(type='bool', default=False),
            name=dict(type='str', required=True),
            persistent=dict(type='bool', default=False),
            state=dict(type='bool', required=True),
        ),
        supports_check_mode=True,
    )

    if not HAVE_SELINUX:
        module.fail_json(msg=missing_required_lib('libselinux-python'),
                         exception=SELINUX_IMP_ERR)

    if not HAVE_SEMANAGE:
        module.fail_json(msg=missing_required_lib('libsemanage-python'),
                         exception=SEMANAGE_IMP_ERR)

    ignore_selinux_state = module.params['ignore_selinux_state']

    if not get_runtime_status(ignore_selinux_state):
        module.fail_json(msg="SELinux is disabled on this host.")

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

    result = dict(name=name, persistent=persistent, state=state)
    changed = False

    if hasattr(selinux, 'selinux_boolean_sub'):
        # selinux_boolean_sub allows sites to rename a boolean and alias the old name
        # Feature only available in selinux library since 2012.
        name = selinux.selinux_boolean_sub(name)

    if not has_boolean_value(module, name):
        module.fail_json(msg="SELinux boolean %s does not exist." % name)

    if persistent:
        changed = semanage_boolean_value(module, name, state)
    else:
        cur_value = get_boolean_value(module, name)
        if cur_value != state:
            changed = True
            if not module.check_mode:
                changed = set_boolean_value(module, name, state)
                if not changed:
                    module.fail_json(msg="Failed to set boolean %s to %s" %
                                     (name, state))
                try:
                    selinux.security_commit_booleans()
                except Exception:
                    module.fail_json(
                        msg="Failed to commit pending boolean %s value" % name)

    result['changed'] = changed

    module.exit_json(**result)
Beispiel #3
0
def main():
    argument_spec = vmware_argument_spec()
    argument_spec.update(cluster_name=dict(required=True, type='str'),
                         fetch_from_cache=dict(required=False, type='bool'))

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

    if not HAS_PYVMOMI:
        module.fail_json(msg=missing_required_lib('PyVmomi'),
                         exception=PYVMOMI_IMP_ERR)

    if not HAS_VSANPYTHONSDK:
        module.fail_json(
            msg=missing_required_lib('vSAN Management SDK for Python'),
            exception=VSANPYTHONSDK_IMP_ERR)

    if not HAS_PYVMOMIJSON:
        module.fail_json(
            msg=
            'The installed version of pyvmomi lacks JSON output support; need pyvmomi>6.7.1'
        )

    try:
        si, content = connect_to_api(module, True, True)
    except Exception as e:
        module.fail_json(msg=e.msg)

    client_stub = si._GetStub()
    ssl_context = client_stub.schemeArgs.get('context')

    cluster = find_cluster_by_name(content, module.params['cluster_name'])

    if not cluster:
        module.fail_json(msg="Failed to find cluster %s" %
                         module.params['cluster_name'])

    apiVersion = vsanapiutils.GetLatestVmodlVersion(module.params['hostname'])
    vcMos = vsanapiutils.GetVsanVcMos(client_stub,
                                      context=ssl_context,
                                      version=apiVersion)

    vsanClusterHealthSystem = vcMos['vsan-cluster-health-system']

    try:
        clusterHealth = vsanClusterHealthSystem.VsanQueryVcClusterHealthSummary(
            cluster=cluster, fetchFromCache=module.params['fetch_from_cache'])
    except vmodl.fault.NotFound as not_found:
        module.fail_json(msg=not_found.msg)
    except vmodl.fault.RuntimeFault as runtime_fault:
        module.fail_json(msg=runtime_fault.msg)

    health = json.dumps(clusterHealth,
                        cls=VmomiSupport.VmomiJSONEncoder,
                        sort_keys=True,
                        strip_dynamic=True)

    module.exit_json(changed=False, vsan_health_info=health)
    def __init__(self, *args, **kwargs):

        kwargs['argument_spec'] = self.argspec
        AnsibleModule.__init__(self, *args, **kwargs)

        if not HAS_K8S_MODULE_HELPER:
            self.fail_json(msg=missing_required_lib('openshift'), exception=K8S_IMP_ERR,
                           error=to_native(k8s_import_exception))
        self.openshift_version = openshift.__version__

        if not HAS_YAML:
            self.fail_json(msg=missing_required_lib("PyYAML"), exception=YAML_IMP_ERR)
def main():
    module = AnsibleModule(
        argument_spec=dict(
            ignore_selinux_state=dict(type='bool', default=False),
            ports=dict(type='list', required=True),
            proto=dict(type='str', required=True, choices=['tcp', 'udp']),
            setype=dict(type='str', required=True),
            state=dict(type='str',
                       default='present',
                       choices=['absent', 'present']),
            reload=dict(type='bool', default=True),
        ),
        supports_check_mode=True,
    )

    if not HAVE_SELINUX:
        module.fail_json(msg=missing_required_lib("libselinux-python"),
                         exception=SELINUX_IMP_ERR)

    if not HAVE_SEOBJECT:
        module.fail_json(msg=missing_required_lib("policycoreutils-python"),
                         exception=SEOBJECT_IMP_ERR)

    ignore_selinux_state = module.params['ignore_selinux_state']

    if not get_runtime_status(ignore_selinux_state):
        module.fail_json(msg="SELinux is disabled on this host.")

    ports = module.params['ports']
    proto = module.params['proto']
    setype = module.params['setype']
    state = module.params['state']
    do_reload = module.params['reload']

    result = {
        'ports': ports,
        'proto': proto,
        'setype': setype,
        'state': state,
    }

    if state == 'present':
        result['changed'] = semanage_port_add(module, ports, proto, setype,
                                              do_reload)
    elif state == 'absent':
        result['changed'] = semanage_port_del(module, ports, proto, setype,
                                              do_reload)
    else:
        module.fail_json(
            msg='Invalid value of argument "state": {0}'.format(state))

    module.exit_json(**result)
Beispiel #6
0
def main():
    module = AnsibleModule(
        argument_spec=dict(
            ignore_selinux_state=dict(type='bool', default=False),
            target=dict(type='str', required=True, aliases=['path']),
            ftype=dict(type='str',
                       default='a',
                       choices=option_to_file_type_str.keys()),
            setype=dict(type='str', required=True),
            seuser=dict(type='str'),
            selevel=dict(type='str', aliases=['serange']),
            state=dict(type='str',
                       default='present',
                       choices=['absent', 'present']),
            reload=dict(type='bool', default=True),
        ),
        supports_check_mode=True,
    )
    if not HAVE_SELINUX:
        module.fail_json(msg=missing_required_lib("libselinux-python"),
                         exception=SELINUX_IMP_ERR)

    if not HAVE_SEOBJECT:
        module.fail_json(msg=missing_required_lib("policycoreutils-python"),
                         exception=SEOBJECT_IMP_ERR)

    ignore_selinux_state = module.params['ignore_selinux_state']

    if not get_runtime_status(ignore_selinux_state):
        module.fail_json(msg="SELinux is disabled on this host.")

    target = module.params['target']
    ftype = module.params['ftype']
    setype = module.params['setype']
    seuser = module.params['seuser']
    serange = module.params['selevel']
    state = module.params['state']
    do_reload = module.params['reload']

    result = dict(target=target, ftype=ftype, setype=setype, state=state)

    if state == 'present':
        semanage_fcontext_modify(module, result, target, ftype, setype,
                                 do_reload, serange, seuser)
    elif state == 'absent':
        semanage_fcontext_delete(module, result, target, ftype, do_reload)
    else:
        module.fail_json(
            msg='Invalid value of argument "state": {0}'.format(state))
Beispiel #7
0
def main():
    argument_spec = infinibox_argument_spec()
    argument_spec.update(
        dict(name=dict(required=True),
             state=dict(default='present', choices=['present', 'absent']),
             wwns=dict(type='list'),
             volume=dict()))

    module = AnsibleModule(argument_spec, supports_check_mode=True)

    if not HAS_INFINISDK:
        module.fail_json(msg=missing_required_lib('infinisdk'))

    state = module.params['state']
    system = get_system(module)
    host = get_host(module, system)

    if module.params['volume']:
        try:
            system.volumes.get(name=module.params['volume'])
        except Exception:
            module.fail_json(
                msg='Volume {0} not found'.format(module.params['volume']))

    if host and state == 'present':
        update_host(module, host)
    elif host and state == 'absent':
        delete_host(module, host)
    elif host is None and state == 'absent':
        module.exit_json(changed=False)
    else:
        create_host(module, system)
Beispiel #8
0
def main():
    """Module entrypoint."""
    module = initialise_module()

    if not HAS_LINODE_DEPENDENCY:
        module.fail_json(msg=missing_required_lib('linode-api4'),
                         exception=LINODE_IMP_ERR)

    client = build_client(module)
    instance = maybe_instance_from_label(module, client)

    if module.params['state'] == 'present' and instance is not None:
        module.exit_json(changed=False, instance=instance._raw_json)

    elif module.params['state'] == 'present' and instance is None:
        instance_json = create_linode(
            module,
            client,
            authorized_keys=module.params['authorized_keys'],
            group=module.params['group'],
            image=module.params['image'],
            label=module.params['label'],
            region=module.params['region'],
            root_pass=module.params['root_pass'],
            tags=module.params['tags'],
            ltype=module.params['type'],
        )
        module.exit_json(changed=True, instance=instance_json)

    elif module.params['state'] == 'absent' and instance is not None:
        instance.delete()
        module.exit_json(changed=True, instance=instance._raw_json)

    elif module.params['state'] == 'absent' and instance is None:
        module.exit_json(changed=False, instance={})
def main():
    module = AnsibleModule(
        argument_spec=dict(
            api_key=dict(required=True, no_log=True),
            app_key=dict(required=True, no_log=True),
            title=dict(required=True),
            text=dict(required=True),
            date_happened=dict(required=False, default=None, type='int'),
            priority=dict(
                required=False, default='normal', choices=['normal', 'low']
            ),
            host=dict(required=False, default=None),
            tags=dict(required=False, default=None, type='list'),
            alert_type=dict(
                required=False, default='info',
                choices=['error', 'warning', 'info', 'success']
            ),
            aggregation_key=dict(required=False, default=None),
            validate_certs=dict(default='yes', type='bool'),
        )
    )

    # Prepare Datadog
    if not HAS_DATADOG:
        module.fail_json(msg=missing_required_lib('datadogpy'), exception=DATADOG_IMP_ERR)

    options = {
        'api_key': module.params['api_key'],
        'app_key': module.params['app_key']
    }

    initialize(**options)

    _post_event(module)
 def __init__(self, module):
     self.module = module
     self.ips = _convert_host_to_ip(module.params['host'])
     self.port = int(self.module.params['port'])
     self.exclude_ips = self._get_exclude_ips()
     if not HAS_PSUTIL:
         module.fail_json(msg=missing_required_lib('psutil'), exception=PSUTIL_IMP_ERR)
Beispiel #11
0
def main():
    # Setup the Ansible module
    module = AnsibleModule(argument_spec=dict(
        state=dict(default='present', choices=['present', 'absent', 'read']),
        key=dict(required=True, type='str'),
        value=dict(required=False, default=None, type='str'),
    ),
                           supports_check_mode=True)

    if not psutil_found:
        module.fail_json(msg=missing_required_lib("psutil"),
                         exception=PSUTIL_IMP_ERR)

    # If present state was specified, value must be provided.
    if module.params['state'] == 'present' and module.params['value'] is None:
        module.fail_json(msg='State "present" requires "value" to be set.')

    # Create wrapper instance.
    dconf = DconfPreference(module, module.check_mode)

    # Process based on different states.
    if module.params['state'] == 'read':
        value = dconf.read(module.params['key'])
        module.exit_json(changed=False, value=value)
    elif module.params['state'] == 'present':
        changed = dconf.write(module.params['key'], module.params['value'])
        module.exit_json(changed=changed)
    elif module.params['state'] == 'absent':
        changed = dconf.reset(module.params['key'])
        module.exit_json(changed=changed)
Beispiel #12
0
def main():
    argument_spec = cs_argument_spec()
    argument_spec.update(
        dict(
            name=dict(required=True),
            public_key=dict(),
            domain=dict(),
            account=dict(),
            project=dict(),
            state=dict(choices=['present', 'absent'], default='present'),
        ))

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

    if not HAS_LIB_SSHPUBKEYS:
        module.fail_json(msg=missing_required_lib("sshpubkeys"),
                         exception=SSHPUBKEYS_IMP_ERR)

    acs_sshkey = AnsibleCloudStackSshKey(module)
    state = module.params.get('state')
    if state in ['absent']:
        ssh_key = acs_sshkey.remove_ssh_key()
    else:
        public_key = module.params.get('public_key')
        if public_key:
            ssh_key = acs_sshkey.register_ssh_key(public_key)
        else:
            ssh_key = acs_sshkey.create_ssh_key()

    result = acs_sshkey.get_result(ssh_key)
    module.exit_json(**result)
    def _connect(self, check_vm_credentials=True):
        if not HAS_REQUESTS:
            raise AnsibleError(
                "%s : %s" %
                (missing_required_lib('requests'), REQUESTS_IMP_ERR))

        if not HAS_PYVMOMI:
            raise AnsibleError(
                "%s : %s" % (missing_required_lib('PyVmomi'), PYVMOMI_IMP_ERR))

        super(Connection, self)._connect()

        if not self.connected:
            self._establish_connection()
            self._establish_vm(check_vm_credentials=check_vm_credentials)
            self._connected = True
 def __init__(self, module, represent):
     self.module = module
     self.represent = represent
     self.result = {"changed": False, self.represent: None}
     if not HAS_HCLOUD:
         module.fail_json(msg=missing_required_lib("hcloud-python"))
     self._build_client()
Beispiel #15
0
    def check_required_library(self):
        """
        Check required libraries

        """
        if not HAS_REQUESTS:
            self.module.fail_json(msg=missing_required_lib('requests'),
                                  exception=REQUESTS_IMP_ERR)
        if not HAS_PYVMOMI:
            self.module.fail_json(msg=missing_required_lib('PyVmomi'),
                                  exception=PYVMOMI_IMP_ERR)
        if not HAS_VSPHERE:
            self.module.fail_json(
                msg=missing_required_lib('vSphere Automation SDK',
                                         url='https://code.vmware.com/web/sdk/65/vsphere-automation-python'),
                exception=VSPHERE_IMP_ERR)
Beispiel #16
0
    def __init__(self, module):
        """
        Construct module
        """
        self.module = module

        if not CLC_FOUND:
            self.module.fail_json(msg=missing_required_lib('clc-sdk'), exception=CLC_IMP_ERR)
        if not REQUESTS_FOUND:
            self.module.fail_json(msg=missing_required_lib('requests'), exception=REQUESTS_IMP_ERR)
        if requests.__version__ and LooseVersion(
                requests.__version__) < LooseVersion('2.5.0'):
            self.module.fail_json(
                msg='requests library  version should be >= 2.5.0')

        self._set_user_agent(self.clc)
Beispiel #17
0
def ECSClient(entrust_api_user=None,
              entrust_api_key=None,
              entrust_api_cert=None,
              entrust_api_cert_key=None,
              entrust_api_specification_path=None):
    """Create an ECS client"""

    if not YAML_FOUND:
        raise SessionConfigurationException(missing_required_lib("PyYAML"),
                                            exception=YAML_IMP_ERR)

    if entrust_api_specification_path is None:
        entrust_api_specification_path = "https://cloud.entrust.net/EntrustCloud/documentation/cms-api-2.1.0.yaml"

    # Not functionally necessary with current uses of this module_util, but better to be explicit for future use cases
    entrust_api_user = to_text(entrust_api_user)
    entrust_api_key = to_text(entrust_api_key)
    entrust_api_cert_key = to_text(entrust_api_cert_key)
    entrust_api_specification_path = to_text(entrust_api_specification_path)

    return ECSSession(
        "ecs",
        entrust_api_user=entrust_api_user,
        entrust_api_key=entrust_api_key,
        entrust_api_cert=entrust_api_cert,
        entrust_api_cert_key=entrust_api_cert_key,
        entrust_api_specification_path=entrust_api_specification_path,
    ).client()
    def __init__(self, module):
        if not HAS_LIB_CS:
            module.fail_json(msg=missing_required_lib('cs'), exception=CS_IMP_ERR)

        self.result = {
            'changed': False,
            'diff': {
                'before': dict(),
                'after': dict()
            }
        }

        # Common returns, will be merged with self.returns
        # search_for_key: replace_with_key
        self.common_returns = {
            'id': 'id',
            'name': 'name',
            'created': 'created',
            'zonename': 'zone',
            'state': 'state',
            'project': 'project',
            'account': 'account',
            'domain': 'domain',
            'displaytext': 'display_text',
            'displayname': 'display_name',
            'description': 'description',
        }

        # Init returns dict for use in subclasses
        self.returns = {}
        # these values will be casted to int
        self.returns_to_int = {}
        # these keys will be compared case sensitive in self.has_changed()
        self.case_sensitive_keys = [
            'id',
            'displaytext',
            'displayname',
            'description',
        ]

        self.module = module
        self._cs = None

        # Helper for VPCs
        self._vpc_networks_ids = None

        self.domain = None
        self.account = None
        self.project = None
        self.ip_address = None
        self.network = None
        self.physical_network = None
        self.vpc = None
        self.zone = None
        self.vm = None
        self.vm_default_nic = None
        self.os_type = None
        self.hypervisor = None
        self.capabilities = None
        self.network_acl = None
def main():
    global module
    module = AnsibleModule(
        argument_spec=dict(
            filter=dict(default=None, choices=[
                'cloudstack_service_offering',
                'cloudstack_availability_zone',
                'cloudstack_public_hostname',
                'cloudstack_public_ipv4',
                'cloudstack_local_hostname',
                'cloudstack_local_ipv4',
                'cloudstack_instance_id',
                'cloudstack_user_data',
            ]),
            meta_data_host=dict(),
        ),
        supports_check_mode=True
    )

    if not HAS_LIB_YAML:
        module.fail_json(msg=missing_required_lib("PyYAML"), exception=YAML_IMP_ERR)

    cs_facts = CloudStackFacts().run()
    cs_facts_result = dict(changed=False, ansible_facts=cs_facts)
    module.exit_json(**cs_facts_result)
def test_dependencies(module):
    if not python_jenkins_installed:
        module.fail_json(msg=missing_required_lib(
            "python-jenkins",
            url="https://python-jenkins.readthedocs.io/en/latest/install.html"
        ),
                         exception=JENKINS_IMP_ERR)
def set_crypto_backend(module):
    '''
    Sets which crypto backend to use (default: auto detection).

    Does not care whether a new enough cryptoraphy is available or not. Must
    be called before any real stuff is done which might evaluate
    ``HAS_CURRENT_CRYPTOGRAPHY``.
    '''
    global HAS_CURRENT_CRYPTOGRAPHY
    # Choose backend
    backend = module.params['select_crypto_backend']
    if backend == 'auto':
        pass
    elif backend == 'openssl':
        HAS_CURRENT_CRYPTOGRAPHY = False
    elif backend == 'cryptography':
        try:
            cryptography.__version__
        except Exception as dummy:
            module.fail_json(msg=missing_required_lib('cryptography'))
        HAS_CURRENT_CRYPTOGRAPHY = True
    else:
        module.fail_json(msg='Unknown crypto backend "{0}"!'.format(backend))
    # Inform about choices
    if HAS_CURRENT_CRYPTOGRAPHY:
        module.debug('Using cryptography backend (library version {0})'.format(
            CRYPTOGRAPHY_VERSION))
        return 'cryptography'
    else:
        module.debug('Using OpenSSL binary backend')
        return 'openssl'
Beispiel #22
0
 def __init__(self, module):
     self.module = module
     self.result = {}
     if not HAS_UCSMSDK:
         self.module.fail_json(msg=missing_required_lib('ucsmsdk'),
                               exception=UCSMSDK_IMP_ERR)
     self.login()
def main():

    module = AnsibleModule(argument_spec=dict(state=dict(
        required=True, choices=['running', 'paused', 'started', 'stopped']),
                                              checkid=dict(required=True),
                                              uid=dict(required=True),
                                              passwd=dict(required=True,
                                                          no_log=True),
                                              key=dict(required=True)))

    if not HAS_PINGDOM:
        module.fail_json(msg=missing_required_lib("pingdom"),
                         exception=PINGDOM_IMP_ERR)

    checkid = module.params['checkid']
    state = module.params['state']
    uid = module.params['uid']
    passwd = module.params['passwd']
    key = module.params['key']

    if (state == "paused" or state == "stopped"):
        (rc, name, result) = pause(checkid, uid, passwd, key)

    if (state == "running" or state == "started"):
        (rc, name, result) = unpause(checkid, uid, passwd, key)

    if rc != 0:
        module.fail_json(checkid=checkid, name=name, status=result)

    module.exit_json(checkid=checkid, name=name, status=result)
def main():
    argument_spec = infinibox_argument_spec()
    argument_spec.update(
        dict(name=dict(required=True),
             state=dict(default='present', choices=['present', 'absent']),
             size=dict(),
             vsize=dict(),
             ssd_cache=dict(type='bool', default=True)))

    module = AnsibleModule(argument_spec, supports_check_mode=True)

    if not HAS_INFINISDK:
        module.fail_json(msg=missing_required_lib('infinisdk'))
    if not HAS_CAPACITY:
        module.fail_json(msg=missing_required_lib('capacity'),
                         exception=CAPACITY_IMP_ERR)

    if module.params['size']:
        try:
            Capacity(module.params['size'])
        except Exception:
            module.fail_json(
                msg=
                'size (Physical Capacity) should be defined in MB, GB, TB or PB units'
            )

    if module.params['vsize']:
        try:
            Capacity(module.params['vsize'])
        except Exception:
            module.fail_json(
                msg=
                'vsize (Virtual Capacity) should be defined in MB, GB, TB or PB units'
            )

    state = module.params['state']
    system = get_system(module)
    pool = get_pool(module, system)

    if state == 'present' and not pool:
        create_pool(module, system)
    elif state == 'present' and pool:
        update_pool(module, system, pool)
    elif state == 'absent' and pool:
        delete_pool(module, pool)
    elif state == 'absent' and not pool:
        module.exit_json(changed=False)
Beispiel #25
0
def main():
    '''
    Main entry point for module execution
    '''
    argument_spec = dict(netbox_url=dict(type="str", required=True),
                         netbox_token=dict(type="str",
                                           required=True,
                                           no_log=True),
                         data=dict(type="dict", required=True),
                         state=dict(required=False,
                                    default='present',
                                    choices=['present', 'absent', 'new']),
                         validate_certs=dict(type="bool", default=True))

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

    # Fail module if pynetbox is not installed
    if not HAS_PYNETBOX:
        module.fail_json(msg=missing_required_lib('pynetbox'),
                         exception=PYNETBOX_IMP_ERR)

    # Assign variables to be used with module
    changed = False
    app = 'ipam'
    endpoint = 'ip_addresses'
    url = module.params["netbox_url"]
    token = module.params["netbox_token"]
    data = module.params["data"]
    state = module.params["state"]
    validate_certs = module.params["validate_certs"]

    # Attempt to create Netbox API object
    try:
        nb = pynetbox.api(url, token=token, ssl_verify=validate_certs)
    except Exception:
        module.fail_json(msg="Failed to establish connection to Netbox API")
    try:
        nb_app = getattr(nb, app)
    except AttributeError:
        module.fail_json(msg="Incorrect application specified: %s" % (app))

    nb_endpoint = getattr(nb_app, endpoint)
    norm_data = normalize_data(data)
    try:
        norm_data = _check_and_adapt_data(nb, norm_data)
        if state in ("new", "present"):
            return _handle_state_new_present(module, state, nb_app,
                                             nb_endpoint, norm_data)
        elif state == "absent":
            return module.exit_json(
                **ensure_ip_address_absent(nb_endpoint, norm_data))
        else:
            return module.fail_json(msg="Invalid state %s" % state)
    except pynetbox.RequestError as e:
        return module.fail_json(msg=json.loads(e.error))
    except ValueError as e:
        return module.fail_json(msg=str(e))
def check_requests_dep(module):
    """Check if an adequate requests version is available"""
    if not HAS_REQUESTS:
        module.fail_json(msg=missing_required_lib('requests'), exception=REQUESTS_IMP_ERR)
    else:
        required_version = '2.0.0' if PY3 else '1.0.0'
        if LooseVersion(requests.__version__) < LooseVersion(required_version):
            module.fail_json(msg="'requests' library version should be >= %s, found: %s." % (required_version, requests.__version__))
def main():
    module = AnsibleModule(
        argument_spec=gen_specs(
            attributes=dict(default={}, type='dict'),
            objectClass=dict(type='raw'),
            params=dict(type='dict'),
            state=dict(default='present', choices=['present', 'absent']),
        ),
        supports_check_mode=True,
    )

    if not HAS_LDAP:
        module.fail_json(msg=missing_required_lib('python-ldap'),
                         exception=LDAP_IMP_ERR)

    state = module.params['state']

    # Check if objectClass is present when needed
    if state == 'present' and module.params['objectClass'] is None:
        module.fail_json(msg="At least one objectClass must be provided.")

    # Check if objectClass is of the correct type
    if (module.params['objectClass'] is not None
            and not (isinstance(module.params['objectClass'], string_types)
                     or isinstance(module.params['objectClass'], list))):
        module.fail_json(msg="objectClass must be either a string or a list.")

    # Update module parameters with user's parameters if defined
    if 'params' in module.params and isinstance(module.params['params'], dict):
        for key, val in module.params['params'].items():
            if key in module.argument_spec:
                module.params[key] = val
            else:
                module.params['attributes'][key] = val

        # Remove the params
        module.params.pop('params', None)

    # Instantiate the LdapEntry object
    ldap = LdapEntry(module)

    # Get the action function
    if state == 'present':
        action = ldap.add()
    elif state == 'absent':
        action = ldap.delete()

    # Perform the action
    if action is not None and not module.check_mode:
        try:
            action()
        except Exception as e:
            module.fail_json(msg="Entry action failed.",
                             details=to_native(e),
                             exception=traceback.format_exc())

    module.exit_json(changed=(action is not None))
def main():
    module = AnsibleModule(argument_spec=dict(
        server_url=dict(type='str', required=True, aliases=['url']),
        login_user=dict(type='str', required=True),
        login_password=dict(type='str', required=True, no_log=True),
        http_login_user=dict(type='str', required=False, default=None),
        http_login_password=dict(type='str',
                                 required=False,
                                 default=None,
                                 no_log=True),
        validate_certs=dict(type='bool', required=False, default=True),
        timeout=dict(type='int', default=10),
        template_name=dict(type='str', required=True),
        format=dict(type='str', choices=['json', 'xml'], default='json')),
                           supports_check_mode=False)

    if not HAS_ZABBIX_API:
        module.fail_json(msg=missing_required_lib(
            'zabbix-api', url='https://pypi.org/project/zabbix-api/'),
                         exception=ZBX_IMP_ERR)

    server_url = module.params['server_url']
    login_user = module.params['login_user']
    login_password = module.params['login_password']
    http_login_user = module.params['http_login_user']
    http_login_password = module.params['http_login_password']
    validate_certs = module.params['validate_certs']
    timeout = module.params['timeout']
    template_name = module.params['template_name']
    format = module.params['format']

    try:
        zbx = ZabbixAPI(server_url,
                        timeout=timeout,
                        user=http_login_user,
                        passwd=http_login_password,
                        validate_certs=validate_certs)
        zbx.login(login_user, login_password)
        atexit.register(zbx.logout)
    except Exception as e:
        module.fail_json(msg="Failed to connect to Zabbix server: %s" % e)

    template_info = TemplateInfo(module, zbx)

    template_id = template_info.get_template_id(template_name)

    if not template_id:
        module.fail_json(msg='Template not found: %s' % template_name)

    if format == 'json':
        module.exit_json(changed=False,
                         template_json=template_info.dump_template(
                             template_id, template_type='json'))
    elif format == 'xml':
        module.exit_json(changed=False,
                         template_xml=template_info.dump_template(
                             template_id, template_type='xml'))
Beispiel #29
0
def main():
    tsig_algs = [
        'HMAC-MD5.SIG-ALG.REG.INT', 'hmac-md5', 'hmac-sha1', 'hmac-sha224',
        'hmac-sha256', 'hmac-sha384', 'hmac-sha512'
    ]

    module = AnsibleModule(argument_spec=dict(
        state=dict(required=False,
                   default='present',
                   choices=['present', 'absent'],
                   type='str'),
        server=dict(required=True, type='str'),
        port=dict(required=False, default=53, type='int'),
        key_name=dict(required=False, type='str'),
        key_secret=dict(required=False, type='str', no_log=True),
        key_algorithm=dict(required=False,
                           default='hmac-md5',
                           choices=tsig_algs,
                           type='str'),
        zone=dict(required=False, default=None, type='str'),
        record=dict(required=True, type='str'),
        type=dict(required=False, default='A', type='str'),
        ttl=dict(required=False, default=3600, type='int'),
        value=dict(required=False, default=None, type='list'),
        protocol=dict(required=False,
                      default='tcp',
                      choices=['tcp', 'udp'],
                      type='str')),
                           supports_check_mode=True)

    if not HAVE_DNSPYTHON:
        module.fail_json(msg=missing_required_lib('dnspython'),
                         exception=DNSPYTHON_IMP_ERR)

    if len(module.params["record"]) == 0:
        module.fail_json(msg='record cannot be empty.')

    record = RecordManager(module)
    result = {}
    if module.params["state"] == 'absent':
        result = record.remove_record()
    elif module.params["state"] == 'present':
        result = record.create_or_update_record()

    result['dns_rc'] = record.dns_rc
    result['dns_rc_str'] = dns.rcode.to_text(record.dns_rc)
    if result['failed']:
        module.fail_json(**result)
    else:
        result['record'] = dict(zone=record.zone,
                                record=module.params['record'],
                                type=module.params['type'],
                                ttl=module.params['ttl'],
                                value=record.value)

        module.exit_json(**result)
Beispiel #30
0
 def is_available(self):
     ''' we expect the python bindings installed, but if there is apt/apt-get give warning about missing bindings'''
     we_have_lib = super(APT, self).is_available()
     if not we_have_lib:
         for exe in ('apt', 'apt-get', 'aptitude'):
             if get_bin_path(exe):
                 module.warn('Found "%s" but %s' %
                             (exe, missing_required_lib('apt')))
                 break
     return we_have_lib