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_replacemsg_device_detection_portal": {
            "required": False,
            "type": "dict",
            "default": None,
            "options": {
                "buffer": {
                    "required": False,
                    "type": "str"
                },
                "format": {
                    "required": False,
                    "type": "str",
                    "choices": ["none", "text", "html", "wml"]
                },
                "header": {
                    "required": False,
                    "type": "str",
                    "choices": ["none", "http", "8bit"]
                },
                "msg_type": {
                    "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

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

            is_error, has_changed, result = fortios_system_replacemsg(
                module.params, fos)
            versions_check_result = connection.get_system_version()
        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_replacemsg(
            module.params, fos)
        fos.logout()

    if versions_check_result and versions_check_result['matched'] is False:
        module.warn(
            "Ansible has detected version mismatch between FortOS system and galaxy, see more details by specifying option -vvv"
        )

    if not is_error:
        if versions_check_result and versions_check_result['matched'] is False:
            module.exit_json(changed=has_changed,
                             version_check_warning=versions_check_result,
                             meta=result)
        else:
            module.exit_json(changed=has_changed, meta=result)
    else:
        if versions_check_result and versions_check_result['matched'] is False:
            module.fail_json(msg="Error in repo",
                             version_check_warning=versions_check_result,
                             meta=result)
        else:
            module.fail_json(msg="Error in repo", meta=result)
def main():
    jrpc_urls = [
        '/pm/config/adom/{adom}/obj/system/dhcp/server/{server}/reserved-address',
        '/pm/config/global/obj/system/dhcp/server/{server}/reserved-address'
    ]

    perobject_jrpc_urls = [
        '/pm/config/adom/{adom}/obj/system/dhcp/server/{server}/reserved-address/{reserved-address}',
        '/pm/config/global/obj/system/dhcp/server/{server}/reserved-address/{reserved-address}'
    ]

    url_params = ['adom', 'server']
    module_primary_key = 'id'
    module_arg_spec = {
        'enable_log': {
            'type': 'bool',
            'required': False,
            'default': False
        },
        'proposed_method': {
            'type': 'str',
            'required': False,
            'choices': [
                'set',
                'update',
                'add'
            ]
        },
        'bypass_validation': {
            'type': 'bool',
            'required': False,
            'default': False
        },
        'workspace_locking_adom': {
            'type': 'str',
            'required': False
        },
        'workspace_locking_timeout': {
            'type': 'int',
            'required': False,
            'default': 300
        },
        'rc_succeeded': {
            'required': False,
            'type': 'list'
        },
        'rc_failed': {
            'required': False,
            'type': 'list'
        },
        'state': {
            'type': 'str',
            'required': True,
            'choices': [
                'present',
                'absent'
            ]
        },
        'adom': {
            'required': True,
            'type': 'str'
        },
        'server': {
            'required': True,
            'type': 'str'
        },
        'system_dhcp_server_reservedaddress': {
            'required': False,
            'type': 'dict',
            'revision': {
                '6.0.0': True,
                '6.2.1': True,
                '6.2.3': True,
                '6.2.5': True,
                '6.4.0': True,
                '6.4.2': True,
                '6.4.5': True,
                '7.0.0': True
            },
            'options': {
                'action': {
                    'required': False,
                    'revision': {
                        '6.0.0': True,
                        '6.2.1': True,
                        '6.2.3': True,
                        '6.2.5': True,
                        '6.4.0': True,
                        '6.4.2': True,
                        '6.4.5': True,
                        '7.0.0': True
                    },
                    'choices': [
                        'assign',
                        'block',
                        'reserved'
                    ],
                    'type': 'str'
                },
                'description': {
                    'required': False,
                    'revision': {
                        '6.0.0': True,
                        '6.2.1': True,
                        '6.2.3': True,
                        '6.2.5': True,
                        '6.4.0': True,
                        '6.4.2': True,
                        '6.4.5': True,
                        '7.0.0': True
                    },
                    'type': 'str'
                },
                'id': {
                    'required': True,
                    'revision': {
                        '6.0.0': True,
                        '6.2.1': True,
                        '6.2.3': True,
                        '6.2.5': True,
                        '6.4.0': True,
                        '6.4.2': True,
                        '6.4.5': True,
                        '7.0.0': True
                    },
                    'type': 'int'
                },
                'ip': {
                    'required': False,
                    'revision': {
                        '6.0.0': True,
                        '6.2.1': True,
                        '6.2.3': True,
                        '6.2.5': True,
                        '6.4.0': True,
                        '6.4.2': True,
                        '6.4.5': True,
                        '7.0.0': True
                    },
                    'type': 'str'
                },
                'mac': {
                    'required': False,
                    'revision': {
                        '6.0.0': True,
                        '6.2.1': True,
                        '6.2.3': True,
                        '6.2.5': True,
                        '6.4.0': True,
                        '6.4.2': True,
                        '6.4.5': True,
                        '7.0.0': True
                    },
                    'type': 'str'
                },
                'circuit-id': {
                    'required': False,
                    'revision': {
                        '6.2.1': True,
                        '6.2.3': True,
                        '6.2.5': True,
                        '6.4.0': True,
                        '6.4.2': True,
                        '6.4.5': True,
                        '7.0.0': True
                    },
                    'type': 'str'
                },
                'circuit-id-type': {
                    'required': False,
                    'revision': {
                        '6.2.1': True,
                        '6.2.3': True,
                        '6.2.5': True,
                        '6.4.0': True,
                        '6.4.2': True,
                        '6.4.5': True,
                        '7.0.0': True
                    },
                    'choices': [
                        'hex',
                        'string'
                    ],
                    'type': 'str'
                },
                'remote-id': {
                    'required': False,
                    'revision': {
                        '6.2.1': True,
                        '6.2.3': True,
                        '6.2.5': True,
                        '6.4.0': True,
                        '6.4.2': True,
                        '6.4.5': True,
                        '7.0.0': True
                    },
                    'type': 'str'
                },
                'remote-id-type': {
                    'required': False,
                    'revision': {
                        '6.2.1': True,
                        '6.2.3': True,
                        '6.2.5': True,
                        '6.4.0': True,
                        '6.4.2': True,
                        '6.4.5': True,
                        '7.0.0': True
                    },
                    'choices': [
                        'hex',
                        'string'
                    ],
                    'type': 'str'
                },
                'type': {
                    'required': False,
                    'revision': {
                        '6.2.1': True,
                        '6.2.3': True,
                        '6.2.5': True,
                        '6.4.0': True,
                        '6.4.2': True,
                        '6.4.5': True,
                        '7.0.0': True
                    },
                    'choices': [
                        'mac',
                        'option82'
                    ],
                    'type': 'str'
                }
            }

        }
    }

    params_validation_blob = []
    check_galaxy_version(module_arg_spec)
    module = AnsibleModule(argument_spec=check_parameter_bypass(module_arg_spec, 'system_dhcp_server_reservedaddress'),
                           supports_check_mode=False)

    fmgr = None
    if module._socket_path:
        connection = Connection(module._socket_path)
        connection.set_option('enable_log', module.params['enable_log'] if 'enable_log' in module.params else False)
        fmgr = NAPIManager(jrpc_urls, perobject_jrpc_urls, module_primary_key, url_params, module, connection, top_level_schema_name='data')
        fmgr.validate_parameters(params_validation_blob)
        fmgr.process_curd(argument_specs=module_arg_spec)
    else:
        module.fail_json(msg='MUST RUN IN HTTPAPI MODE')
    module.exit_json(meta=module.params)
Пример #3
0
                      file=sys.stderr)
                pprint.pprint(ct.get_result().as_dict(), stream=sys.stderr)
                raise


if __name__ == '__main__':
    # When openshift-client-python/ansible/rebuild_module.sh is executed, it will read in this template
    # and replace the following variable with a b64 encoded tarball of the openshift-client-library
    # package. The client_python_extract_dir path will contain the 'openshift' package directory.
    REPLACED_BY_REBUILD_MODULE = '{}'
    OPENSHIFT_CLIENT_PYTHON_TGZ = six.BytesIO(
        base64.b64decode(REPLACED_BY_REBUILD_MODULE))

    module = AnsibleModule(argument_spec=dict(
        script=dict(required=True),
        vars=dict(required=False, default={}, type='dict'),
        project=dict(required=False, default=None),
        timeout=dict(required=False, default=None, type='int'),
        changes=dict(required=False, default=False, type='bool')))

    client_python_extract_dir = tempfile.mkdtemp()
    module.debug('Extracting openshift-client-python module to: {}'.format(
        client_python_extract_dir))

    try:
        tf = tarfile.open(fileobj=OPENSHIFT_CLIENT_PYTHON_TGZ, mode='r:gz')
        tf.extractall(client_python_extract_dir)
        # Add the newly extacted directory to the python path to resolve the openshift package
        sys.path.append(client_python_extract_dir)
        # Import openshift as oc so that we can delete the extract directory. module.exit_ type methods
        # call sys.exit, so this is our only chance to leave no trace.
        import openshift as oc
Пример #4
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"]
        },
        "vpn_ipsec_manualkey_interface": {
            "required": False,
            "type": "dict",
            "default": None,
            "options": {
                "state": {
                    "required": False,
                    "type": "str",
                    "choices": ["present", "absent"]
                },
                "addr_type": {
                    "required": False,
                    "type": "str",
                    "choices": ["4", "6"]
                },
                "auth_alg": {
                    "required":
                    False,
                    "type":
                    "str",
                    "choices":
                    ["null", "md5", "sha1", "sha256", "sha384", "sha512"]
                },
                "auth_key": {
                    "required": False,
                    "type": "str"
                },
                "enc_alg": {
                    "required": False,
                    "type": "str",
                    "choices": ["null", "des"]
                },
                "enc_key": {
                    "required": False,
                    "type": "str"
                },
                "interface": {
                    "required": False,
                    "type": "str"
                },
                "ip_version": {
                    "required": False,
                    "type": "str",
                    "choices": ["4", "6"]
                },
                "local_gw": {
                    "required": False,
                    "type": "str"
                },
                "local_gw6": {
                    "required": False,
                    "type": "str"
                },
                "local_spi": {
                    "required": False,
                    "type": "str"
                },
                "name": {
                    "required": True,
                    "type": "str"
                },
                "remote_gw": {
                    "required": False,
                    "type": "str"
                },
                "remote_gw6": {
                    "required": False,
                    "type": "str"
                },
                "remote_spi": {
                    "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_ipsec(
                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_ipsec(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)
Пример #5
0
def main():
    module = AnsibleModule(
        argument_spec = dict(
            delete_on_termination = dict(type='bool'),
            detach_only = dict(type='bool'),
            instance_name = dict(),
            mode = dict(default='READ_ONLY', choices=['READ_WRITE', 'READ_ONLY']),
            name = dict(required=True),
            size_gb = dict(default=10),
            disk_type = dict(default='pd-standard'),
            image = dict(),
            image_family = dict(),
            external_projects = dict(type='list'),
            snapshot = dict(),
            state = dict(default='present'),
            zone = dict(default='us-central1-b'),
            service_account_email = dict(),
            pem_file = dict(type='path'),
            credentials_file = dict(type='path'),
            project_id = dict(),
        )
    )
    if not HAS_LIBCLOUD:
        module.fail_json(msg='libcloud with GCE support (0.17.0+) is required for this module')

    gce = gce_connect(module)

    delete_on_termination = module.params.get('delete_on_termination')
    detach_only = module.params.get('detach_only')
    instance_name = module.params.get('instance_name')
    mode = module.params.get('mode')
    name = module.params.get('name')
    size_gb = module.params.get('size_gb')
    disk_type = module.params.get('disk_type')
    image = module.params.get('image')
    image_family = module.params.get('image_family')
    external_projects = module.params.get('external_projects')
    snapshot = module.params.get('snapshot')
    state = module.params.get('state')
    zone = module.params.get('zone')

    if delete_on_termination and not instance_name:
        module.fail_json(
            msg='Must specify an instance name when requesting delete on termination',
            changed=False)

    if detach_only and not instance_name:
        module.fail_json(
            msg='Must specify an instance name when detaching a disk',
            changed=False)

    disk = inst = None
    changed = is_attached = False

    json_output = { 'name': name, 'zone': zone, 'state': state, 'disk_type': disk_type  }
    if detach_only:
        json_output['detach_only'] = True
        json_output['detached_from_instance'] = instance_name

    if instance_name:
        # user wants to attach/detach from an existing instance
        try:
            inst = gce.ex_get_node(instance_name, zone)
            # is the disk attached?
            for d in inst.extra['disks']:
                if d['deviceName'] == name:
                    is_attached = True
                    json_output['attached_mode'] = d['mode']
                    json_output['attached_to_instance'] = inst.name
        except:
            pass

    # find disk if it already exists
    try:
        disk = gce.ex_get_volume(name)
        json_output['size_gb'] = int(disk.size)
    except ResourceNotFoundError:
        pass
    except Exception as e:
        module.fail_json(msg=unexpected_error_msg(e), changed=False)

    # user wants a disk to exist.  If "instance_name" is supplied the user
    # also wants it attached
    if state in ['active', 'present']:

        if not size_gb:
            module.fail_json(msg="Must supply a size_gb", changed=False)
        try:
            size_gb = int(round(float(size_gb)))
            if size_gb < 1:
                raise Exception
        except:
            module.fail_json(msg="Must supply a size_gb larger than 1 GB",
                    changed=False)

        if instance_name and inst is None:
            module.fail_json(msg='Instance %s does not exist in zone %s' % (
                instance_name, zone), changed=False)

        if not disk:
            if image is not None and snapshot is not None:
                module.fail_json(
                    msg='Cannot give both image (%s) and snapshot (%s)' % (
                        image, snapshot), changed=False)
            lc_image = None
            lc_snapshot = None
            if image_family is not None:
                lc_image = gce.ex_get_image_from_family(image_family, ex_project_list=external_projects)
            elif image is not None:
                lc_image = gce.ex_get_image(image, ex_project_list=external_projects)
            elif snapshot is not None:
                lc_snapshot = gce.ex_get_snapshot(snapshot)
            try:
                disk = gce.create_volume(
                    size_gb, name, location=zone, image=lc_image,
                    snapshot=lc_snapshot, ex_disk_type=disk_type)
            except ResourceExistsError:
                pass
            except QuotaExceededError:
                module.fail_json(msg='Requested disk size exceeds quota',
                        changed=False)
            except Exception as e:
                module.fail_json(msg=unexpected_error_msg(e), changed=False)
            json_output['size_gb'] = size_gb
            if image is not None:
                json_output['image'] = image
            if snapshot is not None:
                json_output['snapshot'] = snapshot
            changed = True
        if inst and not is_attached:
            try:
                gce.attach_volume(inst, disk, device=name, ex_mode=mode,
                                  ex_auto_delete=delete_on_termination)
            except Exception as e:
                module.fail_json(msg=unexpected_error_msg(e), changed=False)
            json_output['attached_to_instance'] = inst.name
            json_output['attached_mode'] = mode
            if delete_on_termination:
                json_output['delete_on_termination'] = True
            changed = True

    # user wants to delete a disk (or perhaps just detach it).
    if state in ['absent', 'deleted'] and disk:

        if inst and is_attached:
            try:
                gce.detach_volume(disk, ex_node=inst)
            except Exception as e:
                module.fail_json(msg=unexpected_error_msg(e), changed=False)
            changed = True
        if not detach_only:
            try:
                gce.destroy_volume(disk)
            except ResourceInUseError as e:
                module.fail_json(msg=str(e.value), changed=False)
            except Exception as e:
                module.fail_json(msg=unexpected_error_msg(e), changed=False)
            changed = True

    json_output['changed'] = changed
    module.exit_json(**json_output)
Пример #6
0
def main():
    fields = {
        "host": {
            "required": False,
            "type": "str"
        },
        "username": {
            "required": False,
            "type": "str"
        },
        "password": {
            "required": False,
            "type": "str",
            "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"]
        },
        "dlp_fp_doc_source": {
            "required": False,
            "type": "dict",
            "default": None,
            "options": {
                "date": {
                    "required": False,
                    "type": "int"
                },
                "file_path": {
                    "required": False,
                    "type": "str"
                },
                "file_pattern": {
                    "required": False,
                    "type": "str"
                },
                "keep_modified": {
                    "required": False,
                    "type": "str",
                    "choices": ["enable", "disable"]
                },
                "name": {
                    "required": True,
                    "type": "str"
                },
                "password": {
                    "required": False,
                    "type": "str"
                },
                "period": {
                    "required": False,
                    "type": "str",
                    "choices": ["none", "daily", "weekly", "monthly"]
                },
                "remove_deleted": {
                    "required": False,
                    "type": "str",
                    "choices": ["enable", "disable"]
                },
                "scan_on_creation": {
                    "required": False,
                    "type": "str",
                    "choices": ["enable", "disable"]
                },
                "scan_subdirectories": {
                    "required": False,
                    "type": "str",
                    "choices": ["enable", "disable"]
                },
                "sensitivity": {
                    "required": False,
                    "type": "str"
                },
                "server": {
                    "required": False,
                    "type": "str"
                },
                "server_type": {
                    "required": False,
                    "type": "str",
                    "choices": ["samba"]
                },
                "tod_hour": {
                    "required": False,
                    "type": "int"
                },
                "tod_min": {
                    "required": False,
                    "type": "int"
                },
                "username": {
                    "required": False,
                    "type": "str"
                },
                "vdom": {
                    "required": False,
                    "type": "str",
                    "choices": ["mgmt", "current"]
                },
                "weekday": {
                    "required":
                    False,
                    "type":
                    "str",
                    "choices": [
                        "sunday", "monday", "tuesday", "wednesday", "thursday",
                        "friday", "saturday"
                    ]
                }
            }
        }
    }

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

    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_dlp(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_dlp(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():
    """ main entry point for module execution
    """
    backup_spec = dict(filename=dict(), dir_path=dict(type="path"))
    argument_spec = dict(
        src=dict(type="path"),
        replace_src=dict(),
        lines=dict(aliases=["commands"], type="list", elements="str"),
        parents=dict(type="list", elements="str"),
        before=dict(type="list", elements="str"),
        after=dict(type="list", elements="str"),
        match=dict(
            default="line", choices=["line", "strict", "exact", "none"]
        ),
        replace=dict(default="line", choices=["line", "block", "config"]),
        running_config=dict(aliases=["config"]),
        intended_config=dict(),
        defaults=dict(type="bool", default=False),
        backup=dict(type="bool", default=False),
        backup_options=dict(type="dict", options=backup_spec),
        save_when=dict(
            choices=["always", "never", "modified", "changed"], default="never"
        ),
        diff_against=dict(choices=["running", "startup", "intended"]),
        diff_ignore_lines=dict(type="list", elements="str"),
    )

    argument_spec.update(nxos_argument_spec)

    mutually_exclusive = [("lines", "src", "replace_src"), ("parents", "src")]

    required_if = [
        ("match", "strict", ["lines"]),
        ("match", "exact", ["lines"]),
        ("replace", "block", ["lines"]),
        ("replace", "config", ["replace_src"]),
        ("diff_against", "intended", ["intended_config"]),
    ]

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

    warnings = list()

    result = {"changed": False, "warnings": warnings}

    config = None

    diff_ignore_lines = module.params["diff_ignore_lines"]
    path = module.params["parents"]
    connection = get_connection(module)
    contents = None
    flags = ["all"] if module.params["defaults"] else []
    replace_src = module.params["replace_src"]
    if replace_src:
        if module.params["replace"] != "config":
            module.fail_json(
                msg="replace: config is required with replace_src"
            )

    if module.params["backup"] or (
        module._diff and module.params["diff_against"] == "running"
    ):
        contents = get_config(module, flags=flags)
        config = NetworkConfig(indent=2, contents=contents)
        if module.params["backup"]:
            result["__backup__"] = contents

    if any((module.params["src"], module.params["lines"], replace_src)):
        msg = (
            "To ensure idempotency and correct diff the input configuration lines should be"
            " similar to how they appear if present in the running configuration on device"
        )
        if module.params["src"] or replace_src:
            msg += " including the indentation"
        warnings.append(msg)
        match = module.params["match"]
        replace = module.params["replace"]

        commit = not module.check_mode
        candidate = get_candidate(module)
        running = get_running_config(module, contents, flags=flags)
        if replace_src:
            commands = candidate.split("\n")
            result["commands"] = result["updates"] = commands
            if commit:
                load_config(module, commands, replace=replace_src)

            result["changed"] = True
        else:
            try:
                response = connection.get_diff(
                    candidate=candidate,
                    running=running,
                    diff_match=match,
                    diff_ignore_lines=diff_ignore_lines,
                    path=path,
                    diff_replace=replace,
                )
            except ConnectionError as exc:
                module.fail_json(
                    msg=to_text(exc, errors="surrogate_then_replace")
                )

            config_diff = response["config_diff"]
            if config_diff:
                commands = config_diff.split("\n")

                if module.params["before"]:
                    commands[:0] = module.params["before"]

                if module.params["after"]:
                    commands.extend(module.params["after"])

                result["commands"] = commands
                result["updates"] = commands

                if commit:
                    load_config(module, commands, replace=replace_src)

                result["changed"] = True

    running_config = module.params["running_config"]
    startup_config = None

    if module.params["save_when"] == "always":
        save_config(module, result)
    elif module.params["save_when"] == "modified":
        output = execute_show_commands(
            module, ["show running-config", "show startup-config"]
        )

        running_config = NetworkConfig(
            indent=2, contents=output[0], ignore_lines=diff_ignore_lines
        )
        startup_config = NetworkConfig(
            indent=2, contents=output[1], ignore_lines=diff_ignore_lines
        )

        if running_config.sha1 != startup_config.sha1:
            save_config(module, result)
    elif module.params["save_when"] == "changed" and result["changed"]:
        save_config(module, result)

    if module._diff:
        if not running_config:
            output = execute_show_commands(module, "show running-config")
            contents = output[0]
        else:
            contents = running_config

        # recreate the object in order to process diff_ignore_lines
        running_config = NetworkConfig(
            indent=2, contents=contents, ignore_lines=diff_ignore_lines
        )

        if module.params["diff_against"] == "running":
            if module.check_mode:
                module.warn(
                    "unable to perform diff against running-config due to check mode"
                )
                contents = None
            else:
                contents = config.config_text

        elif module.params["diff_against"] == "startup":
            if not startup_config:
                output = execute_show_commands(module, "show startup-config")
                contents = output[0]
            else:
                contents = startup_config.config_text

        elif module.params["diff_against"] == "intended":
            contents = module.params["intended_config"]

        if contents is not None:
            base_config = NetworkConfig(
                indent=2, contents=contents, ignore_lines=diff_ignore_lines
            )

            if running_config.sha1 != base_config.sha1:
                if module.params["diff_against"] == "intended":
                    before = running_config
                    after = base_config
                elif module.params["diff_against"] in ("startup", "running"):
                    before = base_config
                    after = running_config

                result.update(
                    {
                        "changed": True,
                        "diff": {"before": str(before), "after": str(after)},
                    }
                )

    module.exit_json(**result)
Пример #8
0
def main():
    argument_spec = dict(
        snmp_host=dict(required=True, type='str'),
        community=dict(type='str'),
        udp=dict(type='str', default='162'),
        version=dict(choices=['v1', 'v2c', 'v3']),
        src_intf=dict(type='str'),
        v3=dict(choices=['noauth', 'auth', 'priv']),
        vrf_filter=dict(type='str'),
        vrf=dict(type='str'),
        snmp_type=dict(choices=['trap', 'inform']),
        state=dict(choices=['absent', 'present'], default='present'),
    )

    argument_spec.update(nxos_argument_spec)

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

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

    snmp_host = module.params['snmp_host']
    community = module.params['community']
    udp = module.params['udp']
    version = module.params['version']
    src_intf = module.params['src_intf']
    v3 = module.params['v3']
    vrf_filter = module.params['vrf_filter']
    vrf = module.params['vrf']
    snmp_type = module.params['snmp_type']
    state = module.params['state']

    existing = get_snmp_host(snmp_host, udp, module)

    if version is None:
        if existing:
            version = existing.get('version')
        else:
            version = 'v1'

    if snmp_type is None:
        if existing:
            snmp_type = existing.get('snmp_type')
        else:
            snmp_type = 'trap'

    if v3 is None:
        if version == 'v3' and existing:
            v3 = existing.get('v3')

    if snmp_type == 'inform' and version == 'v1':
        module.fail_json(msg='inform requires snmp v2c or v3')

    if (version == 'v1' or version == 'v2c') and v3:
        module.fail_json(msg='param: "v3" should not be used when '
                             'using version v1 or v2c')

    if not any([vrf_filter, vrf, src_intf]):
        if not all([snmp_type, version, community, udp]):
            module.fail_json(msg='when not configuring options like '
                                 'vrf_filter, vrf, and src_intf,'
                                 'the following params are required: '
                                 'type, version, community')

    if version == 'v3' and v3 is None:
        module.fail_json(msg='when using version=v3, the param v3 '
                             '(options: auth, noauth, priv) is also required')

    # existing returns the list of vrfs configured for a given host
    # checking to see if the proposed is in the list
    store = existing.get('vrf_filter')
    if existing and store:
        if vrf_filter not in existing['vrf_filter']:
            existing['vrf_filter'] = None
        else:
            existing['vrf_filter'] = vrf_filter
    commands = []

    args = dict(
        community=community,
        snmp_host=snmp_host,
        udp=udp,
        version=version,
        src_intf=src_intf,
        vrf_filter=vrf_filter,
        v3=v3,
        vrf=vrf,
        snmp_type=snmp_type
    )
    proposed = dict((k, v) for k, v in args.items() if v is not None)

    if state == 'absent' and existing:
        if proposed.get('community'):
            commands.append(remove_snmp_host(snmp_host, udp, existing))
        else:
            if proposed.get('src_intf'):
                commands.append(remove_src(snmp_host, udp, proposed, existing))
            if proposed.get('vrf'):
                commands.append(remove_vrf(snmp_host, udp, proposed, existing))
            if proposed.get('vrf_filter'):
                commands.append(remove_filter(snmp_host, udp, proposed, existing))

    elif state == 'present':
        delta = dict(set(proposed.items()).difference(existing.items()))
        if delta:
            command = config_snmp_host(delta, udp, proposed, existing, module)
            commands.append(command)

    cmds = flatten_list(commands)
    if cmds:
        results['changed'] = True
        if not module.check_mode:
            load_config(module, cmds)

        if 'configure' in cmds:
            cmds.pop(0)
        results['commands'] = cmds

    module.exit_json(**results)
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"]},
        "wireless_controller_hotspot20_icon": {
            "required": False, "type": "dict", "default": None,
            "options": {
                "icon_list": {"required": False, "type": "list",
                              "options": {
                                  "file": {"required": False, "type": "str"},
                                  "height": {"required": False, "type": "int"},
                                  "lang": {"required": False, "type": "str"},
                                  "name": {"required": True, "type": "str"},
                                  "type": {"required": False, "type": "str",
                                           "choices": ["bmp", "gif", "jpeg",
                                                       "png", "tiff"]},
                                  "width": {"required": False, "type": "int"}
                              }},
                "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_wireless_controller_hotspot20(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_wireless_controller_hotspot20(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
        },
        "state": {
            "required": True,
            "type": "str",
            "choices": ["present", "absent"]
        },
        "firewall_multicast_policy6": {
            "required": False,
            "type": "dict",
            "default": None,
            "options": {
                "action": {
                    "required": False,
                    "type": "str",
                    "choices": ["accept", "deny"]
                },
                "dstaddr": {
                    "required": False,
                    "type": "list",
                    "options": {
                        "name": {
                            "required": True,
                            "type": "str"
                        }
                    }
                },
                "dstintf": {
                    "required": False,
                    "type": "str"
                },
                "end_port": {
                    "required": False,
                    "type": "int"
                },
                "id": {
                    "required": True,
                    "type": "int"
                },
                "logtraffic": {
                    "required": False,
                    "type": "str",
                    "choices": ["enable", "disable"]
                },
                "protocol": {
                    "required": False,
                    "type": "int"
                },
                "srcaddr": {
                    "required": False,
                    "type": "list",
                    "options": {
                        "name": {
                            "required": True,
                            "type": "str"
                        }
                    }
                },
                "srcintf": {
                    "required": False,
                    "type": "str"
                },
                "start_port": {
                    "required": False,
                    "type": "int"
                },
                "status": {
                    "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)
Пример #11
0
    def __init__(self):
        """
        Parse arguments, setup state variables,
        check paramenters and ensure SDK is installed
        """
        self._size_unit_map = netapp_utils.SF_BYTE_MAP

        self.argument_spec = netapp_utils.ontap_sf_host_argument_spec()
        self.argument_spec.update(
            dict(
                state=dict(required=False,
                           type='str',
                           choices=['present', 'absent'],
                           default='present'),
                name=dict(required=True, type='str'),
                account_id=dict(required=True),
                enable512e=dict(type='bool', aliases=['enable512emulation']),
                qos=dict(required=False, type='dict', default=None),
                attributes=dict(required=False, type='dict', default=None),
                size=dict(type='int'),
                size_unit=dict(default='gb',
                               choices=[
                                   'bytes', 'b', 'kb', 'mb', 'gb', 'tb', 'pb',
                                   'eb', 'zb', 'yb'
                               ],
                               type='str'),
                access=dict(required=False,
                            type='str',
                            default=None,
                            choices=[
                                'readOnly', 'readWrite', 'locked',
                                'replicationTarget'
                            ]),
            ))

        self.module = AnsibleModule(argument_spec=self.argument_spec,
                                    required_if=[('state', 'present',
                                                  ['size', 'enable512e'])],
                                    supports_check_mode=True)

        param = self.module.params

        # set up state variables
        self.state = param['state']
        self.name = param['name']
        self.account_id = param['account_id']
        self.enable512e = param['enable512e']
        self.qos = param['qos']
        self.attributes = param['attributes']
        self.access = param['access']
        self.size_unit = param['size_unit']
        if param['size'] is not None:
            self.size = param['size'] * self._size_unit_map[self.size_unit]
        else:
            self.size = None

        if HAS_SF_SDK is False:
            self.module.fail_json(
                msg="Unable to import the ElementSW Python SDK")
        else:
            try:
                self.sfe = netapp_utils.create_sf_connection(
                    module=self.module)
            except solidfire.common.ApiServerError:
                self.module.fail_json(msg="Unable to create the connection")

        self.elementsw_helper = NaElementSWModule(self.sfe)

        # add telemetry attributes
        if self.attributes is not None:
            self.attributes.update(
                self.elementsw_helper.set_element_attributes(
                    source='na_elementsw_volume'))
        else:
            self.attributes = self.elementsw_helper.set_element_attributes(
                source='na_elementsw_volume')
def main():

    module_specific_arguments = dict(
        servicename=dict(type='str'),
        cnameentry=dict(type='str'),
        servername=dict(type='str'),
        servicetype=dict(type='str',
                         choices=[
                             'HTTP',
                             'FTP',
                             'TCP',
                             'UDP',
                             'SSL',
                             'SSL_BRIDGE',
                             'SSL_TCP',
                             'NNTP',
                             'ANY',
                             'SIP_UDP',
                             'SIP_TCP',
                             'SIP_SSL',
                             'RADIUS',
                             'RDP',
                             'RTSP',
                             'MYSQL',
                             'MSSQL',
                             'ORACLE',
                         ]),
        port=dict(type='int'),
        publicip=dict(type='str'),
        publicport=dict(type='int'),
        maxclient=dict(type='float'),
        healthmonitor=dict(type='bool'),
        sitename=dict(type='str'),
        cip=dict(type='str', choices=[
            'enabled',
            'disabled',
        ]),
        cipheader=dict(type='str'),
        sitepersistence=dict(type='str',
                             choices=[
                                 'ConnectionProxy',
                                 'HTTPRedirect',
                                 'NONE',
                             ]),
        siteprefix=dict(type='str'),
        clttimeout=dict(type='float'),
        maxbandwidth=dict(type='float'),
        downstateflush=dict(type='str', choices=[
            'enabled',
            'disabled',
        ]),
        maxaaausers=dict(type='float'),
        monthreshold=dict(type='float'),
        hashid=dict(type='float'),
        comment=dict(type='str'),
        appflowlog=dict(type='str', choices=[
            'enabled',
            'disabled',
        ]),
        ipaddress=dict(type='str'),
    )

    hand_inserted_arguments = dict(monitor_bindings=dict(type='list'), )

    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)

    if not module.params['mas_proxy_call']:
        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 = [
        'servicename',
        'cnameentry',
        'ip',
        'servername',
        'servicetype',
        'port',
        'publicip',
        'publicport',
        'maxclient',
        'healthmonitor',
        'sitename',
        'cip',
        'cipheader',
        'sitepersistence',
        'siteprefix',
        'clttimeout',
        'maxbandwidth',
        'downstateflush',
        'maxaaausers',
        'monthreshold',
        'hashid',
        'comment',
        'appflowlog',
        'ipaddress',
    ]

    readonly_attrs = [
        'gslb',
        'svrstate',
        'svreffgslbstate',
        'gslbthreshold',
        'gslbsvcstats',
        'monstate',
        'preferredlocation',
        'monitor_state',
        'statechangetimesec',
        'tickssincelaststatechange',
        'threshold',
        'clmonowner',
        'clmonview',
        '__count',
    ]

    immutable_attrs = [
        'servicename',
        'cnameentry',
        'ip',
        'servername',
        'servicetype',
        'port',
        'sitename',
        'state',
        'cipheader',
        'cookietimeout',
        'clttimeout',
        'svrtimeout',
        'viewip',
        'monitor_name_svc',
        'newname',
    ]

    transforms = {
        'healthmonitor': ['bool_yes_no'],
        'cip': [lambda v: v.upper()],
        'downstateflush': [lambda v: v.upper()],
        'appflowlog': [lambda v: v.upper()],
    }

    # params = copy.deepcopy(module.params)
    module.params['ip'] = module.params['ipaddress']

    # Instantiate config proxy
    gslb_service_proxy = ConfigProxy(
        actual=gslbservice(),
        client=client,
        attribute_values_dict=module.params,
        transforms=transforms,
        readwrite_attrs=readwrite_attrs,
        readonly_attrs=readonly_attrs,
        immutable_attrs=immutable_attrs,
    )

    try:
        ensure_feature_is_enabled(client, 'GSLB')
        # Apply appropriate state
        if module.params['state'] == 'present':
            if not gslb_service_exists(client, module):
                if not module.check_mode:
                    gslb_service_proxy.add()
                    sync_monitor_bindings(client, module)
                    if module.params['save_config']:
                        client.save_config()
                module_result['changed'] = True
            elif not all_identical(client, module, gslb_service_proxy):

                # Check if we try to change value of immutable attributes
                immutables_changed = get_immutables_intersection(
                    gslb_service_proxy,
                    diff_list(client, module, gslb_service_proxy).keys())
                if immutables_changed != []:
                    module.fail_json(
                        msg='Cannot update immutable attributes %s' %
                        (immutables_changed, ),
                        diff=diff_list(client, module, gslb_service_proxy),
                        **module_result)

                # Update main configuration object
                if not gslb_service_identical(client, module,
                                              gslb_service_proxy):
                    if not module.check_mode:
                        gslb_service_proxy.update()

                # Update monitor bindigns
                if not monitor_bindings_identical(client, module):
                    if not module.check_mode:
                        sync_monitor_bindings(client, module)

                # Fallthrough to save and change status update
                module_result['changed'] = True
                if module.params['save_config']:
                    client.save_config()
            else:
                module_result['changed'] = False

            # Sanity check for state
            if not module.check_mode:
                if not gslb_service_exists(client, module):
                    module.fail_json(msg='GSLB service does not exist',
                                     **module_result)
                if not gslb_service_identical(client, module,
                                              gslb_service_proxy):
                    module.fail_json(
                        msg='GSLB service differs from configured',
                        diff=diff_list(client, module, gslb_service_proxy),
                        **module_result)
                if not monitor_bindings_identical(client, module):
                    module.fail_json(
                        msg='Monitor bindings differ from configured',
                        diff=diff_list(client, module, gslb_service_proxy),
                        **module_result)

        elif module.params['state'] == 'absent':
            if gslb_service_exists(client, module):
                if not module.check_mode:
                    gslb_service_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:
                if gslb_service_exists(client, module):
                    module.fail_json(msg='GSLB service 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)

    if not module.params['mas_proxy_call']:
        client.logout()

    module.exit_json(**module_result)
Пример #13
0
def main():
    """ main entry point for module execution
    """
    element_spec = dict(
        name=dict(),

        configured_password=dict(no_log=True),
        update_password=dict(default='always', choices=['on_create', 'always']),

        public_key=dict(),
        public_key_contents=dict(),

        group=dict(aliases=['role']),
        groups=dict(type='list', elements='dict'),

        state=dict(default='present', choices=['present', 'absent'])
    )
    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, aliases=['users', 'collection']),
        purge=dict(type='bool', default=False)
    )

    argument_spec.update(element_spec)
    argument_spec.update(iosxr_argument_spec)
    mutually_exclusive = [('name', 'aggregate'), ('public_key', 'public_key_contents'), ('group', 'groups')]

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

    if (module.params['public_key_contents'] or module.params['public_key']):
        if not HAS_B64:
            module.fail_json(
                msg='library base64 is required but does not appear to be '
                    'installed. It can be installed using `pip install base64`'
            )
        if not HAS_PARAMIKO:
            module.fail_json(
                msg='library paramiko is required but does not appear to be '
                    'installed. It can be installed using `pip install paramiko`'
            )

    warnings = list()
    if module.params['password'] and not module.params['configured_password']:
        warnings.append(
            'The "password" argument is used to authenticate the current connection. ' +
            'To set a user password use "configured_password" instead.'
        )

    result = {'changed': False}

    want = map_params_to_obj(module)
    have = map_config_to_obj(module)

    commands = map_obj_to_commands((want, have), module)

    if module.params['purge']:
        want_users = [x['name'] for x in want]
        have_users = [x['name'] for x in have]
        for item in set(have_users).difference(want_users):
            if item != 'admin':
                commands.append('no username %s' % item)

    result['commands'] = commands
    result['warnings'] = warnings

    if 'no username admin' in commands:
        module.fail_json(msg='cannot delete the `admin` account')

    if commands:
        commit = not module.check_mode
        diff = load_config(module, commands, commit=commit)
        if diff:
            result['diff'] = dict(prepared=diff)
        result['changed'] = True

    if module.params['state'] == 'present' and (module.params['public_key_contents'] or module.params['public_key']):
        if not module.check_mode:
            key = convert_key_to_base64(module)
            copykeys = copy_key_to_node(module, key)
            if copykeys is False:
                warnings.append('Please set up your provider before running this playbook')

            if module.params['aggregate']:
                for user in module.params['aggregate']:
                    cmdtodo = "admin crypto key import authentication rsa username %s harddisk:/publickey_aggregate.b64" % (user)
                    addremove = addremovekey(module, cmdtodo)
                    if addremove is False:
                        warnings.append('Please set up your provider before running this playbook')
            else:
                cmdtodo = "admin crypto key import authentication rsa username %s harddisk:/publickey_%s.b64" % (module.params['name'], module.params['name'])
                addremove = addremovekey(module, cmdtodo)
                if addremove is False:
                    warnings.append('Please set up your provider before running this playbook')
    elif module.params['state'] == 'absent':
        if not module.check_mode:
            if module.params['aggregate']:
                for user in module.params['aggregate']:
                    cmdtodo = "admin crypto key zeroize authentication rsa username %s" % (user)
                    addremove = addremovekey(module, cmdtodo)
                    if addremove is False:
                        warnings.append('Please set up your provider before running this playbook')
            else:
                cmdtodo = "admin crypto key zeroize authentication rsa username %s" % (module.params['name'])
                addremove = addremovekey(module, cmdtodo)
                if addremove is False:
                    warnings.append('Please set up your provider before running this playbook')
    elif module.params['purge'] is True:
        if not module.check_mode:
            cmdtodo = "admin crypto key zeroize authentication rsa all"
            addremove = addremovekey(module, cmdtodo)
            if addremove is False:
                warnings.append('Please set up your provider before running this playbook')

    module.exit_json(**result)
def main():
    argument_spec = dict(ip_address=dict(required=True),
                         password=dict(no_log=True),
                         username=dict(default='admin'),
                         api_key=dict(no_log=True),
                         state=dict(default='present',
                                    choices=['present', 'absent']),
                         name=dict(required=True),
                         dhgroup=dict(default='group2'),
                         authentication=dict(default='sha1'),
                         encryption=dict(type='list',
                                         default=['aes-256-cbc', '3des']),
                         lifetime_sec=dict(type='int', default=28800),
                         commit=dict(type='bool', default=True))
    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=False,
                           required_one_of=[['api_key', 'password']])
    if not HAS_LIB:
        module.fail_json(msg='Missing required libraries.')

    ip_address = module.params['ip_address']
    password = module.params['password']
    username = module.params['username']
    api_key = module.params['api_key']
    state = module.params['state']
    ike_profile_name = module.params['name']
    ike_dhgroup = module.params['dhgroup']
    ike_authentication = module.params['authentication']
    ike_encryption = module.params['encryption']
    ike_lifetime_sec = module.params['lifetime_sec']
    commit = module.params['commit']

    # If Panorama, validate the devicegroup
    # dev_group = None
    # if devicegroup and isinstance(device, panorama.Panorama):
    #     dev_group = get_devicegroup(device, devicegroup)
    #     if dev_group:
    #         device.add(dev_group)
    #     else:
    #         module.fail_json(msg='\'%s\' device group not found in Panorama. Is the name correct?' % devicegroup)

    ikeProfile = IKEProfile(name=ike_profile_name,
                            authentication=ike_authentication,
                            encryption=ike_encryption,
                            dh_group=ike_dhgroup,
                            lifetime_secs=ike_lifetime_sec)

    ike_crypto_prof = network.IkeCryptoProfile(
        ikeProfile.name, ikeProfile.dh_group, ikeProfile.authentication,
        ikeProfile.encryption, ikeProfile.lifetime_secs, None, None, None, 0)

    # Create the device with the appropriate pandevice type
    device = base.PanDevice.create_from_device(ip_address,
                                               username,
                                               password,
                                               api_key=api_key)

    changed = False
    try:
        # fetch all crypto profiles
        profiles = network.IkeCryptoProfile.refreshall(device)
        if state == "present":
            device.add(ike_crypto_prof)
            for p in profiles:
                if p.name == ike_crypto_prof.name:
                    if not ike_crypto_prof.equal(p):
                        ike_crypto_prof.apply()
                        changed = True
                    break
            else:
                ike_crypto_prof.create()
                changed = True
        elif state == "absent":
            ike_crypto_prof = device.find(ikeProfile.name,
                                          network.IkeCryptoProfile)
            if ike_crypto_prof:
                ike_crypto_prof.delete()
                changed = True
        else:
            module.fail_json(msg='[%s] state is not implemented yet' % state)
    except PanDeviceError:
        exc = get_exception()
        module.fail_json(msg=exc.message)

    if commit and changed:
        device.commit(sync=True)

    module.exit_json(msg='IKE Crypto profile config successful.',
                     changed=changed)
Пример #15
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
        },
        "system_fortisandbox": {
            "required": False,
            "type": "dict",
            "default": None,
            "options": {
                "email": {
                    "required": False,
                    "type": "str"
                },
                "enc_algorithm": {
                    "required": False,
                    "type": "str",
                    "choices": ["default", "high", "low"]
                },
                "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"]
                }
            }
        }
    }

    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},
        "state": {"required": True, "type": "str",
                  "choices": ["present", "absent"]},
        "system_gre_tunnel": {
            "required": False, "type": "dict", "default": None,
            "options": {
                "checksum_reception": {"required": False, "type": "str",
                                       "choices": ["disable", "enable"]},
                "checksum_transmission": {"required": False, "type": "str",
                                          "choices": ["disable", "enable"]},
                "dscp_copying": {"required": False, "type": "str",
                                 "choices": ["disable", "enable"]},
                "interface": {"required": False, "type": "str"},
                "ip_version": {"required": False, "type": "str",
                               "choices": ["4", "6"]},
                "keepalive_failtimes": {"required": False, "type": "int"},
                "keepalive_interval": {"required": False, "type": "int"},
                "key_inbound": {"required": False, "type": "int"},
                "key_outbound": {"required": False, "type": "int"},
                "local_gw": {"required": False, "type": "str"},
                "local_gw6": {"required": False, "type": "str"},
                "name": {"required": True, "type": "str"},
                "remote_gw": {"required": False, "type": "str"},
                "remote_gw6": {"required": False, "type": "str"},
                "sequence_number_reception": {"required": False, "type": "str",
                                              "choices": ["disable", "enable"]},
                "sequence_number_transmission": {"required": False, "type": "str",
                                                 "choices": ["disable", "enable"]}

            }
        }
    }

    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 execution

    :return:
    """
    argument_spec = keycloak_argument_spec()

    protmapper_spec = dict(
        consentRequired=dict(type='bool'),
        consentText=dict(type='str'),
        id=dict(type='str'),
        name=dict(type='str'),
        protocol=dict(type='str', choices=['openid-connect', 'saml']),
        protocolMapper=dict(type='str'),
        config=dict(type='dict'),
    )

    meta_args = dict(
        state=dict(default='present', choices=['present', 'absent']),
        realm=dict(type='str', default='master'),

        id=dict(type='str'),
        client_id=dict(type='str', aliases=['clientId']),
        name=dict(type='str'),
        description=dict(type='str'),
        root_url=dict(type='str', aliases=['rootUrl']),
        admin_url=dict(type='str', aliases=['adminUrl']),
        base_url=dict(type='str', aliases=['baseUrl']),
        surrogate_auth_required=dict(type='bool', aliases=['surrogateAuthRequired']),
        enabled=dict(type='bool'),
        client_authenticator_type=dict(type='str', choices=['client-secret', 'client-jwt'], aliases=['clientAuthenticatorType']),
        secret=dict(type='str', no_log=True),
        registration_access_token=dict(type='str', aliases=['registrationAccessToken']),
        default_roles=dict(type='list', aliases=['defaultRoles']),
        redirect_uris=dict(type='list', aliases=['redirectUris']),
        web_origins=dict(type='list', aliases=['webOrigins']),
        not_before=dict(type='int', aliases=['notBefore']),
        bearer_only=dict(type='bool', aliases=['bearerOnly']),
        consent_required=dict(type='bool', aliases=['consentRequired']),
        standard_flow_enabled=dict(type='bool', aliases=['standardFlowEnabled']),
        implicit_flow_enabled=dict(type='bool', aliases=['implicitFlowEnabled']),
        direct_access_grants_enabled=dict(type='bool', aliases=['directAccessGrantsEnabled']),
        service_accounts_enabled=dict(type='bool', aliases=['serviceAccountsEnabled']),
        authorization_services_enabled=dict(type='bool', aliases=['authorizationServicesEnabled']),
        public_client=dict(type='bool', aliases=['publicClient']),
        frontchannel_logout=dict(type='bool', aliases=['frontchannelLogout']),
        protocol=dict(type='str', choices=['openid-connect', 'saml']),
        attributes=dict(type='dict'),
        full_scope_allowed=dict(type='bool', aliases=['fullScopeAllowed']),
        node_re_registration_timeout=dict(type='int', aliases=['nodeReRegistrationTimeout']),
        registered_nodes=dict(type='dict', aliases=['registeredNodes']),
        client_template=dict(type='str', aliases=['clientTemplate']),
        use_template_config=dict(type='bool', aliases=['useTemplateConfig']),
        use_template_scope=dict(type='bool', aliases=['useTemplateScope']),
        use_template_mappers=dict(type='bool', aliases=['useTemplateMappers']),
        protocol_mappers=dict(type='list', elements='dict', options=protmapper_spec, aliases=['protocolMappers']),
        authorization_settings=dict(type='dict', aliases=['authorizationSettings']),
    )
    argument_spec.update(meta_args)

    module = AnsibleModule(argument_spec=argument_spec,
                           supports_check_mode=True,
                           required_one_of=([['client_id', 'id']]))

    result = dict(changed=False, msg='', diff={}, proposed={}, existing={}, end_state={})

    # Obtain access token, initialize API
    try:
        connection_header = get_token(
            base_url=module.params.get('auth_keycloak_url'),
            validate_certs=module.params.get('validate_certs'),
            auth_realm=module.params.get('auth_realm'),
            client_id=module.params.get('auth_client_id'),
            auth_username=module.params.get('auth_username'),
            auth_password=module.params.get('auth_password'),
            client_secret=module.params.get('auth_client_secret'),
        )
    except KeycloakError as e:
        module.fail_json(msg=str(e))

    kc = KeycloakAPI(module, connection_header)

    realm = module.params.get('realm')
    cid = module.params.get('id')
    state = module.params.get('state')

    # convert module parameters to client representation parameters (if they belong in there)
    client_params = [x for x in module.params
                     if x not in list(keycloak_argument_spec().keys()) + ['state', 'realm'] and
                     module.params.get(x) is not None]
    keycloak_argument_spec().keys()
    # See whether the client already exists in Keycloak
    if cid is None:
        before_client = kc.get_client_by_clientid(module.params.get('client_id'), realm=realm)
        if before_client is not None:
            cid = before_client['id']
    else:
        before_client = kc.get_client_by_id(cid, realm=realm)

    if before_client is None:
        before_client = dict()

    # Build a proposed changeset from parameters given to this module
    changeset = dict()

    for client_param in client_params:
        new_param_value = module.params.get(client_param)

        # some lists in the Keycloak API are sorted, some are not.
        if isinstance(new_param_value, list):
            if client_param in ['attributes']:
                try:
                    new_param_value = sorted(new_param_value)
                except TypeError:
                    pass
        # Unfortunately, the ansible argument spec checker introduces variables with null values when
        # they are not specified
        if client_param == 'protocol_mappers':
            new_param_value = [dict((k, v) for k, v in x.items() if x[k] is not None) for x in new_param_value]

        changeset[camel(client_param)] = new_param_value

    # Whether creating or updating a client, take the before-state and merge the changeset into it
    updated_client = before_client.copy()
    updated_client.update(changeset)

    result['proposed'] = sanitize_cr(changeset)
    result['existing'] = sanitize_cr(before_client)

    # If the client does not exist yet, before_client is still empty
    if before_client == dict():
        if state == 'absent':
            # do nothing and exit
            if module._diff:
                result['diff'] = dict(before='', after='')
            result['msg'] = 'Client does not exist, doing nothing.'
            module.exit_json(**result)

        # create new client
        result['changed'] = True
        if 'clientId' not in updated_client:
            module.fail_json(msg='client_id needs to be specified when creating a new client')

        if module._diff:
            result['diff'] = dict(before='', after=sanitize_cr(updated_client))

        if module.check_mode:
            module.exit_json(**result)

        kc.create_client(updated_client, realm=realm)
        after_client = kc.get_client_by_clientid(updated_client['clientId'], realm=realm)

        result['end_state'] = sanitize_cr(after_client)

        result['msg'] = 'Client %s has been created.' % updated_client['clientId']
        module.exit_json(**result)
    else:
        if state == 'present':
            # update existing client
            result['changed'] = True
            if module.check_mode:
                # We can only compare the current client with the proposed updates we have
                if module._diff:
                    result['diff'] = dict(before=sanitize_cr(before_client),
                                          after=sanitize_cr(updated_client))
                result['changed'] = (before_client != updated_client)

                module.exit_json(**result)

            kc.update_client(cid, updated_client, realm=realm)

            after_client = kc.get_client_by_id(cid, realm=realm)
            if before_client == after_client:
                result['changed'] = False
            if module._diff:
                result['diff'] = dict(before=sanitize_cr(before_client),
                                      after=sanitize_cr(after_client))
            result['end_state'] = sanitize_cr(after_client)

            result['msg'] = 'Client %s has been updated.' % updated_client['clientId']
            module.exit_json(**result)
        else:
            # Delete existing client
            result['changed'] = True
            if module._diff:
                result['diff']['before'] = sanitize_cr(before_client)
                result['diff']['after'] = ''

            if module.check_mode:
                module.exit_json(**result)

            kc.delete_client(cid, realm=realm)
            result['proposed'] = dict()
            result['end_state'] = dict()
            result['msg'] = 'Client %s has been deleted.' % before_client['clientId']
            module.exit_json(**result)

    module.exit_json(**result)
    def __init__(self):
        self._size_unit_map = dict(
            bytes=1,
            b=1,
            kb=1024,
            mb=1024 ** 2,
            gb=1024 ** 3,
            tb=1024 ** 4,
            pb=1024 ** 5,
            eb=1024 ** 6,
            zb=1024 ** 7,
            yb=1024 ** 8
        )

        self._post_headers = dict(Accept="application/json")
        self._post_headers['Content-Type'] = 'application/json'

        argument_spec = basic_auth_argument_spec()
        argument_spec.update(dict(
            state=dict(required=True, choices=['present', 'absent']),
            ssid=dict(required=True, type='str'),
            name=dict(required=True, type='str'),
            storage_pool_name=dict(type='str'),
            size_unit=dict(default='gb', choices=['bytes', 'b', 'kb', 'mb', 'gb', 'tb', 'pb', 'eb', 'zb', 'yb'],
                           type='str'),
            size=dict(type='int'),
            segment_size_kb=dict(default=128, choices=[8, 16, 32, 64, 128, 256, 512], type='int'),
            ssd_cache_enabled=dict(type='bool'),  # no default, leave existing setting alone
            data_assurance_enabled=dict(default=False, type='bool'),
            thin_provision=dict(default=False, type='bool'),
            thin_volume_repo_size=dict(type='int'),
            thin_volume_max_repo_size=dict(type='int'),
            # TODO: add cache, owning controller support, thin expansion policy, etc
            log_path=dict(type='str'),
            api_url=dict(type='str'),
            api_username=dict(type='str'),
            api_password=dict(type='str', no_log=True),
            validate_certs=dict(type='bool'),
        ))

        self.module = AnsibleModule(argument_spec=argument_spec,
                                    required_if=[
                                        ('state', 'present', ['storage_pool_name', 'size']),
                                        ('thin_provision', 'true', ['thin_volume_repo_size'])
                                    ],
                                    supports_check_mode=True)
        p = self.module.params

        log_path = p['log_path']

        # logging setup
        self._logger = logging.getLogger(self.__class__.__name__)
        self.debug = self._logger.debug

        if log_path:
            logging.basicConfig(level=logging.DEBUG, filename=log_path)

        self.state = p['state']
        self.ssid = p['ssid']
        self.name = p['name']
        self.storage_pool_name = p['storage_pool_name']
        self.size_unit = p['size_unit']
        self.size = p['size']
        self.segment_size_kb = p['segment_size_kb']
        self.ssd_cache_enabled = p['ssd_cache_enabled']
        self.data_assurance_enabled = p['data_assurance_enabled']
        self.thin_provision = p['thin_provision']
        self.thin_volume_repo_size = p['thin_volume_repo_size']
        self.thin_volume_max_repo_size = p['thin_volume_max_repo_size']

        if not self.thin_volume_max_repo_size:
            self.thin_volume_max_repo_size = self.size

        self.validate_certs = p['validate_certs']

        try:
            self.api_usr = p['api_username']
            self.api_pwd = p['api_password']
            self.api_url = p['api_url']
        except KeyError:
            self.module.fail_json(msg="You must pass in api_username "
                                      "and api_password and api_url to the module.")
def main():
    argument_spec = dict(
        key_id=dict(type='str'),
        md5string=dict(type='str'),
        auth_type=dict(choices=['text', 'encrypt'], default='text'),
        trusted_key=dict(choices=['true', 'false'], default='false'),
        authentication=dict(choices=['on', 'off']),
        state=dict(choices=['absent', 'present'], default='present'),
    )

    argument_spec.update(nxos_argument_spec)

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

    warnings = list()

    key_id = module.params['key_id']
    md5string = module.params['md5string']
    auth_type = module.params['auth_type']
    trusted_key = module.params['trusted_key']
    authentication = module.params['authentication']
    state = module.params['state']

    if key_id:
        if not trusted_key and not md5string:
            module.fail_json(msg='trusted_key or md5string MUST be specified')

    args = dict(key_id=key_id, md5string=md5string,
                auth_type=auth_type, trusted_key=trusted_key,
                authentication=authentication)

    changed = False
    proposed = dict((k, v) for k, v in args.items() if v is not None)

    existing = get_ntp_auth_info(key_id, module)
    end_state = existing

    delta = dict(set(proposed.items()).difference(existing.items()))

    commands = []
    if state == 'present':
        if delta:
            command = set_ntp_auth_key(
                key_id, md5string, delta.get('auth_type'),
                delta.get('trusted_key'), delta.get('authentication'))
            if command:
                commands.append(command)
    elif state == 'absent':
        auth_toggle = None
        if existing.get('authentication') == 'on':
            auth_toggle = True
        if not existing.get('key_id'):
            key_id = None
        command = remove_ntp_auth_key(
            key_id, md5string, auth_type, trusted_key, auth_toggle)
        if command:
            commands.append(command)

    cmds = flatten_list(commands)
    if cmds:
        if module.check_mode:
            module.exit_json(changed=True, commands=cmds)
        else:
            load_config(module, cmds)
            end_state = get_ntp_auth_info(key_id, module)
            delta = dict(set(end_state.items()).difference(existing.items()))
            if delta or (len(existing) != len(end_state)):
                changed = True
            if 'configure' in cmds:
                cmds.pop(0)

    results = {}
    results['proposed'] = proposed
    results['existing'] = existing
    results['updates'] = cmds
    results['changed'] = changed
    results['warnings'] = warnings
    results['end_state'] = end_state

    module.exit_json(**results)
Пример #20
0
def main():
    ''' Main entry point for module execution
    '''
    ipv4_spec = dict(
        address=dict(),
        subnet_mask=dict(),
        gateway=dict(),
    )

    ipv6_spec = dict(
        virtual_ip=dict(),
        cidr_prefix=dict(type='int'),
        gateway=dict(),
    )

    port_spec = dict(
        auto_port_setting_enabled=dict(type='bool'),
        duplex=dict(),
        speed=dict(),
    )

    lan2_port_spec = dict(
        enabled=dict(type='bool'),
        network_setting=dict(type='list', elements='dict', options=ipv4_spec),
        v6_network_setting=dict(type='list',
                                elements='dict',
                                options=ipv6_spec),
    )

    ha_port_spec = dict(
        ha_ip_address=dict(),
        ha_port_setting=dict(type='list', elements='dict', options=port_spec),
        lan_port_setting=dict(type='list', elements='dict', options=port_spec),
        mgmt_lan=dict(),
        mgmt_ipv6addr=dict(),
    )

    node_spec = dict(
        lan2_physical_setting=dict(type='list',
                                   elements='dict',
                                   options=port_spec),
        lan_ha_port_setting=dict(type='list',
                                 elements='dict',
                                 options=ha_port_spec),
        mgmt_network_setting=dict(type='list',
                                  elements='dict',
                                  options=ipv4_spec),
        v6_mgmt_network_setting=dict(type='list',
                                     elements='dict',
                                     options=ipv6_spec),
    )

    mgmt_port_spec = dict(
        enabled=dict(type='bool'),
        security_access_enabled=dict(type='bool'),
        vpn_enabled=dict(type='bool'),
    )

    syslog_spec = dict(
        address=dict(),
        category_list=dict(type='list'),
        connection_type=dict(default='UDP'),
        local_interface=dict(default='ANY'),
        message_node_id=dict(default='LAN'),
        message_source=dict(default='ANY'),
        only_category_list=dict(type='bool'),
        port=dict(type='int', default=514),
        severity=dict(default='DEBUG'),
    )

    hw_spec = dict(
        hwmodel=dict(),
        hwtype=dict(),
    )

    pre_prov_spec = dict(
        hardware_info=dict(type='list', elements='dict', options=hw_spec),
        licenses=dict(type='list'),
    )

    ib_spec = dict(
        host_name=dict(required=True, aliases=['name'], ib_req=True),
        vip_setting=dict(type='list', elements='dict', options=ipv4_spec),
        ipv6_setting=dict(type='list', elements='dict', options=ipv6_spec),
        config_addr_type=dict(default='IPV4'),
        comment=dict(),
        enable_ha=dict(type='bool', default=False),
        router_id=dict(type='int'),
        lan2_enabled=dict(type='bool', default=False),
        lan2_port_setting=dict(type='list',
                               elements='dict',
                               options=lan2_port_spec),
        platform=dict(default='INFOBLOX'),
        node_info=dict(type='list', elements='dict', options=node_spec),
        mgmt_port_setting=dict(type='list',
                               elements='dict',
                               options=mgmt_port_spec),
        upgrade_group=dict(default='Default'),
        use_syslog_proxy_setting=dict(type='bool'),
        external_syslog_server_enable=dict(type='bool'),
        syslog_servers=dict(type='list', elements='dict', options=syslog_spec),
        pre_provisioning=dict(type='list',
                              elements='dict',
                              options=pre_prov_spec),
        extattrs=dict(type='dict'),
        create_token=dict(type='bool', default=False),
    )

    argument_spec = dict(provider=dict(required=True),
                         state=dict(default='present',
                                    choices=['present', 'absent']))

    argument_spec.update(ib_spec)
    argument_spec.update(WapiModule.provider_spec)

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

    wapi = WapiModule(module)
    result = wapi.run(NIOS_MEMBER, ib_spec)
    module.exit_json(**result)
def main():
    module = AnsibleModule(argument_spec=get_argspec(),
                           supports_check_mode=True)
    result = run_command(module)
    module.exit_json(**result)
Пример #22
0
def main():
    argument_spec = pgutils.postgres_common_argument_spec()
    argument_spec.update(dict(
        db=dict(required=True, aliases=['name']),
        owner=dict(default=""),
        template=dict(default=""),
        encoding=dict(default=""),
        lc_collate=dict(default=""),
        lc_ctype=dict(default=""),
        state=dict(default="present", choices=["absent", "present"]),
    ))


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

    if not HAS_PSYCOPG2:
        module.fail_json(msg="the python psycopg2 module is required")

    db = module.params["db"]
    port = module.params["port"]
    owner = module.params["owner"]
    template = module.params["template"]
    encoding = module.params["encoding"]
    lc_collate = module.params["lc_collate"]
    lc_ctype = module.params["lc_ctype"]
    state = module.params["state"]
    sslrootcert = module.params["ssl_rootcert"]
    changed = False

    # To use defaults values, keyword arguments must be absent, so
    # check which values are empty and don't include in the **kw
    # dictionary
    params_map = {
        "login_host":"host",
        "login_user":"******",
        "login_password":"******",
        "port":"port",
        "ssl_mode":"sslmode",
        "ssl_rootcert":"sslrootcert"
    }
    kw = dict( (params_map[k], v) for (k, v) in iteritems(module.params)
              if k in params_map and v != '' and v is not None)

    # If a login_unix_socket is specified, incorporate it here.
    is_localhost = "host" not in kw or kw["host"] == "" or kw["host"] == "localhost"
    if is_localhost and module.params["login_unix_socket"] != "":
        kw["host"] = module.params["login_unix_socket"]

    try:
        pgutils.ensure_libs(sslrootcert=module.params.get('ssl_rootcert'))
        db_connection = psycopg2.connect(database="postgres", **kw)
        # Enable autocommit so we can create databases
        if psycopg2.__version__ >= '2.4.2':
            db_connection.autocommit = True
        else:
            db_connection.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
        cursor = db_connection.cursor(cursor_factory=psycopg2.extras.DictCursor)

    except pgutils.LibraryError:
        e = get_exception()
        module.fail_json(msg="unable to connect to database: {0}".format(str(e)), exception=traceback.format_exc())

    except TypeError:
        e = get_exception()
        if 'sslrootcert' in e.args[0]:
            module.fail_json(msg='Postgresql server must be at least version 8.4 to support sslrootcert. Exception: {0}'.format(e), exception=traceback.format_exc())
        module.fail_json(msg="unable to connect to database: %s" % e, exception=traceback.format_exc())

    except Exception:
        e = get_exception()
        module.fail_json(msg="unable to connect to database: %s" % e, exception=traceback.format_exc())

    try:
        if module.check_mode:
            if state == "absent":
                changed = db_exists(cursor, db)
            elif state == "present":
                changed = not db_matches(cursor, db, owner, template, encoding, lc_collate, lc_ctype)
            module.exit_json(changed=changed, db=db)

        if state == "absent":
            try:
                changed = db_delete(cursor, db)
            except SQLParseError:
                e = get_exception()
                module.fail_json(msg=str(e))

        elif state == "present":
            try:
                changed = db_create(cursor, db, owner, template, encoding, lc_collate, lc_ctype)
            except SQLParseError:
                e = get_exception()
                module.fail_json(msg=str(e))
    except NotSupportedError:
        e = get_exception()
        module.fail_json(msg=str(e))
    except SystemExit:
        # Avoid catching this on Python 2.4
        raise
    except Exception:
        e = get_exception()
        module.fail_json(msg="Database query failed: %s" % e)

    module.exit_json(changed=changed, db=db)
Пример #23
0
def main():
    helper = get_connection(
        vsys=True,
        device_group=True,
        rulebase=True,
        with_state=True,
        with_classic_provider_spec=True,
        error_on_firewall_shared=True,
        argument_spec=dict(
            rule_name=dict(required=True),
            source_zone=dict(type='list', elements='str', default=['any']),
            source_ip=dict(type='list', elements='str', default=["any"]),
            source_user=dict(type='list', elements='str', default=['any']),
            hip_profiles=dict(type='list', elements='str', default=['any']),
            destination_zone=dict(type='list', elements='str',
                                  default=['any']),
            destination_ip=dict(type='list', elements='str', default=["any"]),
            application=dict(type='list', elements='str', default=['any']),
            service=dict(type='list',
                         elements='str',
                         default=['application-default']),
            category=dict(type='list', elements='str', default=['any']),
            action=dict(
                default='allow',
                choices=[
                    'allow', 'deny', 'drop', 'reset-client', 'reset-server',
                    'reset-both'
                ],
            ),
            log_setting=dict(),
            log_start=dict(type='bool', default=False),
            log_end=dict(type='bool', default=True),
            description=dict(),
            rule_type=dict(default='universal',
                           choices=['universal', 'intrazone', 'interzone']),
            tag_name=dict(type='list', elements='str'),
            negate_source=dict(type='bool', default=False),
            negate_destination=dict(type='bool', default=False),
            disabled=dict(type='bool', default=False),
            schedule=dict(),
            icmp_unreachable=dict(type='bool'),
            disable_server_response_inspection=dict(type='bool',
                                                    default=False),
            group_profile=dict(),
            antivirus=dict(),
            spyware=dict(),
            vulnerability=dict(),
            url_filtering=dict(),
            file_blocking=dict(),
            wildfire_analysis=dict(),
            data_filtering=dict(),
            target=dict(type='list', elements='str'),
            negate_target=dict(type='bool'),
            location=dict(choices=['top', 'bottom', 'before', 'after']),
            existing_rule=dict(),
            commit=dict(type='bool', default=False),

            # TODO(gfreeman) - remove this in the next role release.
            devicegroup=dict(),
        ),
    )
    module = AnsibleModule(
        argument_spec=helper.argument_spec,
        supports_check_mode=True,
        required_one_of=helper.required_one_of,
    )

    # TODO(gfreeman) - remove when devicegroup is removed.
    if module.params['devicegroup'] is not None:
        module.deprecate(
            'Param "devicegroup" is deprecated; use "device_group"',
            version='3.0.0',
            collection_name='paloaltonetworks.panos')
        if module.params['device_group'] is not None:
            msg = [
                'Both "devicegroup" and "device_group" are specified',
                'Specify one or the other, not both.',
            ]
            module.fail_json(msg='. '.join(msg))
        module.params['device_group'] = module.params['devicegroup']

    # Verify imports, build pandevice object tree.
    parent = helper.get_pandevice_parent(module)

    # Set the SecurityRule object params.
    rule_spec = {
        'name':
        module.params['rule_name'],
        'fromzone':
        module.params['source_zone'],
        'tozone':
        module.params['destination_zone'],
        'source':
        module.params['source_ip'],
        'source_user':
        module.params['source_user'],
        'hip_profiles':
        module.params['hip_profiles'],
        'destination':
        module.params['destination_ip'],
        'application':
        module.params['application'],
        'service':
        module.params['service'],
        'category':
        module.params['category'],
        'action':
        module.params['action'],
        'log_setting':
        module.params['log_setting'],
        'log_start':
        module.params['log_start'],
        'log_end':
        module.params['log_end'],
        'description':
        module.params['description'],
        'type':
        module.params['rule_type'],
        'tag':
        module.params['tag_name'],
        'negate_source':
        module.params['negate_source'],
        'negate_destination':
        module.params['negate_destination'],
        'disabled':
        module.params['disabled'],
        'schedule':
        module.params['schedule'],
        'icmp_unreachable':
        module.params['icmp_unreachable'],
        'disable_server_response_inspection':
        module.params['disable_server_response_inspection'],
        'group':
        module.params['group_profile'],
        'virus':
        module.params['antivirus'],
        'spyware':
        module.params['spyware'],
        'vulnerability':
        module.params['vulnerability'],
        'url_filtering':
        module.params['url_filtering'],
        'file_blocking':
        module.params['file_blocking'],
        'wildfire_analysis':
        module.params['wildfire_analysis'],
        'data_filtering':
        module.params['data_filtering'],
        'target':
        module.params['target'],
        'negate_target':
        module.params['negate_target'],
    }

    # Other module info.
    location = module.params['location']
    existing_rule = module.params['existing_rule']
    commit = module.params['commit']

    # Retrieve the current rules.
    try:
        rules = SecurityRule.refreshall(parent, add=False)
    except PanDeviceError as e:
        module.fail_json(msg='Failed refresh: {0}'.format(e))

    # Create new rule object from the params.
    new_rule = SecurityRule(**rule_spec)
    parent.add(new_rule)

    # Which action shall we take on the rule object?
    changed, diff = helper.apply_state(new_rule, rules, module)

    # Move the rule to the correct spot, if applicable.
    if module.params['state'] == 'present':
        changed |= helper.apply_position(new_rule, location, existing_rule,
                                         module)

    # Optional commit.
    if changed and commit:
        helper.commit(module)

    # Done.
    module.exit_json(changed=changed, diff=diff, msg='Done')
Пример #24
0
def main():
    argument_spec = ovirt_full_argument_spec(
        state=dict(
            choices=['running', 'stopped', 'present', 'absent', 'suspended', 'next_run'],
            default='present',
        ),
        name=dict(default=None),
        id=dict(default=None),
        cluster=dict(default=None),
        template=dict(default=None),
        template_version=dict(default=None, type='int'),
        use_latest_template_version=dict(default=None, type='bool'),
        disks=dict(default=[], type='list'),
        memory=dict(default=None),
        memory_guaranteed=dict(default=None),
        cpu_sockets=dict(default=None, type='int'),
        cpu_cores=dict(default=None, type='int'),
        cpu_shares=dict(default=None, type='int'),
        type=dict(choices=['server', 'desktop']),
        operating_system=dict(
            default=None,
            choices=[
                'rhel_6_ppc64', 'other', 'freebsd', 'windows_2003x64', 'windows_10',
                'rhel_6x64', 'rhel_4x64', 'windows_2008x64', 'windows_2008R2x64',
                'debian_7', 'windows_2012x64', 'ubuntu_14_04', 'ubuntu_12_04',
                'ubuntu_13_10', 'windows_8x64', 'other_linux_ppc64', 'windows_2003',
                'other_linux', 'windows_10x64', 'windows_2008', 'rhel_3', 'rhel_5',
                'rhel_4', 'other_ppc64', 'sles_11', 'rhel_6', 'windows_xp', 'rhel_7x64',
                'freebsdx64', 'rhel_7_ppc64', 'windows_7', 'rhel_5x64',
                'ubuntu_14_04_ppc64', 'sles_11_ppc64', 'windows_8',
                'windows_2012R2x64', 'windows_2008r2x64', 'ubuntu_13_04',
                'ubuntu_12_10', 'windows_7x64',
            ],
        ),
        cd_iso=dict(default=None),
        boot_devices=dict(default=None, type='list'),
        high_availability=dict(type='bool'),
        stateless=dict(type='bool'),
        delete_protected=dict(type='bool'),
        force=dict(type='bool', default=False),
        nics=dict(default=[], type='list'),
        cloud_init=dict(type='dict'),
        cloud_init_nics=dict(defaul=[], type='list'),
        sysprep=dict(type='dict'),
        host=dict(default=None),
        clone=dict(type='bool', default=False),
        clone_permissions=dict(type='bool', default=False),
        kernel_path=dict(default=None),
        initrd_path=dict(default=None),
        kernel_params=dict(default=None),
        instance_type=dict(default=None),
        description=dict(default=None),
        comment=dict(default=None),
        timezone=dict(default=None),
        serial_policy=dict(default=None, choices=['vm', 'host', 'custom']),
        serial_policy_value=dict(default=None),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    check_sdk(module)
    check_params(module)

    try:
        state = module.params['state']
        connection = create_connection(module.params.pop('auth'))
        vms_service = connection.system_service().vms_service()
        vms_module = VmsModule(
            connection=connection,
            module=module,
            service=vms_service,
        )
        vm = vms_module.search_entity()

        control_state(vm, vms_service, module)
        if state == 'present' or state == 'running' or state == 'next_run':
            sysprep = module.params['sysprep']
            cloud_init = module.params['cloud_init']
            cloud_init_nics = module.params['cloud_init_nics'] or []
            if cloud_init is not None:
                cloud_init_nics.append(cloud_init)

            # In case VM don't exist, wait for VM DOWN state,
            # otherwise don't wait for any state, just update VM:
            vms_module.create(
                entity=vm,
                result_state=otypes.VmStatus.DOWN if vm is None else None,
                clone=module.params['clone'],
                clone_permissions=module.params['clone_permissions'],
            )
            ret = vms_module.action(
                action='start',
                post_action=vms_module._post_start_action,
                action_condition=lambda vm: (
                    vm.status not in [
                        otypes.VmStatus.MIGRATING,
                        otypes.VmStatus.POWERING_UP,
                        otypes.VmStatus.REBOOT_IN_PROGRESS,
                        otypes.VmStatus.WAIT_FOR_LAUNCH,
                        otypes.VmStatus.UP,
                        otypes.VmStatus.RESTORING_STATE,
                    ]
                ),
                wait_condition=lambda vm: vm.status == otypes.VmStatus.UP,
                # Start action kwargs:
                use_cloud_init=cloud_init is not None or len(cloud_init_nics) > 0,
                use_sysprep=sysprep is not None,
                vm=otypes.Vm(
                    placement_policy=otypes.VmPlacementPolicy(
                        hosts=[otypes.Host(name=module.params['host'])]
                    ) if module.params['host'] else None,
                    initialization=_get_initialization(sysprep, cloud_init, cloud_init_nics),
                    os=otypes.OperatingSystem(
                        cmdline=module.params.get('kernel_params'),
                        initrd=module.params.get('initrd_path'),
                        kernel=module.params.get('kernel_path'),
                    ),
                ),
            )

            if state == 'next_run':
                # Apply next run configuration, if needed:
                vm = vms_service.vm_service(ret['id']).get()
                if vm.next_run_configuration_exists:
                    ret = vms_module.action(
                        action='reboot',
                        entity=vm,
                        action_condition=lambda vm: vm.status == otypes.VmStatus.UP,
                        wait_condition=lambda vm: vm.status == otypes.VmStatus.UP,
                    )
        elif state == 'stopped':
            vms_module.create(
                result_state=otypes.VmStatus.DOWN if vm is None else None,
                clone=module.params['clone'],
                clone_permissions=module.params['clone_permissions'],
            )
            if module.params['force']:
                ret = vms_module.action(
                    action='stop',
                    post_action=vms_module._attach_cd,
                    action_condition=lambda vm: vm.status != otypes.VmStatus.DOWN,
                    wait_condition=lambda vm: vm.status == otypes.VmStatus.DOWN,
                )
            else:
                ret = vms_module.action(
                    action='shutdown',
                    pre_action=vms_module._pre_shutdown_action,
                    post_action=vms_module._attach_cd,
                    action_condition=lambda vm: vm.status != otypes.VmStatus.DOWN,
                    wait_condition=lambda vm: vm.status == otypes.VmStatus.DOWN,
                )
        elif state == 'suspended':
            vms_module.create(
                result_state=otypes.VmStatus.DOWN if vm is None else None,
                clone=module.params['clone'],
                clone_permissions=module.params['clone_permissions'],
            )
            ret = vms_module.action(
                action='suspend',
                pre_action=vms_module._pre_suspend_action,
                action_condition=lambda vm: vm.status != otypes.VmStatus.SUSPENDED,
                wait_condition=lambda vm: vm.status == otypes.VmStatus.SUSPENDED,
            )
        elif state == 'absent':
            ret = vms_module.remove()

        module.exit_json(**ret)
    except Exception as e:
        module.fail_json(msg=str(e), exception=traceback.format_exc())
    finally:
        connection.close(logout=False)
Пример #25
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))

        module.preserved_copy(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))
            module.preserved_copy(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)
Пример #26
0
def main():

    argspec = dict(state=dict(required=True,
                              choices=["present", "absent"],
                              type="str"),
                   id=dict(required=False, type="int"),
                   name=dict(required=False, type="str"),
                   ip_address=dict(required=False, type="str"),
                   address_version=dict(required=False,
                                        choices=["ipv4", "ipv6"],
                                        type="str",
                                        default="ipv4"),
                   type=dict(required=False,
                             choices=["ipaddress", "group"],
                             type="str",
                             default="ipaddress"),
                   members=dict(required=False, type="list", elements="str"))

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

    space_request = SpaceRequest(module, )
    sd_address_manager = SDAddressMgr(module, )

    # Gather address details to determine if address exists
    if module.params["id"]:
        address = sd_address_manager.get_address_by_id(module.params["id"])
    elif module.params["name"]:
        address = sd_address_manager.get_address(name=module.params["name"])
    else:
        module.fail_json(msg='You must provide either an id or a name')

    if to_text(module.params["state"]) == "present":
        #check params
        if not module.params["name"]:
            module.fail_json(msg='You must provide a name')
        elif not module.params["ip_address"] and not module.params[
                "type"] == "group":  #only require IP addres if this isn't a group
            module.fail_json(msg='You must provide an IP address')

        if module.params[
                "type"] == "group" and module.params["members"] is None:
            module.fail_json(
                msg=
                'You must provide at least one member if the address type is GROUP'
            )

        space_request.headers = {
            "Accept": "application/json",
            "Content-Type": "application/json"
        }

        # Create the address body
        body = dict(
            address={
                "definition_type": "CUSTOM",
                "associated_metadata": "",
                "name": module.params["name"],
                "description": "",
                "address_type": module.params["type"].upper(),
                "address_version": module.params["address_version"].upper(),
                "host_name": ""
            })

        # Add member-refs if necessary
        if module.params["type"] == "group":
            address_refs = []
            for member in module.params["members"]:
                response = sd_address_manager.get_address(name=member)
                if response is not None:
                    # address_refs.append(dict(name=response[0]['name'], uuid=response[0]['uuid']))
                    response[0].pop('uri', None)
                    address_refs.append(response[0])
                else:
                    module.fail_json(msg="Could not find member with name: {}".
                                     format(member))
            body['address']['address_refs'] = address_refs
        else:
            # only set ip_address key if this isn't a group
            body['address']['ip_address'] = module.params["ip_address"]

        # Logic for changing an existing address
        if address:
            # make a copy
            patch_address = dict(address=address[0].copy())

            #update the patch with the prepared body
            patch_address['address'].update(body['address'])

            #compare for differences
            if address[0] == patch_address['address']:
                module.exit_json(msg='Address already up to date',
                                 address=address[0],
                                 changed=False)
            else:
                code, response = space_request.put(
                    "/api/juniper/sd/address-management/v5/address/{0}".format(
                        address[0]["uuid"]),
                    payload=json.dumps(patch_address))

                module.exit_json(msg='Address updated',
                                 address=response['address'],
                                 changed=True)

            if address[0]["address-type"] == "GROUP":
                for member in body["address"]["address_refs"]:
                    if not any(d["uuid"] == member["uuid"] for d in a):
                        pass  # update body with edit-version and set method to PUT

            module.exit_json(msg='Address already present',
                             address=address[0],
                             changed=False)

        code, response = space_request.post(
            "/api/juniper/sd/address-management/v5/address",
            payload=json.dumps(body))

        module.exit_json(address=response['address'], changed=True)

    elif module.params["state"] == "absent":
        if not address:
            module.exit_json(msg="Address already absent",
                             address=address,
                             changed=False)
        else:
            space_request.headers = {
                "Accept":
                "application/vnd.net.juniper.space.address-management.address+json;version=1"
            }
            space_request.expect_json = False

            code, response = space_request.delete(
                "/api/juniper/sd/address-management/addresses/{0}".format(
                    address[0]["uuid"]),
                status_codes="204, 500")

            if code == 204:
                module.exit_json(changed=True)
            elif code == 500:
                module.fail_json(
                    msg=
                    "Could not delete the address. Most likely it is in use by another group or policy.",
                    response=response)
Пример #27
0
def main():
    argument_spec = postgres_common_argument_spec()
    argument_spec.update(
        name=dict(required=True),
        db=dict(type='str', aliases=['login_db']),
        connection=dict(required=True, type='str'),
        state=dict(type='str',
                   default='present',
                   choices=['absent', 'present']),
        publication=dict(type='list', required=True),
        #todo add another arguments
        #tables=dict(type='list'),
        parameters=dict(type='dict'),
        owner=dict(type='str'),
        #cascade=dict(type='bool', default=False),
    )
    module = AnsibleModule(
        argument_spec=argument_spec,
        supports_check_mode=True,
    )
    pprint.pprint('temp log: start')
    pprint.pprint('temp log: module:' + str(module))

    # Parameters handling:
    name = module.params['name']
    state = module.params['state']
    connection = module.params['connection']
    publication = module.params['publication']
    params = module.params['parameters']
    owner = module.params['owner']

    # todo add checks
    #tables = module.params['tables']
    #params = module.params['parameters']
    #owner = module.params['owner']
    #cascade = module.params['cascade']

    #if state == 'absent':
    #    if tables:
    #        module.warn('parameter "tables" is ignored when "state=absent"')
    #    if params:
    #        module.warn('parameter "parameters" is ignored when "state=absent"')
    #    if owner:
    #        module.warn('parameter "owner" is ignored when "state=absent"')

    #if state == 'present' and cascade:
    #    module.warm('parameter "cascade" is ignored when "state=present"')

    # Connect to DB and make cursor object:
    conn_params = get_conn_params(module, module.params)
    # We check publication state without DML queries execution, so set autocommit:
    db_connection = connect_to_db(module, conn_params, autocommit=True)
    cursor = db_connection.cursor(cursor_factory=DictCursor)

    # Check version:
    if cursor.connection.server_version < SUPPORTED_PG_VERSION:
        module.fail_json(
            msg="PostgreSQL server version should be 10.0 or greater")

    # Nothing was changed by default:
    changed = False

    ###################################
    # Create object and do rock'n'roll:
    subscription = PgSubscription(module, cursor, name, connection,
                                  publication)

    #if tables:
    #    tables = transform_tables_representation(tables)
    pprint.pprint('temp log: module.check_mode' + str(module.check_mode))

    # If module.check_mode=True, nothing will be changed:
    if state == 'present':
        if not subscription.exists:
            changed = subscription.create(params,
                                          owner,
                                          check_mode=module.check_mode)

        else:
            changed = publication.update(tables,
                                         params,
                                         owner,
                                         check_mode=module.check_mode)

    elif state == 'absent':
        changed = publication.drop(cascade=cascade,
                                   check_mode=module.check_mode)

    # Get final publication info:
    pub_fin_info = {}
    if state != 'absent' or (state == 'absent' and module.check_mode):
        pub_fin_info = publication.get_info()
    elif state == 'absent' and not module.check_mode:
        publication.exists = False

    # Connection is not needed any more:
    cursor.close()
    db_connection.close()

    # Update publication info and return ret values:
    module.exit_json(changed=changed,
                     queries=publication.executed_queries,
                     exists=publication.exists,
                     **pub_fin_info)
def main():
    mkeyname = 'name'
    fields = {
        "access_token": {"required": False, "type": "str", "no_log": True},
        "vdom": {"required": False, "type": "str", "default": "root"},
        "state": {"required": False, "type": "str",
                  "choices": ["present", "absent"]},
        "firewall_ssh_host_key": {
            "required": False, "type": "dict", "default": None,
            "options": {
                "state": {"required": False, "type": "str",
                          "choices": ["present", "absent"]},
                "hostname": {"required": False, "type": "str"},
                "ip": {"required": False, "type": "str"},
                "name": {"required": True, "type": "str"},
                "nid": {"required": False, "type": "str",
                        "choices": ["256",
                                    "384",
                                    "521"]},
                "port": {"required": False, "type": "int"},
                "public_key": {"required": False, "type": "str"},
                "status": {"required": False, "type": "str",
                           "choices": ["trusted",
                                       "revoked"]},
                "type": {"required": False, "type": "str",
                         "choices": ["RSA",
                                     "DSA",
                                     "ECDSA",
                                     "ED25519",
                                     "RSA-CA",
                                     "DSA-CA",
                                     "ECDSA-CA",
                                     "ED25519-CA"]}

            }
        }
    }

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

    versions_check_result = None
    if module._socket_path:
        connection = Connection(module._socket_path)
        if 'access_token' in module.params:
            connection.set_option('access_token', module.params['access_token'])

        fos = FortiOSHandler(connection, module, mkeyname)

        is_error, has_changed, result = fortios_firewall_ssh(module.params, fos)
        versions_check_result = connection.get_system_version()
    else:
        module.fail_json(**FAIL_SOCKET_MSG)

    if versions_check_result and versions_check_result['matched'] is False:
        module.warn("Ansible has detected version mismatch between FortOS system and galaxy, see more details by specifying option -vvv")

    if not is_error:
        if versions_check_result and versions_check_result['matched'] is False:
            module.exit_json(changed=has_changed, version_check_warning=versions_check_result, meta=result)
        else:
            module.exit_json(changed=has_changed, meta=result)
    else:
        if versions_check_result and versions_check_result['matched'] is False:
            module.fail_json(msg="Error in repo", version_check_warning=versions_check_result, meta=result)
        else:
            module.fail_json(msg="Error in repo", meta=result)
Пример #29
0
def main():

    module = AnsibleModule(
        argument_spec=dict(
            account_key=dict(required=True, no_log=True),
            account_secret=dict(required=True, no_log=True),
            domain=dict(required=True),
            sandbox=dict(default=False, type='bool'),
            state=dict(required=True, choices=['present', 'absent']),
            record_name=dict(required=False),
            record_type=dict(required=False, choices=[
                             'A', 'AAAA', 'CNAME', 'ANAME', 'HTTPRED', 'MX', 'NS', 'PTR', 'SRV', 'TXT']),
            record_value=dict(required=False),
            record_ttl=dict(required=False, default=1800, type='int'),
            monitor=dict(default=False, type='bool'),
            systemDescription=dict(default=''),
            maxEmails=dict(default=1, type='int'),
            protocol=dict(default='HTTP', choices=['TCP', 'UDP', 'HTTP', 'DNS', 'SMTP', 'HTTPS']),
            port=dict(default=80, type='int'),
            sensitivity=dict(default='Medium', choices=['Low', 'Medium', 'High']),
            contactList=dict(default=None),
            httpFqdn=dict(required=False),
            httpFile=dict(required=False),
            httpQueryString=dict(required=False),
            failover=dict(default=False, type='bool'),
            autoFailover=dict(default=False, type='bool'),
            ip1=dict(required=False),
            ip2=dict(required=False),
            ip3=dict(required=False),
            ip4=dict(required=False),
            ip5=dict(required=False),
            validate_certs=dict(default=True, type='bool'),
        ),
        required_together=[
            ['record_value', 'record_ttl', 'record_type']
        ],
        required_if=[
            ['failover', True, ['autoFailover', 'port', 'protocol', 'ip1', 'ip2']],
            ['monitor', True, ['port', 'protocol', 'maxEmails', 'systemDescription', 'ip1']]
        ]
    )

    protocols = dict(TCP=1, UDP=2, HTTP=3, DNS=4, SMTP=5, HTTPS=6)
    sensitivities = dict(Low=8, Medium=5, High=3)

    DME = DME2(module.params["account_key"], module.params[
               "account_secret"], module.params["domain"], module.params["sandbox"], module)
    state = module.params["state"]
    record_name = module.params["record_name"]
    record_type = module.params["record_type"]
    record_value = module.params["record_value"]

    # Follow Keyword Controlled Behavior
    if record_name is None:
        domain_records = DME.getRecords()
        if not domain_records:
            module.fail_json(
                msg="The requested domain name is not accessible with this api_key; try using its ID if known.")
        module.exit_json(changed=False, result=domain_records)

    # Fetch existing record + Build new one
    current_record = DME.getMatchingRecord(record_name, record_type, record_value)
    new_record = {'name': record_name}
    for i in ["record_value", "record_type", "record_ttl"]:
        if not module.params[i] is None:
            new_record[i[len("record_"):]] = module.params[i]
    # Special handling for mx record
    if new_record["type"] == "MX":
        new_record["mxLevel"] = new_record["value"].split(" ")[0]
        new_record["value"] = new_record["value"].split(" ")[1]

    # Special handling for SRV records
    if new_record["type"] == "SRV":
        new_record["priority"] = new_record["value"].split(" ")[0]
        new_record["weight"] = new_record["value"].split(" ")[1]
        new_record["port"] = new_record["value"].split(" ")[2]
        new_record["value"] = new_record["value"].split(" ")[3]

    # Fetch existing monitor if the A record indicates it should exist and build the new monitor
    current_monitor = dict()
    new_monitor = dict()
    if current_record and current_record['type'] == 'A' and current_record.get('monitor'):
        current_monitor = DME.getMonitor(current_record['id'])

    # Build the new monitor
    for i in ['monitor', 'systemDescription', 'protocol', 'port', 'sensitivity', 'maxEmails',
              'contactList', 'httpFqdn', 'httpFile', 'httpQueryString',
              'failover', 'autoFailover', 'ip1', 'ip2', 'ip3', 'ip4', 'ip5']:
        if module.params[i] is not None:
            if i == 'protocol':
                # The API requires protocol to be a numeric in the range 1-6
                new_monitor['protocolId'] = protocols[module.params[i]]
            elif i == 'sensitivity':
                # The API requires sensitivity to be a numeric of 8, 5, or 3
                new_monitor[i] = sensitivities[module.params[i]]
            elif i == 'contactList':
                # The module accepts either the name or the id of the contact list
                contact_list_id = module.params[i]
                if not contact_list_id.isdigit() and contact_list_id != '':
                    contact_list = DME.getContactListByName(contact_list_id)
                    if not contact_list:
                        module.fail_json(msg="Contact list {0} does not exist".format(contact_list_id))
                    contact_list_id = contact_list.get('id', '')
                new_monitor['contactListId'] = contact_list_id
            else:
                # The module option names match the API field names
                new_monitor[i] = module.params[i]

    # Compare new record against existing one
    record_changed = False
    if current_record:
        for i in new_record:
            # Remove leading and trailing quote character from values because TXT records
            # are surrounded by quotes.
            if str(current_record[i]).strip('"') != str(new_record[i]):
                record_changed = True
        new_record['id'] = str(current_record['id'])

    monitor_changed = False
    if current_monitor:
        for i in new_monitor:
            if str(current_monitor.get(i)) != str(new_monitor[i]):
                monitor_changed = True

    # Follow Keyword Controlled Behavior
    if state == 'present':
        # return the record if no value is specified
        if "value" not in new_record:
            if not current_record:
                module.fail_json(
                    msg="A record with name '%s' does not exist for domain '%s.'" % (record_name, module.params['domain']))
            module.exit_json(changed=False, result=dict(record=current_record, monitor=current_monitor))

        # create record and monitor as the record does not exist
        if not current_record:
            record = DME.createRecord(DME.prepareRecord(new_record))
            if new_monitor.get('monitor') and record_type == "A":
                monitor = DME.updateMonitor(record['id'], DME.prepareMonitor(new_monitor))
                module.exit_json(changed=True, result=dict(record=record, monitor=monitor))
            else:
                module.exit_json(changed=True, result=dict(record=record, monitor=current_monitor))

        # update the record
        updated = False
        if record_changed:
            DME.updateRecord(current_record['id'], DME.prepareRecord(new_record))
            updated = True
        if monitor_changed:
            DME.updateMonitor(current_monitor['recordId'], DME.prepareMonitor(new_monitor))
            updated = True
        if updated:
            module.exit_json(changed=True, result=dict(record=new_record, monitor=new_monitor))

        # return the record (no changes)
        module.exit_json(changed=False, result=dict(record=current_record, monitor=current_monitor))

    elif state == 'absent':
        changed = False
        # delete the record (and the monitor/failover) if it exists
        if current_record:
            DME.deleteRecord(current_record['id'])
            module.exit_json(changed=True)

        # record does not exist, return w/o change.
        module.exit_json(changed=changed)

    else:
        module.fail_json(
            msg="'%s' is an unknown value for the state argument" % state)
Пример #30
0
def main():
    argument_spec = dict(
        local_file=dict(type='str'),
        remote_file=dict(type='str'),
        file_system=dict(required=False, default='bootflash:'),
        connect_ssh_port=dict(required=False, type='int', default=22),
        file_pull=dict(type='bool', default=False),
        file_pull_timeout=dict(type='int', default=300),
        local_file_directory=dict(required=False, type='str'),
        remote_scp_server=dict(type='str'),
        remote_scp_server_user=dict(type='str'),
        remote_scp_server_password=dict(no_log=True),
    )

    argument_spec.update(nxos_argument_spec)

    required_if = [("file_pull", True, ["remote_file", "remote_scp_server"]),
                   ("file_pull", False, ["local_file"])]

    required_together = [['remote_scp_server',
                          'remote_scp_server_user',
                          'remote_scp_server_password']]

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

    file_pull = module.params['file_pull']

    if file_pull:
        if not HAS_PEXPECT:
            module.fail_json(
                msg='library pexpect is required when file_pull is True but does not appear to be '
                    'installed. It can be installed using `pip install pexpect`'
            )
    else:
        if not HAS_PARAMIKO:
            module.fail_json(
                msg='library paramiko is required when file_pull is False but does not appear to be '
                    'installed. It can be installed using `pip install paramiko`'
            )

        if not HAS_SCP:
            module.fail_json(
                msg='library scp is required when file_pull is False but does not appear to be '
                    'installed. It can be installed using `pip install scp`'
            )
    warnings = list()
    check_args(module, warnings)
    results = dict(changed=False, warnings=warnings)

    local_file = module.params['local_file']
    remote_file = module.params['remote_file']
    file_system = module.params['file_system']
    local_file_directory = module.params['local_file_directory']

    results['transfer_status'] = 'No Transfer'
    results['file_system'] = file_system

    if file_pull:
        src = remote_file.split('/')[-1]
        local = local_file or src

        if not module.check_mode:
            copy_file_from_remote(module, local, local_file_directory, file_system=file_system)
            results['transfer_status'] = 'Received'

        results['changed'] = True
        results['remote_file'] = src
        results['local_file'] = local
    else:
        if not local_file_exists(module):
            module.fail_json(msg="Local file {0} not found".format(local_file))

        dest = remote_file or os.path.basename(local_file)
        remote_exists = remote_file_exists(module, dest, file_system=file_system)

        if not remote_exists:
            results['changed'] = True
            file_exists = False
        else:
            file_exists = True

        if not module.check_mode and not file_exists:
            transfer_file_to_device(module, dest)
            results['transfer_status'] = 'Sent'

        results['local_file'] = local_file
        if remote_file is None:
            remote_file = os.path.basename(local_file)
        results['remote_file'] = remote_file

    module.exit_json(**results)