def main(): argument_spec = cs_argument_spec() argument_spec.update(dict( name=dict(required=True), ip_address=dict(aliases=['public_ip']), vms=dict(required=True, aliases=['vm'], type='list'), state=dict(choices=['present', 'absent'], default='present'), zone=dict(), domain=dict(), project=dict(), account=dict(), poll_async=dict(type='bool', default=True), )) module = AnsibleModule( argument_spec=argument_spec, required_together=cs_required_together(), supports_check_mode=True ) acs_lb_rule_member = AnsibleCloudStackLBRuleMember(module) state = module.params.get('state') if state in ['absent']: rule = acs_lb_rule_member.remove_members() else: rule = acs_lb_rule_member.add_members() result = acs_lb_rule_member.get_result(rule) module.exit_json(**result)
def main(): module = AnsibleModule( argument_spec = dict( recipe = dict(required=True, type='str'), username = dict(required=True, type='str'), password = dict(required=True, type='str'), hostname = dict(default="127.0.0.1", type="str"), port = dict(default=80, type="int") ) ) xos_auth=(module.params['username'], module.params['password']) url = "http://%s:%d/api/utility/tosca/run/" % (module.params['hostname'], module.params['port']) r = requests.post(url, data={"recipe": module.params['recipe']}, auth=xos_auth) if (r.status_code != 200): try: error_text=r.json()["error_text"] except: error_text="error while formatting the error: " + traceback.format_exc() module.fail_json(msg=error_text, rc=r.status_code) result = r.json() if "log_msgs" in result: module.exit_json(changed=True, msg="\n".join(result["log_msgs"])+"\n") else: module.exit_json(changed=True, msg="success")
def main(): module = AnsibleModule( argument_spec=dict( state=dict(default='present', choices=['present', 'absent']), name=dict(required=True), repo=dict(default='https://cran.rstudio.com/') ) ) state = module.params['state'] name = module.params['name'] changed = False version = get_installed_version(module) if state == 'present' and not version: stderr = install(module) version = get_installed_version(module) if not version: module.fail_json( msg='Failed to install {name:}: {err:}'.format( name=name, err=stderr, version=version)) changed = True elif state == 'absent' and version: stderr = uninstall(module) version = get_installed_version(module) if version: module.fail_json( msg='Failed to install {name:}: {err:}'.format( name=name, err=stderr)) changed = True module.exit_json(changed=changed, name=name, version=version)
def main(): module = AnsibleModule( argument_spec=dict( host=dict( required=True, type='str', ), path=dict( required=True, type='str', ), proto=dict( required=True, choices=['ssh', 'ssl'], ), ), supports_check_mode=False, ) host = module.params.get('host') path = module.params.get('path') proto = module.params.get('proto') with open(path, 'r') as src: result = { 'type': 'sign_request', 'request': { 'keyType': '{}_host'.format(proto), 'hostName': host, 'keyData': src.read().replace('\n', ''), }, } module.exit_json(**result)
def main(): argument_spec = vmware_argument_spec() argument_spec.update(dict(vmk_name=dict(required=True, type='str'), ip_address=dict(required=True, type='str'), subnet_mask=dict(required=True, type='str'))) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) if not HAS_PYVMOMI: module.fail_json(msg='pyvmomi is required for this module') vmk_name = module.params['vmk_name'] ip_address = module.params['ip_address'] subnet_mask = module.params['subnet_mask'] try: content = connect_to_api(module, False) host = get_all_objs(content, [vim.HostSystem]) if not host: module.fail_json(msg="Unable to locate Physical Host.") host_system = host.keys()[0] changed = configure_vmkernel_ip_address(host_system, vmk_name, ip_address, subnet_mask) module.exit_json(changed=changed) except vmodl.RuntimeFault as runtime_fault: module.fail_json(msg=runtime_fault.msg) except vmodl.MethodFault as method_fault: module.fail_json(msg=method_fault.msg) except Exception as e: module.fail_json(msg=str(e))
def main(): """main entry point for module execution """ argument_spec = dict( commands=dict(type='list', required=True), wait_for=dict(type='list', aliases=['waitfor']), match=dict(default='all', choices=['all', 'any']), retries=dict(default=10, type='int'), interval=dict(default=1, type='int') ) argument_spec.update(ios_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) result = {'changed': False} warnings = list() check_args(module, warnings) commands = parse_commands(module, warnings) result['warnings'] = warnings wait_for = module.params['wait_for'] or list() conditionals = [Conditional(c) for c in wait_for] retries = module.params['retries'] interval = module.params['interval'] match = module.params['match'] while retries > 0: responses = run_commands(module, commands) for item in list(conditionals): if item(responses): if match == 'any': conditionals = list() break conditionals.remove(item) if not conditionals: break time.sleep(interval) retries -= 1 if conditionals: failed_conditions = [item.raw for item in conditionals] msg = 'One or more conditional statements have not been satisfied' module.fail_json(msg=msg, failed_conditions=failed_conditions) result.update({ 'changed': False, 'stdout': responses, 'stdout_lines': list(to_lines(responses)) }) module.exit_json(**result)
def main(): argument_spec = vmware_argument_spec() argument_spec.update(dict(target_id=dict(required=True, type='int'))) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=False) if not HAS_PYVMOMI: module.fail_json(msg='pyvmomi is required for this module') content = connect_to_api(module) host = find_hostsystem(content) target_lun_uuid = {} scsilun_canonical = {} # Associate the scsiLun key with the canonicalName (NAA) for scsilun in host.config.storageDevice.scsiLun: scsilun_canonical[scsilun.key] = scsilun.canonicalName # Associate target number with LUN uuid for target in host.config.storageDevice.scsiTopology.adapter[0].target: for lun in target.lun: target_lun_uuid[target.target] = lun.scsiLun module.exit_json(changed=False, canonical=scsilun_canonical[target_lun_uuid[module.params['target_id']]])
def main(): Module = AnsibleModule( argument_spec=dict( env_id=dict(required=False, type='str'), name=dict(required=True, type='str'), release=dict(required=False, type='str') ) ) env_id = Module.params['env_id'] release = Module.params['release'] repo_name = Module.params['name'] try: if not env_id and not release: raise BaseException("Either env_id or release must be given") if env_id and repo_name: remove_from_env(env_id, repo_name) if release and repo_name: remove_from_release(release, repo_name) except Exception as e: Module.fail_json(msg="Exception occurred {}".format(e)) Module.exit_json(changed=True, result=0)
def main(): module = AnsibleModule( argument_spec=dict( name=dict(type='str'), count=dict(default=1, type='int'), state=dict(choices=['present', 'absent']), ), ) try: d = Dummy() execute_output = d.execute(module) json_output = {} host = execute_output.get('host') changed = execute_output.get('changed') if host or changed is not None: json_output['changed'] = True json_output.update(execute_output) else: json_output['changed'] = False module.exit_json(**json_output) except Exception as e: module.fail_json(msg=str(e))
def main(): argument_spec = ovirt_full_argument_spec( authz_name=dict(required=True, aliases=['domain']), user_name=dict(rdefault=None), group_name=dict(default=None), namespace=dict(default=None), ) module = AnsibleModule(argument_spec) check_sdk(module) try: connection = create_connection(module.params.pop('auth')) permissions_service = _permissions_service(connection, module) permissions = [] for p in permissions_service.list(): newperm = dict() for key, value in p.__dict__.items(): if value and isinstance(value, sdk.Struct): newperm[key[1:]] = get_link_name(connection, value) permissions.append(newperm) module.exit_json( changed=False, ansible_facts=dict(ovirt_permissions=permissions), ) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=False)
def main(): module = AnsibleModule( argument_spec=dict( state=dict(required=True, choices=['present', 'absent']), name=dict(required=False), apikey=dict(required=True), apiid=dict(required=True), validate_certs = dict(default='yes', type='bool'), ) ) state = module.params['state'] name= module.params['name'] apikey = module.params['api_key'] apiid = module.params['api_id'] if state == "present": (rc, result) = create_meter(module, name, apiid, apikey) if state == "absent": (rc, result) = delete_meter(module, name, apiid, apikey) if rc != 0: module.fail_json(msg=result) module.exit_json(status=result,changed=True)
def main(): ''' ansible oc module for secrets ''' module = AnsibleModule( argument_spec=dict( state=dict(default='present', type='str', choices=['present', 'absent', 'list']), debug=dict(default=False, type='bool'), src=dict(default=None, type='str'), content=dict(default=None), content_type=dict(default='dict', choices=['dict']), key=dict(default='', type='str'), value=dict(), value_type=dict(default='', type='str'), update=dict(default=False, type='bool'), append=dict(default=False, type='bool'), index=dict(default=None, type='int'), curr_value=dict(default=None, type='str'), curr_value_format=dict(default='yaml', choices=['yaml', 'json', 'str'], type='str'), backup=dict(default=True, type='bool'), separator=dict(default='.', type='str'), ), mutually_exclusive=[["curr_value", "index"], ['update', "append"]], required_one_of=[["content", "src"]], ) rval = Yedit.run_ansible(module) if 'failed' in rval and rval['failed']: module.fail_json(**rval) module.exit_json(**rval)
def main(): argument_spec = ec2_argument_spec() argument_spec.update(dict( vpc_id=dict(), name=dict(), nacl_id=dict(), subnets=dict(required=False, type='list', default=list()), tags=dict(required=False, type='dict'), ingress=dict(required=False, type='list', default=list()), egress=dict(required=False, type='list', default=list()), state=dict(default='present', choices=['present', 'absent']), ), ) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True, required_one_of=[['name', 'nacl_id']], required_if=[['state', 'present', ['vpc_id']]]) if not HAS_BOTO3: module.fail_json(msg='json, botocore and boto3 are required.') state = module.params.get('state').lower() try: region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True) client = boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_kwargs) except botocore.exceptions.NoCredentialsError as e: module.fail_json(msg="Can't authorize connection - %s" % str(e)) invocations = { "present": setup_network_acl, "absent": remove_network_acl } (changed, results) = invocations[state](client, module) module.exit_json(changed=changed, nacl_id=results)
def main(): module = AnsibleModule( argument_spec=dict( state=dict(type='str', default='file', choices=['file', 'directory']), path=dict(type='path'), prefix=dict(type='str', default='ansible.'), suffix=dict(type='str', default=''), ), ) try: if module.params['state'] == 'file': handle, path = mkstemp( prefix=module.params['prefix'], suffix=module.params['suffix'], dir=module.params['path'], ) close(handle) elif module.params['state'] == 'directory': path = mkdtemp( prefix=module.params['prefix'], suffix=module.params['suffix'], dir=module.params['path'], ) module.exit_json(changed=True, path=path) except Exception as e: module.fail_json(msg=to_native(e), exception=format_exc())
def main(): """main entry point for module execution """ argument_spec = dict( netconf_port=dict(type='int', default=830, aliases=['listens_on']), state=dict(default='present', choices=['present', 'absent']), ) argument_spec.update(junos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() result = {'changed': False, 'warnings': warnings} want = map_params_to_obj(module) have = map_config_to_obj(module) commands = map_obj_to_commands((want, have), module) result['commands'] = commands if commands: commit = not module.check_mode diff = load_config(module, commands, commit=commit) if diff: if module._diff: result['diff'] = {'prepared': diff} result['changed'] = True module.exit_json(**result)
def main(): argument_spec = dict( host_name=dict(type='str'), domain_name=dict(type='str'), domain_search=dict(type='list'), name_server=dict(type='list', aliases=['name_servers']), state=dict(type='str', default='present', choices=['present', 'absent']), ) argument_spec.update(vyos_argument_spec) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, mutually_exclusive=[('domain_name', 'domain_search')], ) warnings = list() check_args(module, warnings) result = {'changed': False, 'warnings': warnings} want = map_param_to_obj(module) have = config_to_dict(module) commands = spec_to_commands(want, have) result['commands'] = commands if commands: commit = not module.check_mode response = load_config(module, commands, commit=commit) result['changed'] = True module.exit_json(**result)
def main(): module = AnsibleModule( argument_spec=dict( description=dict(type='str', required=False), external=dict(type='bool', required=False), gidnumber=dict(type='str', required=False, aliases=['gid']), cn=dict(type='str', required=True, aliases=['name']), nonposix=dict(type='str', required=False), state=dict(type='str', required=False, default='present', choices=['present', 'absent']), ipa_prot=dict(type='str', required=False, default='https', choices=['http', 'https']), ipa_host=dict(type='str', required=False, default='ipa.example.com'), ipa_port=dict(type='int', required=False, default=443), ipa_user=dict(type='str', required=False, default='admin'), ipa_pass=dict(type='str', required=True, no_log=True), ), supports_check_mode=True, ) client = IPAClient(module=module, host=module.params['ipa_host'], port=module.params['ipa_port'], username=module.params['ipa_user'], password=module.params['ipa_pass'], protocol=module.params['ipa_prot']) try: client.login() changed, group = ensure(module, client) module.exit_json(changed=changed, group=group) except Exception as e: module.fail_json(msg=e.message)
def main(): argument_spec = cs_argument_spec() argument_spec.update(dict( name=dict(required=True), state=dict(default='present', choices=['present', 'absent']), domain=dict(), account=dict(), project=dict(), )) module = AnsibleModule( argument_spec=argument_spec, required_together=cs_required_together(), supports_check_mode=True ) acs_ig = AnsibleCloudStackInstanceGroup(module) state = module.params.get('state') if state in ['absent']: instance_group = acs_ig.absent_instance_group() else: instance_group = acs_ig.present_instance_group() result = acs_ig.get_result(instance_group) module.exit_json(**result)
def main(): """ Main entry point for Ansible module execution """ argument_spec = dict( hostname=dict(), vrf=dict(type='str', default='default'), domain_name=dict(), domain_search=dict(type='list'), name_servers=dict(type='list'), lookup_source=dict(), lookup_enabled=dict(type='bool', default=True), state=dict(choices=['present', 'absent'], default='present') ) argument_spec.update(iosxr_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) config_object = None if is_cliconf(module): module.deprecate(msg="cli support for 'iosxr_system' is deprecated. Use transport netconf instead", version="4 releases from v2.5") config_object = CliConfiguration(module) elif is_netconf(module): config_object = NCConfiguration(module) result = None if config_object: result = config_object.run() module.exit_json(**result)
def main(): arg_spec = dict( name=dict(required=True), vhost=dict(default='/'), pattern=dict(required=True), apply_to=dict(default='all', choices=['all', 'exchanges', 'queues']), tags=dict(type='dict', required=True), priority=dict(default='0'), node=dict(default='rabbit'), state=dict(default='present', choices=['present', 'absent']), ) module = AnsibleModule( argument_spec=arg_spec, supports_check_mode=True ) name = module.params['name'] state = module.params['state'] rabbitmq_policy = RabbitMqPolicy(module, name) result = dict(changed=False, name=name, state=state) if rabbitmq_policy.list(): if state == 'absent': rabbitmq_policy.clear() result['changed'] = True else: result['changed'] = False elif state == 'present': rabbitmq_policy.set() result['changed'] = True module.exit_json(**result)
def main(): argument_spec = ansible.module_utils.ec2.ec2_argument_spec() argument_spec.update(dict( mode = dict(choices=['grant', 'deny'], default='grant'), key_alias = dict(required=False, type='str'), key_arn = dict(required=False, type='str'), role_name = dict(required=False, type='str'), role_arn = dict(required=False, type='str'), grant_types = dict(required=False, type='list'), clean_invalid_entries = dict(type='bool', default=True), ) ) module = AnsibleModule( supports_check_mode=True, argument_spec=argument_spec, required_one_of=[['key_alias', 'key_arn'], ['role_name', 'role_arn']], required_if=[['mode', 'grant', ['grant_types']]] ) if not HAS_BOTO3: module.fail_json(msg='boto3 required for this module') result = {} mode = module.params['mode'] try: region, ec2_url, aws_connect_kwargs = ansible.module_utils.ec2.get_aws_connection_info(module, boto3=True) kms = ansible.module_utils.ec2.boto3_conn(module, conn_type='client', resource='kms', region=region, endpoint=ec2_url, **aws_connect_kwargs) iam = ansible.module_utils.ec2.boto3_conn(module, conn_type='client', resource='iam', region=region, endpoint=ec2_url, **aws_connect_kwargs) except botocore.exceptions.NoCredentialsError as e: module.fail_json(msg='cannot connect to AWS', exception=traceback.format_exc()) try: if module.params['key_alias'] and not module.params['key_arn']: module.params['key_arn'] = get_arn_from_kms_alias(kms, module.params['key_alias']) if not module.params['key_arn']: module.fail_json(msg='key_arn or key_alias is required to {}'.format(mode)) if module.params['role_name'] and not module.params['role_arn']: module.params['role_arn'] = get_arn_from_role_name(iam, module.params['role_name']) if not module.params['role_arn']: module.fail_json(msg='role_arn or role_name is required to {}'.format(module.params['mode'])) # check the grant types for 'grant' only. if mode == 'grant': for g in module.params['grant_types']: if not g in statement_label: module.fail_json(msg='{} is an unknown grant type.'.format(g)) ret = do_grant(kms, module.params['key_arn'], module.params['role_arn'], module.params['grant_types'], mode=mode, dry_run=module.check_mode, clean_invalid_entries=module.params['clean_invalid_entries']) result.update(ret) except Exception as err: error_msg = boto_exception(err) module.fail_json(msg=error_msg, exception=traceback.format_exc()) module.exit_json(**result)
def main(): argument_spec = vmware_argument_spec() argument_spec.update( name=dict(type='str'), datacenter=dict(type='str'), cluster=dict(type='str') ) module = AnsibleModule(argument_spec=argument_spec, required_one_of=[ ['cluster', 'datacenter'], ], ) result = dict(changed=False) pyv = PyVmomiHelper(module) if module.params['cluster']: dxs = pyv.lookup_datastore_by_cluster() else: dxs = pyv.lookup_datastore() datastores = list() for ds in dxs: summary = ds.summary dds = dict() dds['accessible'] = summary.accessible dds['capacity'] = summary.capacity dds['name'] = summary.name dds['freeSpace'] = summary.freeSpace dds['maintenanceMode'] = summary.maintenanceMode dds['multipleHostAccess'] = summary.multipleHostAccess dds['type'] = summary.type # vcsim does not return uncommitted if not summary.uncommitted: summary.uncommitted = 0 dds['uncommitted'] = summary.uncommitted dds['url'] = summary.url # Calculated values dds['provisioned'] = summary.capacity - summary.freeSpace + summary.uncommitted dds['datastore_cluster'] = 'N/A' if isinstance(ds.parent, vim.StoragePod): dds['datastore_cluster'] = ds.parent.name if module.params['name']: if dds['name'] == module.params['name']: datastores.extend([dds]) else: datastores.extend([dds]) result['datastores'] = datastores # found a datastore if datastores: module.exit_json(**result) else: msg = "Unable to gather datastore facts" if module.params['name']: msg += " for %(name)s" % module.params msg += " in datacenter %(datacenter)s" % module.params module.fail_json(msg=msg)
def main(): """ main entry point for module execution """ argument_spec = dict( http=dict(aliases=['enable_http'], type='bool'), http_port=dict(type='int'), https=dict(aliases=['enable_https'], type='bool'), https_port=dict(type='int'), sandbox=dict(aliases=['enable_sandbox'], type='bool'), state=dict(default='present', choices=['started', 'stopped', 'present', 'absent']) ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() check_args(module, warnings) result = {'changed': False, 'warnings': warnings} want = map_params_to_obj(module) have = map_config_to_obj(module) commands = map_obj_to_commands(want, have, module) result['commands'] = commands if commands: if not module.check_mode: load_config(module, commands) result['changed'] = True module.exit_json(**result)
def main(): argument_spec = vmware_argument_spec() argument_spec.update( name=dict(type='str'), uuid=dict(type='str'), folder=dict(type='str'), datacenter=dict(required=True, type='str'), ) module = AnsibleModule(argument_spec=argument_spec, required_together=[['name', 'folder']], required_one_of=[['name', 'uuid']], ) if module.params['folder']: # FindByInventoryPath() does not require an absolute path # so we should leave the input folder path unmodified module.params['folder'] = module.params['folder'].rstrip('/') pyv = PyVmomiHelper(module) # Check if the VM exists before continuing vm = pyv.get_vm() if not vm: # If UUID is set, getvm select UUID, show error message accordingly. module.fail_json(msg="Unable to gather facts about snapshots for" " non-existing VM ['%s']" % (module.params.get('uuid') or module.params.get('name'))) results = dict(changed=False, guest_snapshots=pyv.gather_guest_snapshot_facts(vm_obj=vm)) module.exit_json(**results)
def main(): module = AnsibleModule( argument_spec = dict( name = dict(required = True), login = dict(required = True), login_port = dict(required = False, default = 1433), login_name = dict(required = True), login_password = dict(required = True, no_log = True) ) ) name = module.params['name'] login = module.params['login'] login_port = module.params['login_port'] login_name = module.params['login_name'] login_password = module.params['login_password'] sqlcmd(login_port, login_name, login_password, """ IF NOT EXISTS( SELECT * FROM sys.sysusers WHERE name = {0} ) CREATE USER {1} FOR LOGIN {2} ; """.format( quoteName(name, "'"), quoteName(name, '['), quoteName(login, '[') )) module.exit_json(changed = True, name = name)
def main(): module = AnsibleModule( argument_spec=dict( nsc_host=dict(type='str', required=True), nsc_protocol=dict(type='str', default='https'), user=dict(type='str', required=True), password=dict(type='str', required=True, no_log=True), action=dict(type='str', default='enable', choices=['disable', 'enable']), name=dict(type='str', default=socket.gethostname()), type=dict(type='str', default='server', choices=['server', 'service']), validate_certs=dict(type='bool', default=True), ), ) rc = 0 try: rc, result = core(module) except Exception as e: module.fail_json(msg=to_native(e), exception=traceback.format_exc()) if rc != 0: module.fail_json(rc=rc, msg=result) else: result['changed'] = True module.exit_json(**result)
def main(): argument_spec = ovirt_facts_full_argument_spec( pattern=dict(default='', required=False), ) module = AnsibleModule(argument_spec) check_sdk(module) try: auth = module.params.pop('auth') connection = create_connection(auth) users_service = connection.system_service().users_service() users = users_service.list(search=module.params['pattern']) module.exit_json( changed=False, ansible_facts=dict( ovirt_users=[ get_dict_of_struct( struct=c, connection=connection, fetch_nested=module.params.get('fetch_nested'), attributes=module.params.get('nested_attributes'), ) for c in users ], ), ) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=auth.get('token') is None)
def main(): argument_spec = ovirt_full_argument_spec( pattern=dict(default='', required=False), ) module = AnsibleModule(argument_spec) check_sdk(module) try: connection = create_connection(module.params.pop('auth')) vms_service = connection.system_service().vms_service() vms = vms_service.list(search=module.params['pattern']) module.exit_json( changed=False, ansible_facts=dict( ovirt_vms=[ get_dict_of_struct( struct=c, connection=connection, fetch_nested=1, attributes=['name', 'description'], ) for c in vms ], ), ) except Exception as e: module.fail_json(msg=str(e), exception=traceback.format_exc()) finally: connection.close(logout=False)
def main(): argument_spec = vmware_argument_spec() argument_spec.update( name=dict(type='str'), name_match=dict(type='str', choices=['first', 'last'], default='first'), uuid=dict(type='str'), folder=dict(type='str', default='/vm'), datacenter=dict(type='str', required=True), ) module = AnsibleModule(argument_spec=argument_spec, required_one_of=[['name', 'uuid']]) # FindByInventoryPath() does not require an absolute path # so we should leave the input folder path unmodified module.params['folder'] = module.params['folder'].rstrip('/') pyv = PyVmomiHelper(module) # Check if the VM exists before continuing vm = pyv.getvm(name=module.params['name'], folder=module.params['folder'], uuid=module.params['uuid']) # VM already exists if vm: try: module.exit_json(instance=pyv.gather_facts(vm)) except Exception as exc: module.fail_json(msg="Fact gather failed with exception %s" % to_text(exc)) else: msg = "Unable to gather facts for non-existing VM " if module.params['name']: msg += "%(name)s" % module.params elif module.params['uuid']: msg += "%(uuid)s" % module.params module.fail_json(msg=msg)
def main(): argument_spec = ec2_argument_spec() argument_spec.update(dict(state=dict(default='present', choices=['present', 'absent']), name=dict(), amazon_asn=dict(), virtual_gateway_id=dict(), direct_connect_gateway_id=dict(), wait_timeout=dict(type='int', default=320))) required_if = [('state', 'present', ['name', 'amazon_asn']), ('state', 'absent', ['direct_connect_gateway_id'])] module = AnsibleModule(argument_spec=argument_spec, required_if=required_if) if not HAS_BOTO3: module.fail_json(msg='boto3 is required for this module') state = module.params.get('state') region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module, boto3=True) client = boto3_conn(module, conn_type='client', resource='directconnect', region=region, endpoint=ec2_url, **aws_connect_kwargs) if state == 'present': (changed, results) = ensure_present(client, module) elif state == 'absent': changed = ensure_absent(client, module) results = {} module.exit_json(changed=changed, **camel_dict_to_snake_dict(results))
def main(): module_args = oci_common_utils.get_common_arg_spec() module_args.update( dict( compartment_id=dict(type="str", required=True), database_type=dict( type="list", choices=["ADW-S", "ATP-S", "ADW-D", "ATP-D"] ), database_id=dict(type="list"), database_time_pct_greater_than=dict(type="float"), sql_identifier=dict(type="list"), analysis_time_interval=dict(type="str"), time_interval_start=dict(type="str"), time_interval_end=dict(type="str"), sort_order=dict(type="str", choices=["ASC", "DESC"]), sort_by=dict( type="str", choices=[ "databaseTimeInSec", "executionsPerHour", "executionsCount", "cpuTimeInSec", "ioTimeInSec", "inefficientWaitTimeInSec", "responseTimeInSec", "planCount", "variability", "averageActiveSessions", "databaseTimePct", "inefficiencyInPct", "changeInCpuTimeInPct", "changeInIoTimeInPct", "changeInInefficientWaitTimeInPct", "changeInResponseTimeInPct", "changeInAverageActiveSessionsInPct", "changeInExecutionsPerHourInPct", "changeInInefficiencyInPct", ], ), category=dict( type="list", choices=[ "DEGRADING", "VARIANT", "INEFFICIENT", "CHANGING_PLANS", "IMPROVING", "DEGRADING_VARIANT", "DEGRADING_INEFFICIENT", "DEGRADING_CHANGING_PLANS", "DEGRADING_INCREASING_IO", "DEGRADING_INCREASING_CPU", "DEGRADING_INCREASING_INEFFICIENT_WAIT", "DEGRADING_CHANGING_PLANS_AND_INCREASING_IO", "DEGRADING_CHANGING_PLANS_AND_INCREASING_CPU", "DEGRADING_CHANGING_PLANS_AND_INCREASING_INEFFICIENT_WAIT", "VARIANT_INEFFICIENT", "VARIANT_CHANGING_PLANS", "VARIANT_INCREASING_IO", "VARIANT_INCREASING_CPU", "VARIANT_INCREASING_INEFFICIENT_WAIT", "VARIANT_CHANGING_PLANS_AND_INCREASING_IO", "VARIANT_CHANGING_PLANS_AND_INCREASING_CPU", "VARIANT_CHANGING_PLANS_AND_INCREASING_INEFFICIENT_WAIT", "INEFFICIENT_CHANGING_PLANS", "INEFFICIENT_INCREASING_INEFFICIENT_WAIT", "INEFFICIENT_CHANGING_PLANS_AND_INCREASING_INEFFICIENT_WAIT", ], ), ) ) module = AnsibleModule(argument_spec=module_args) if not HAS_OCI_PY_SDK: module.fail_json(msg="oci python sdk required for this module.") resource_facts_helper = ResourceFactsHelper( module=module, resource_type="sql_statistics", service_client_class=OperationsInsightsClient, namespace="opsi", ) result = [] if resource_facts_helper.is_get(): result = resource_facts_helper.get() elif resource_facts_helper.is_list(): result = resource_facts_helper.list() else: resource_facts_helper.fail() module.exit_json(sql_statistics=result)
def main(): """ This section is for arguments parsing """ state_map = dict( present='ipv6security-raguard-create', absent='ipv6security-raguard-delete', update='ipv6security-raguard-modify' ) argument_spec = dict( pn_cliswitch=dict(required=False, type='str'), state=dict(required=False, type='str', choices=state_map.keys(), default='present'), pn_device=dict(required=False, type='str', choices=['host', 'router']), pn_access_list=dict(required=False, type='str'), pn_prefix_list=dict(required=False, type='str'), pn_router_priority=dict(required=False, type='str', choices=['low', 'medium', 'high']), pn_name=dict(required=True, type='str'), ) module = AnsibleModule( argument_spec=argument_spec, required_if=( ["state", "present", ['pn_device']], ), ) # Accessing the arguments cliswitch = module.params['pn_cliswitch'] state = module.params['state'] device = module.params['pn_device'] access_list = module.params['pn_access_list'] prefix_list = module.params['pn_prefix_list'] router_priority = module.params['pn_router_priority'] name = module.params['pn_name'] command = state_map[state] # Building the CLI command string cli = pn_cli(module, cliswitch) NAME_EXISTS = check_cli(module) if command == 'ipv6security-raguard-modify': if not device and not access_list and not prefix_list and not router_priority: module.fail_json( failed=True, msg='required one of device, access_list, prefix_list or router_priority' ) if command == 'ipv6security-raguard-create': if NAME_EXISTS is True: module.exit_json( skipped=True, msg='ipv6 security raguard with name %s already exists' % name ) if command != 'ipv6security-raguard-create': if NAME_EXISTS is False: module.exit_json( skipped=True, msg='ipv6 security raguard with name %s does not exist' % name ) cli += ' %s name %s ' % (command, name) if command != 'ipv6security-raguard-delete': if device == 'router': cli += ' device ' + device if access_list: check_list(module, access_list, 'access-list-show') cli += ' access-list ' + access_list if prefix_list: check_list(module, prefix_list, 'prefix-list-show') cli += ' prefix-list ' + prefix_list if router_priority: cli += ' router-priority ' + router_priority if device == 'host': cli += ' device ' + device run_cli(module, cli, state_map)
class UniFi(object): """ Wraps all interactions with the UniFi controller REST API. :ivar __module: the Ansible module object :vartype __module: AnsibleModule :ivar __result: the result structure for the Ansible module operation :vartype __result: dict :ivar __connection: the Ansible connection object :vartype __connection: Connection :ivar __logger: logging facility, only used for log_levels > 0 :vartype __logger: Logger :ivar error: shorthand to the same method of the logger :vartype error: function :ivar info: shorthand to the same method of the logger :vartype info: function :ivar debug: shorthand to the same method of the logger :vartype debug: function :ivar trace: shorthand to the same method of the logger :vartype trace: function """ #: default parameters the any UniFi Ansible module should accept DEFAULT_ARGS = dict( debug=dict(type='int', default=Logger.LEVEL_DISABLED.value), state=dict(choices=['present','absent','ignore'], default='present'), site=dict(type='str', required=False, default='default') ) #: the default result structure __RESULT_STUB = {'changed': False} #: the key that identifies attributes which are missing __MISSING_KEY = '__missing__' #: how item types match to requests to the UniFi REST API __API_CONFIG = { 'site': { 'request_kwargs': { 'path': '/sites', 'path_prefix': '/api/', 'site': 'self', 'proxy': 'network' } }, 'device': { 'request_kwargs': { 'path': '/stat/device', 'proxy': 'network' } }, 'networkconf': { 'request_kwargs': { 'path': '/rest/networkconf', 'proxy': 'network' } }, 'portconf': { 'request_kwargs': { 'path': '/rest/portconf', 'proxy': 'network' } } } @classmethod def set_missing(cls, item, attribute): """ Class method that annotates a particular attribute of an item as missing in the sense that it is required to be absent in the object on the UniFi controller. Use pop_missing to remove these annotations. :param item: The item that should be annotated :type item: dict :param attribute: The attribute that should be marked missing :type attribute: str :returns: The list of attributes which have been marked missing so far :rtype: list """ missing = item.get(UniFi.__MISSING_KEY, []) missing.append(attribute) item[UniFi.__MISSING_KEY] = missing return missing @classmethod def pop_missing(cls, item): """ Class method that removes any previous annotations for attributes that have been marked missing from an item. Use this method before submitting an item via REST to the controller. :param item: The item where the annotations should be removed :type item: dict :returns: The list of attributes which have been marked missing :rtype: list """ return item.pop(UniFi.__MISSING_KEY, []) def __init__(self, result=None, **module_specs): """ Constructor for the UniFi API wrapper. :param result: A dictionary that may contain any data which will be used in the result that is returned by the Ansible module :type result: dict :param \\**module_specs: Any parameter that can be passed to the constructor of AnsibleModule """ module_specs['supports_check_mode'] = True self.__module = AnsibleModule(**module_specs) self.__result = result if result is not None else UniFi.__RESULT_STUB self.__connection = None self.__logger = Logger( self.param('debug', Logger.LEVEL_DISABLED), environ.get('ANSIBLE_UNIFI_LOG_PATH') ) self.error = self.__logger.error self.info = self.__logger.info self.debug = self.__logger.debug self.trace = self.__logger.trace def __generate_setter(self, name): """ Factory for a setter method that allows to upload an object to the UniFi REST API. The generated method passes all keyword arguments on to the connection plugin. Example: * set_networkconf(_id=my_networkconf_id) * set_portconf(data=my_portconf) :param name: The name (or type) of a UniFi API object :type name: str :returns: A setter method :rtype: function """ def __item_setter(name, **item_kwargs): """ Inner method that implements the actual setter :param name: The name (or type) of a UniFi API object :type name: str :param \\**kwargs: Any parameter will be passed on to the connection plugin :returns: The resulting UniFi object :rtype: dict """ result = self.send(**UniFi.__API_CONFIG[name]['request_kwargs'], **item_kwargs) return result if name in UniFi.__API_CONFIG: return lambda **item_kwargs: __item_setter(name, **item_kwargs) def __generate_getter(self, name): """ Factory for a getter method that allows the retrieval of an object via the UniFi REST API. Depending on the usage of singular or plural of the name parameter the generated method will return all objects or only a single object that passes the filter test. In case of a single item all keyword arguments passed to the getter will be used to filter the results. If multiple objects would match a filter, then only the first match will be returned. Example: * get_networkconfs() * get_networkconf(vlan=500) :param name: The name (or type) of a UniFi API object :type name: str :returns: A setter method :rtype: function """ def __items_getter(name): """ Inner method that implements the actual getter for a list of objects :param name: The name (or type) of a UniFi API object :type name: str :returns: The resulting list of UniFi object :rtype: list """ items = self.send(**UniFi.__API_CONFIG[name]['request_kwargs']) return items def __item_getter(name, **filter_kwargs): """ Inner method that implements the actual getter for a single object :param name: The name (or type) of a UniFi API object :type name: str :param \\**kwargs: All parameters will be used as filter :returns: The resulting UniFi object :rtype: dict """ if not filter_kwargs: default = self.param(name, default=None) if default is not None: filter_kwargs['name'] = default items = __items_getter(name) for item in items: match = True for key, value in filter_kwargs.items(): if item.get(key, None) != value and \ item.get(key, None) != str(value): match = False break if match: return item return None if name in UniFi.__API_CONFIG: return lambda **filter_kwargs: __item_getter(name, **filter_kwargs) if name[-1] == 's' and name[:-1] in UniFi.__API_CONFIG: return lambda: __items_getter(name[:-1]) return None def __getattribute__(self, name): """ Override of the normal __getattribute__ method to return UniFi getter and setter methods. :param name: The name (or type) of a UniFi API object :type name: str :returns: the generated getter or setter or the appropriate attribute :rtype: any """ if name.startswith('get_'): getter = self.__generate_getter(name[4:]) if getter: return getter if name.startswith('set_'): setter = self.__generate_setter(name[4:]) if setter: return setter return super(UniFi, self).__getattribute__(name) @property def connection(self): """ Property to initialize the Ansible Connection object if needed and return the object """ if self.__connection: return self.__connection if not self.__module._socket_path: raise ConnectionError('please use this module with a host httpapi ' 'connection of type "unifi"') self.__connection = Connection(self.__module._socket_path) self.__connection.set_logging(self.__logger.level.value, environ.get('ANSIBLE_UNIFI_LOG_PATH')) return self.__connection @property def result(self): """ Gives access to the structure containing the result of the Ansible module operation """ return self.__result @property def check_mode(self): """ Shorthand property to identify if Ansible check mode is enabled """ return self.__module.check_mode def has_param(self, key): """ Shorthand method to check if a particular param has been passed to the Ansible module :param key: the name of the param :type key: str :returns: True if the Module param is available, else False :rtype: bool """ return key in self.__module.params def param(self, key, fail_on_error=True, **kwargs): """ Shorthand method to retrieve the value of an Ansible module parameter or an optional default value or fail if it is not present. :raises KeyError: if a required parameter is missing and fail_on_error was set to False :param key: the name of the param :type key: str :param fail_on_error: if True, then the Module will fail if the param is missing and no default value is provided (this behavior is default) - otherwise a KeyError is thrown and can be handled by the calling code :type fail_on_error: bool :param default: an optional default value that is returned if the param is missing, in this case the method will never fail :type default: any :returns: the value of the Ansible module parameter :rtype: any """ if key in self.__module.params: return self.__module.params[key] if 'default' in kwargs: return kwargs['default'] if fail_on_error: self.fail('No such module parameter: {key}', key=key) else: raise KeyError('No such module parameter: {key}'.format(key=key)) def exit(self): """ This method concludes the Ansible module operation and provides the required clean-up of new-style Ansible modules """ if self.__logger.enabled: self.__result['logs'] = Logger.join( self.connection.get_logs(), self.__logger.logs) self.__module.exit_json(**self.__result) def fail(self, message, **message_kwargs): """ This method concludes the Ansible module operation with an error and provides the required clean-up of new-style Ansible modules. :param message: an error message :type message: str :param \\**message_kwargs: format parameters for the error message :type \\**message_kwargs: any """ if self.__logger.enabled: self.__result['logs'] = Logger.join( self.connection.get_logs(), self.__logger.logs) try: message = message.format(**message_kwargs) except: pass self.__module.fail_json(msg=message, **self.__result) def update_item(self, input_item, existing_item, require_absent): """ Convenience method to verify if an (existing) item matches another (input) item by all attributes of the (input) item and update the former if needed. The method also pays attention to attributes that may not occur on the (existing) item and removes those if present. :param input_item: the item which contains the desired state :type input_item: dict :param existing_item: the existing item which should be verified :type existing_item: dict :param require_absent: the names of attributes which may not occur on the existing item :type require_absent: list :returns: True if the existing item was changed, else False :rtype: bool """ changed = False for key, value in input_item.items(): if key not in existing_item or existing_item[key] != value: changed = True self.debug('Field {key} differs on controller: ' 'expected {expected} but got {value}', key=key, expected=value, value=existing_item.get(key, '<missing>')) existing_item[key] = value for key in require_absent: if key in existing_item: changed = True self.debug('Field {key} exists on controller ' 'but it should be absent', key=key) del existing_item[key] return changed def update_list(self, input_item, existing_items, state, compare=None): """ Convenience method that updates a list of (existing) items to contain an (input) item in a desired state. Valid states include the Ansible states 'present' and 'absent' as well as 'ignore' or None (only lists matching items), True (same as present), False (same as absent) :raises ValueError: if not no valid (Ansible) state is passed :param input_item: the item which contains the desired state :type input_item: dict :param existing_items: the existing items which should be verified :type existing_items: list :param state: a valid (Ansible) state :type state: str :param compare: an optional function that accepts two items as parameters and checks if an existing item matches the input item, if ommited items will be compared by name (case invariant) :type compare: function :returns: - ignored_items (:py:class:`list`) - the list of ignored items (those which only match but should neither be changed nor deleted) - changed_items (:py:class:`list`) - the list items that should be changed or created - deleted_items (:py:class:`list`) - the list of _id values of all the items that should be deleted """ def _do_compare(existing_item, compare): """ Inner shorthand method which either calls the passed compare function or compares the passed existing item to the input item based on the name attributes. The method is used to determine which existing item (if any) from a list of all existing items should be affected by the surrounding update method. Note: the input_item does not change throughout that process and is retrieved from the scope of the surrounding method. :param existing_item: the existing item that should be matched against the input item :type existing_item: dict :param compare: a custom compare function which accepts two items and returns True if the check succeeds :type compare: function: :returns: the result of the comparison, True if the input item matches the existing item :rtype: bool """ if compare: return compare(input_item, existing_item) else: return ('name' in input_item and 'name' in existing_item and input_item['name'].lower() == existing_item['name'].lower()) matching_items = list( filter(lambda x: _do_compare(x, compare), existing_items) ) if not matching_items and compare is not None: # second attempt, compare by name only self.trace('No matches, fallback to comparison by name') matching_items = list( filter(lambda x: _do_compare(x, None), existing_items) ) self.debug('Got {count} match(es) for input item', count=len(matching_items)) ignored_items = [] changed_items = [] deleted_items = [] if state in ['ignore', None]: for matching_item in matching_items: ignored_items.append(matching_item) elif state in ['present', True]: require_absent = UniFi.pop_missing(input_item) if matching_items: for matching_item in matching_items: changed = self.update_item(input_item, matching_item, require_absent) if changed: changed_items.append(matching_item) else: changed_items.append(input_item) elif state in ['absent', False]: for matching_item in matching_items: deleted_items.append(matching_item['_id']) else: raise ValueError('Got unexpected value for requested state: {state}' .format(state=state)) return ignored_items, changed_items, deleted_items def ensure_item(self, item_type, preprocess_item=None, compare=None): """ Convenience method to ensure the provided item state is reflected by the corresponding object on the UniFi controller. The item is refered to by the item_type which in turns will be used to - lookup the input item from the Ansible module parameter with the same name as the item_type - lookup the API config based on item_type as key - store the resulting objects in a field of the result object under item_type as key :param item_type: the name of the item type :type item_type: str :param preprocess_item: optional callback function that accepts this object and the item that was retrieved from the Ansible module paramters to preprocess the item for further operation :type preprocess_item: function :param compare: optional callback function that compares two items based on custom attributes, if ommitted the default comparison checks two items based on their name attributes (case invariant) :type compare: function """ def _set_result(result_item): """ Inner shorthand method which appends a resulting item to the appropriate list in the result structure. Creates the list if it is not already present :param result_item: the result item that should be appended to the result list :type result_item: dict: """ result_data = self.__result.get(item_type, []) if isinstance(result_item, list): result_data.extend(result_item) else: result_data.append(result_item) self.__result[item_type] = result_data try: if not item_type in UniFi.__API_CONFIG: self.fail('No API configuration found for type {item}', item=item_type) request_kwargs = UniFi.__API_CONFIG[item_type]['request_kwargs'] item = self.param(item_type) if preprocess_item: preprocess_item(self, item) existing_items = self.send(**request_kwargs) ignored_items, changed_items, deleted_items = self.update_list( item, existing_items, self.param('state'), compare=compare) changed = False for item in ignored_items: _set_result(item) for item in changed_items: if not self.check_mode: self.send(**request_kwargs, data=item) changed = True _set_result(item) for item in deleted_items: if not self.check_mode: self.send(**request_kwargs, _id=item) changed_items = True _set_result(item) self.__result['changed'] = (changed or self.__result['changed']) except Exception as e: if self.__logger.enabled: self.__result['trace'] = format_exc() self.fail(str(e)) def send(self, path, site=None, result_path=['data'], **kwargs): """ Convenience method that sends a request to the UniFi REST API. Note about paths: paths are assembled by the UniFi connection plugin and the path here usually contains the one or two last path elements, e.g. /rest/networkconf :raises KeyError: if the UniFi response object doesn't match the expected structure :param path: the path of the REST endpoint :type path: str :param site: the optional name of the site, if ommitted will be taken from the Ansible module param :type site: str :param result_path: a list of path elements to navigate the response from the UniFi REST API (typically contains the actual response data under the attribute 'data' of the response object) :type result_path: list :param \\**kwargs: any further keyword arguments will be passed on to the UniFi connection plugin :type \\**kwargs: any :returns: the UniFi response object :rtype: dict """ if not site: site = self.param('site', default='default') result_item = self.connection.send_request(path=path, site=site, **kwargs) for attr in result_path: if attr not in result_item: raise KeyError('UniFi API response does not include {path}, ' 'misses attribute {attr}' .format(path=', '.join(result_path), attr=attr)) result_item = result_item.get(attr, None) return result_item
def main(): module = AnsibleModule( argument_spec=dict( name=dict(required=True, type='str'), type=dict(default='ipv4', type='str', aliases=['tunnel_type'], choices=SUPPORTED_TYPES), local_address=dict(type='str', aliases=['local']), remote_address=dict(type='str', aliases=['remote']), temporary=dict(default=False, type='bool'), state=dict(default='present', choices=['absent', 'present']), ), required_if=[ ['state', 'present', ['local_address', 'remote_address']], ], supports_check_mode=True ) iptun = IPTun(module) rc = None out = '' err = '' result = {} result['name'] = iptun.name result['type'] = iptun.type result['local_address'] = iptun.local_address result['remote_address'] = iptun.remote_address result['state'] = iptun.state result['temporary'] = iptun.temporary if iptun.state == 'absent': if iptun.iptun_exists(): if module.check_mode: module.exit_json(changed=True) (rc, out, err) = iptun.delete_iptun() if rc != 0: module.fail_json(name=iptun.name, msg=err, rc=rc) elif iptun.state == 'present': if not iptun.iptun_exists(): if module.check_mode: module.exit_json(changed=True) (rc, out, err) = iptun.create_iptun() if rc is not None and rc != 0: module.fail_json(name=iptun.name, msg=err, rc=rc) else: if iptun.iptun_needs_updating(): (rc, out, err) = iptun.update_iptun() if rc != 0: module.fail_json(msg='Error while updating tunnel interface: "%s"' % err, name=iptun.name, stderr=err, rc=rc) if rc is None: result['changed'] = False else: result['changed'] = True if out: result['stdout'] = out if err: result['stderr'] = err module.exit_json(**result)
def run_module(): """The entry point of the module.""" module_args = dict(purge=dict(type="bool", required=False, default=False), ) tuned_plugin_names = get_supported_tuned_plugin_names() for plugin_name in tuned_plugin_names: # use raw here - type can be dict or list - perform validation # below module_args[plugin_name] = dict(type="raw", required=False) result = dict(changed=False, message="") module = AnsibleModule(argument_spec=module_args, supports_check_mode=True) if not module.check_mode: if os.environ.get("TESTING", "false") == "true": # pylint: disable=blacklisted-name _ = setup_for_testing() params = module.params # remove any non-tuned fields from params and save them locally # state = params.pop("state") purge = params.pop("purge", False) # also remove any empty or None # pylint: disable=blacklisted-name _ = remove_if_empty(params) errlist = validate_and_digest(params) if errlist: errmsg = "Invalid format for input parameters" module.fail_json(msg=errmsg, warnings=errlist, **result) # In check_mode, just perform input validation (above), because # tuned will not be installed on the remote system if module.check_mode: module.exit_json(**result) elif caught_import_error is not None: raise caught_import_error # pylint: disable-msg=E0702 elif caught_name_error is not None: # name error is usually because tuned module was not imported # but just in case, report it here raise caught_name_error # pylint: disable-msg=E0702 tuned_config = get_tuned_config() current_profile = None tuned_app, errmsg = load_current_profile(tuned_config, TUNED_PROFILE, module) if tuned_app is None: module.fail_json(msg=errmsg, **result) else: current_profile = tuned_app.daemon.profile debug_print_profile(current_profile, module) errmsg = "" result["msg"] = "Kernel settings were updated." # apply the given params to the profile - if there are any new items # the function will return True we set changed = True changestatus, reboot_required = apply_params_to_profile( params, current_profile, purge) profile_list = [] if update_current_profile_and_mode(tuned_app.daemon, profile_list): # profile or mode changed if changestatus == NOCHANGES: changestatus = CHANGES result["msg"] = "Updated active profile and/or mode." if changestatus > NOCHANGES: try: write_profile(current_profile) # notify tuned to reload/reapply profile except TunedException as tex: module.debug("caught TunedException [{0}]".format(tex)) errmsg = "Unable to apply tuned settings: {0}".format(tex) module.fail_json(msg=errmsg, **result) except IOError as ioe: module.debug("caught IOError [{0}]".format(ioe)) errmsg = "Unable to apply tuned settings: {0}".format(ioe) module.fail_json(msg=errmsg, **result) result["changed"] = True else: result["msg"] = "Kernel settings are up to date." debug_print_profile(current_profile, module) result["new_profile"] = profile_to_dict(current_profile) result["active_profile"] = " ".join(profile_list) result["reboot_required"] = reboot_required if reboot_required: result["msg"] = (result["msg"] + " A system reboot is needed to apply the changes.") module.exit_json(**result)
def main(): argument_spec = dict( vrf=dict(required=True), afi=dict(required=True, choices=['ipv4', 'ipv6']), route_target_both_auto_evpn=dict(required=False, type='bool'), state=dict(choices=['present', 'absent'], default='present'), safi=dict(choices=['unicast', 'multicast'], removed_in_version="2.4"), ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() check_args(module, warnings) result = {'changed': False, 'warnings': warnings} config_text = get_config(module) config = NetworkConfig(indent=2, contents=config_text) path = [ 'vrf context %s' % module.params['vrf'], 'address-family %s unicast' % module.params['afi'] ] try: current = config.get_block_config(path) except ValueError: current = None commands = list() if current and module.params['state'] == 'absent': commands.append('no address-family %s unicast' % module.params['afi']) elif module.params['state'] == 'present': if current: have = 'route-target both auto evpn' in current want = bool(module.params['route_target_both_auto_evpn']) if want and not have: commands.append('address-family %s unicast' % module.params['afi']) commands.append('route-target both auto evpn') elif have and not want: commands.append('address-family %s unicast' % module.params['afi']) commands.append('no route-target both auto evpn') else: commands.append('address-family %s unicast' % module.params['afi']) if module.params['route_target_both_auto_evpn']: commands.append('route-target both auto evpn') if commands: commands.insert(0, 'vrf context %s' % module.params['vrf']) if not module.check_mode: load_config(module, commands) result['changed'] = True result['commands'] = commands module.exit_json(**result)
def main(): """ main entry point for module execution """ element_spec = dict(address=dict(aliases=['prefix']), next_hop=dict(), preference=dict(type='int', aliases=['admin_distance']), qualified_next_hop=dict(type='str'), qualified_preference=dict(type='int'), state=dict(default='present', choices=['present', 'absent']), active=dict(default=True, type='bool')) aggregate_spec = deepcopy(element_spec) aggregate_spec['address'] = 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), purge=dict(default=False, type='bool')) argument_spec.update(element_spec) argument_spec.update(junos_argument_spec) required_one_of = [['aggregate', 'address']] mutually_exclusive = [['aggregate', 'address']] module = AnsibleModule(argument_spec=argument_spec, required_one_of=required_one_of, mutually_exclusive=mutually_exclusive, supports_check_mode=True) warnings = list() check_args(module, warnings) result = {'changed': False} if warnings: result['warnings'] = warnings top = 'routing-options/static/route' param_to_xpath_map = collections.OrderedDict() param_to_xpath_map.update([('address', { 'xpath': 'name', 'is_key': True }), ('next_hop', 'next-hop'), ('preference', 'preference/metric-value'), ('qualified_next_hop', { 'xpath': 'name', 'top': 'qualified-next-hop' }), ('qualified_preference', { 'xpath': 'preference', 'top': 'qualified-next-hop' })]) params = to_param_list(module) requests = list() for param in params: # if key doesn't exist in the item, get it from module.params for key in param: if param.get(key) is None: param[key] = module.params[key] item = param.copy() if item['state'] == 'present': if not item['address'] and item['next_hop']: module.fail_json( msg= "parameters are required together: ['address', 'next_hop']" ) want = map_params_to_obj(module, param_to_xpath_map, param=item) requests.append(map_obj_to_ele(module, want, top, param=item)) with locked_config(module): for req in requests: diff = load_config(module, tostring(req), warnings, action='replace') commit = not module.check_mode if diff: if commit: commit_configuration(module) else: discard_changes(module) result['changed'] = True if module._diff: result['diff'] = {'prepared': diff} module.exit_json(**result)
def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict( subnet_id=dict(type='str'), eip_address=dict(type='str'), allocation_id=dict(type='str'), if_exist_do_not_create=dict(type='bool', default=False), state=dict(default='present', choices=['present', 'absent']), wait=dict(type='bool', default=False), wait_timeout=dict(type='int', default=320, required=False), release_eip=dict(type='bool', default=False), nat_gateway_id=dict(type='str'), client_token=dict(type='str'), )) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, mutually_exclusive=[['allocation_id', 'eip_address']], required_if=[['state', 'absent', ['nat_gateway_id']], ['state', 'present', ['subnet_id']]]) # Validate Requirements if not HAS_BOTO3: module.fail_json(msg='botocore/boto3 is required.') state = module.params.get('state').lower() check_mode = module.check_mode subnet_id = module.params.get('subnet_id') allocation_id = module.params.get('allocation_id') eip_address = module.params.get('eip_address') nat_gateway_id = module.params.get('nat_gateway_id') wait = module.params.get('wait') wait_timeout = module.params.get('wait_timeout') release_eip = module.params.get('release_eip') client_token = module.params.get('client_token') if_exist_do_not_create = module.params.get('if_exist_do_not_create') try: region, ec2_url, aws_connect_kwargs = (get_aws_connection_info( module, boto3=True)) client = (boto3_conn(module, conn_type='client', resource='ec2', region=region, endpoint=ec2_url, **aws_connect_kwargs)) except botocore.exceptions.ClientError as e: module.fail_json(msg="Boto3 Client Error - " + str(e.msg)) changed = False err_msg = '' if state == 'present': success, changed, err_msg, results = (pre_create( client, subnet_id, allocation_id, eip_address, if_exist_do_not_create, wait, wait_timeout, client_token, check_mode=check_mode)) else: success, changed, err_msg, results = (remove(client, nat_gateway_id, wait, wait_timeout, release_eip, check_mode=check_mode)) if not success: module.fail_json(msg=err_msg, success=success, changed=changed) else: module.exit_json(msg=err_msg, success=success, changed=changed, **results)
def main(): fields = { "host": { "required": True, "type": "str" }, "username": { "required": True, "type": "str" }, "password": { "required": False, "type": "str", "no_log": True }, "vdom": { "required": False, "type": "str", "default": "root" }, "https": { "required": False, "type": "bool", "default": "False" }, "spamfilter_dnsbl": { "required": False, "type": "dict", "options": { "state": { "required": True, "type": "str", "choices": ["present", "absent"] }, "comment": { "required": False, "type": "str" }, "entries": { "required": False, "type": "list", "options": { "action": { "required": False, "type": "str", "choices": ["reject", "spam"] }, "id": { "required": True, "type": "int" }, "server": { "required": False, "type": "str" }, "status": { "required": False, "type": "str", "choices": ["enable", "disable"] } } }, "id": { "required": True, "type": "int" }, "name": { "required": False, "type": "str" } } } } module = AnsibleModule(argument_spec=fields, supports_check_mode=False) try: from fortiosapi import FortiOSAPI except ImportError: module.fail_json(msg="fortiosapi module is required") global fos fos = FortiOSAPI() is_error, has_changed, result = fortios_spamfilter(module.params, fos) if not is_error: module.exit_json(changed=has_changed, meta=result) else: module.fail_json(msg="Error in repo", meta=result)
def main(): module = AnsibleModule( argument_spec=dict( paths=dict(type='list', required=True, aliases=['name', 'path']), patterns=dict(type='list', default=['*'], aliases=['pattern']), contains=dict(type='str'), file_type=dict(type='str', default="file", choices=['any', 'directory', 'file', 'link']), age=dict(type='str'), age_stamp=dict(type='str', default="mtime", choices=['atime', 'mtime', 'ctime']), size=dict(type='str'), recurse=dict(type='bool', default='no'), hidden=dict(type='bool', default='no'), follow=dict(type='bool', default='no'), get_checksum=dict(type='bool', default='no'), use_regex=dict(type='bool', default='no'), ), supports_check_mode=True, ) params = module.params filelist = [] if params['age'] is None: age = None else: # convert age to seconds: m = re.match("^(-?\d+)(s|m|h|d|w)?$", params['age'].lower()) seconds_per_unit = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800} if m: age = int(m.group(1)) * seconds_per_unit.get(m.group(2), 1) else: module.fail_json(age=params['age'], msg="failed to process age") if params['size'] is None: size = None else: # convert size to bytes: m = re.match("^(-?\d+)(b|k|m|g|t)?$", params['size'].lower()) bytes_per_unit = {"b": 1, "k": 1024, "m": 1024**2, "g": 1024**3, "t": 1024**4} if m: size = int(m.group(1)) * bytes_per_unit.get(m.group(2), 1) else: module.fail_json(size=params['size'], msg="failed to process size") now = time.time() msg = '' looked = 0 for npath in params['paths']: npath = os.path.expanduser(os.path.expandvars(npath)) if os.path.isdir(npath): ''' ignore followlinks for python version < 2.6 ''' for root, dirs, files in (sys.version_info < (2, 6, 0) and os.walk(npath)) or os.walk(npath, followlinks=params['follow']): looked = looked + len(files) + len(dirs) for fsobj in (files + dirs): fsname = os.path.normpath(os.path.join(root, fsobj)) if os.path.basename(fsname).startswith('.') and not params['hidden']: continue try: st = os.lstat(fsname) except: msg += "%s was skipped as it does not seem to be a valid file or it cannot be accessed\n" % fsname continue r = {'path': fsname} if params['file_type'] == 'any': if pfilter(fsobj, params['patterns'], params['use_regex']) and agefilter(st, now, age, params['age_stamp']): r.update(statinfo(st)) filelist.append(r) elif stat.S_ISDIR(st.st_mode) and params['file_type'] == 'directory': if pfilter(fsobj, params['patterns'], params['use_regex']) and agefilter(st, now, age, params['age_stamp']): r.update(statinfo(st)) filelist.append(r) elif stat.S_ISREG(st.st_mode) and params['file_type'] == 'file': if pfilter(fsobj, params['patterns'], params['use_regex']) and \ agefilter(st, now, age, params['age_stamp']) and \ sizefilter(st, size) and \ contentfilter(fsname, params['contains']): r.update(statinfo(st)) if params['get_checksum']: r['checksum'] = module.sha1(fsname) filelist.append(r) elif stat.S_ISLNK(st.st_mode) and params['file_type'] == 'link': if pfilter(fsobj, params['patterns'], params['use_regex']) and agefilter(st, now, age, params['age_stamp']): r.update(statinfo(st)) filelist.append(r) if not params['recurse']: break else: msg += "%s was skipped as it does not seem to be a valid directory or it cannot be accessed\n" % npath matched = len(filelist) module.exit_json(files=filelist, changed=False, msg=msg, matched=matched, examined=looked)
def main(): argument_spec = dict( server=dict(type='str'), peer=dict(type='str'), key_id=dict(type='str'), prefer=dict(type='str', choices=['enabled', 'disabled']), vrf_name=dict(type='str'), source_addr=dict(type='str'), source_int=dict(type='str'), state=dict(choices=['absent', 'present'], default='present'), ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=[ ['server', 'peer'], ['source_addr', 'source_int']], supports_check_mode=True) warnings = list() check_args(module, warnings) server = module.params['server'] or None peer = module.params['peer'] or None key_id = module.params['key_id'] prefer = module.params['prefer'] vrf_name = module.params['vrf_name'] source_addr = module.params['source_addr'] source_int = module.params['source_int'] state = module.params['state'] if source_int is not None: source_int = source_int.lower() if server: peer_type = 'server' address = server elif peer: peer_type = 'peer' address = peer else: peer_type = None address = None source_type = None source = None if source_addr: source_type = 'source' source = source_addr elif source_int: source_type = 'source-interface' source = source_int if key_id or vrf_name or prefer: if not server and not peer: module.fail_json( msg='Please supply the server or peer parameter') args = dict(peer_type=peer_type, address=address, key_id=key_id, prefer=prefer, vrf_name=vrf_name, source_type=source_type, source=source) proposed = dict((k, v) for k, v in args.items() if v is not None) existing, peer_server_list = get_ntp_existing(address, peer_type, module) end_state = existing changed = False commands = [] if state == 'present': delta = dict(set(proposed.items()).difference(existing.items())) if delta: command = config_ntp(delta, existing) if command: commands.append(command) elif state == 'absent': if existing.get('peer_type') and existing.get('address'): command = 'no ntp {0} {1}'.format( existing['peer_type'], existing['address']) if command: commands.append([command]) existing_source_type = existing.get('source_type') existing_source = existing.get('source') proposed_source_type = proposed.get('source_type') proposed_source = proposed.get('source') if proposed_source_type: if proposed_source_type == existing_source_type: if proposed_source == existing_source: command = 'no ntp {0} {1}'.format( existing_source_type, existing_source) if command: commands.append([command]) cmds = flatten_list(commands) if cmds: if module.check_mode: module.exit_json(changed=True, commands=cmds) else: changed = True load_config(module, cmds) end_state = get_ntp_existing(address, peer_type, module)[0] 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 results['peer_server_list'] = peer_server_list module.exit_json(**results)
def main(): module = AnsibleModule(argument_spec=get_argspec(), supports_check_mode=True) result = run_command(module) module.exit_json(**result)
def main(): argument_spec = dict( interface=dict(required=True, type='str'), description=dict(required=False, type='str'), host_reachability=dict(required=False, type='bool'), shutdown=dict(required=False, type='bool'), source_interface=dict(required=False, type='str'), source_interface_hold_down_time=dict(required=False, type='str'), m_facts=dict(required=False, default=False, type='bool'), state=dict(choices=['present', 'absent'], default='present', required=False), include_defaults=dict(default=True), config=dict(), save=dict(type='bool', default=False) ) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() check_args(module, warnings) state = module.params['state'] interface = module.params['interface'].lower() args = [ 'interface', 'description', 'host_reachability', 'shutdown', 'source_interface', 'source_interface_hold_down_time' ] existing = invoke('get_existing', module, args) end_state = existing proposed_args = dict((k, v) for k, v in module.params.items() if v is not None and k in args) proposed = {} for key, value in proposed_args.items(): if key != 'interface': if str(value).lower() == 'true': value = True elif str(value).lower() == 'false': value = False elif str(value).lower() == 'default': value = PARAM_TO_DEFAULT_KEYMAP.get(key) if value is None: if key in BOOL_PARAMS: value = False else: value = 'default' if existing.get(key) or (not existing.get(key) and value): proposed[key] = value result = {} if state == 'present' or (state == 'absent' and existing): if not existing: WARNINGS.append("The proposed NVE interface did not exist. " "It's recommended to use nxos_interface to create " "all logical interfaces.") candidate = CustomNetworkConfig(indent=3) invoke('state_%s' % state, module, existing, proposed, candidate) try: response = load_config(module, candidate) result.update(response) except ShellError: exc = get_exception() module.fail_json(msg=str(exc)) else: result['updates'] = [] result['connected'] = module.connected if module._verbosity > 0: end_state = invoke('get_existing', module, args) result['end_state'] = end_state result['existing'] = existing result['proposed'] = proposed_args if WARNINGS: result['warnings'] = WARNINGS module.exit_json(**result)
def main(): argument_spec = purefa_argument_spec() argument_spec.update( dict( name=dict(type="str", required=True), suffix=dict(type="str"), target=dict(type="str"), offload=dict(type="str"), ignore_repl=dict(type="bool", default=False), overwrite=dict(type="bool", default=False), eradicate=dict(type="bool", default=False), state=dict( type="str", default="present", choices=["absent", "copy", "present", "rename"], ), ) ) required_if = [("state", "copy", ["target", "suffix"])] module = AnsibleModule( argument_spec, required_if=required_if, supports_check_mode=True ) pattern = re.compile("^(?=.*[a-zA-Z-])[a-zA-Z0-9]([a-zA-Z0-9-]{0,63}[a-zA-Z0-9])?$") state = module.params["state"] if module.params["suffix"] is None: suffix = "snap-" + str( (datetime.utcnow() - datetime(1970, 1, 1, 0, 0, 0, 0)).total_seconds() ) module.params["suffix"] = suffix.replace(".", "") else: if not module.params["offload"]: if not pattern.match(module.params["suffix"]) and state not in [ "absent", "rename", ]: module.fail_json( msg="Suffix name {0} does not conform to suffix name rules".format( module.params["suffix"] ) ) if state == "rename" and module.params["target"] is not None: if not pattern.match(module.params["target"]): module.fail_json( msg="Suffix target {0} does not conform to suffix name rules".format( module.params["target"] ) ) array = get_system(module) api_version = array._list_available_rest_versions() if GET_SEND_API not in api_version: arrayv6 = None if module.params["offload"]: module.fail_json( msg="Purity 6.1, or higher, is required to support single volume offload snapshots" ) if state == "rename": module.fail_json( msg="Purity 6.1, or higher, is required to support snapshot rename" ) else: if not HAS_PURESTORAGE: module.fail_json(msg="py-pure-client sdk is required for this module") arrayv6 = get_array(module) if module.params["offload"]: if not _check_offload(module, arrayv6) and not _check_target( module, arrayv6 ): module.fail_json( msg="Selected offload {0} not connected.".format( module.params["offload"] ) ) if ( state == "copy" and module.params["offload"] and not _check_target(module, arrayv6) ): module.fail_json( msg="Snapshot copy is not supported when an offload target is defined" ) destroyed = False array_snap = offload_snap = False volume = get_volume(module, array) if module.params["offload"] and not _check_target(module, arrayv6): offload_snap = _check_offload_snapshot(module, arrayv6) if offload_snap is None: offload_snap = False else: offload_snap = not offload_snap.destroyed else: array_snap = get_snapshot(module, array) snap = array_snap or offload_snap if not snap: destroyed = get_deleted_snapshot(module, array, arrayv6) if state == "present" and volume and not destroyed: create_snapshot(module, array, arrayv6) elif state == "present" and volume and destroyed: recover_snapshot(module, array, arrayv6) elif state == "rename" and volume and snap: update_snapshot(module, arrayv6) elif state == "copy" and snap: create_from_snapshot(module, array) elif state == "absent" and snap and not destroyed: delete_snapshot(module, array, arrayv6) elif state == "absent" and destroyed and module.params["eradicate"]: eradicate_snapshot(module, array, arrayv6) elif state == "absent" and not snap: module.exit_json(changed=False) module.exit_json(changed=False)
def main(): fields = { "host": { "required": False, "type": "str" }, "username": { "required": False, "type": "str" }, "password": { "required": False, "type": "str", "default": "", "no_log": True }, "vdom": { "required": False, "type": "str", "default": "root" }, "https": { "required": False, "type": "bool", "default": True }, "ssl_verify": { "required": False, "type": "bool", "default": True }, "state": { "required": True, "type": "str", "choices": ["present", "absent"] }, "switch_controller_qos_queue_policy": { "required": False, "type": "dict", "default": None, "options": { "cos_queue": { "required": False, "type": "list", "options": { "description": { "required": False, "type": "str" }, "drop_policy": { "required": False, "type": "str", "choices": ["taildrop", "weighted-random-early-detection"] }, "max_rate": { "required": False, "type": "int" }, "min_rate": { "required": False, "type": "int" }, "name": { "required": True, "type": "str" }, "weight": { "required": False, "type": "int" } } }, "name": { "required": True, "type": "str" }, "schedule": { "required": False, "type": "str", "choices": ["strict", "round-robin", "weighted"] } } } } module = AnsibleModule(argument_spec=fields, supports_check_mode=False) # legacy_mode refers to using fortiosapi instead of HTTPAPI legacy_mode = 'host' in module.params and module.params['host'] is not None and \ 'username' in module.params and module.params['username'] is not None and \ 'password' in module.params and module.params['password'] is not None if not legacy_mode: if module._socket_path: connection = Connection(module._socket_path) fos = FortiOSHandler(connection) is_error, has_changed, result = fortios_switch_controller_qos( module.params, fos) else: module.fail_json(**FAIL_SOCKET_MSG) else: try: from fortiosapi import FortiOSAPI except ImportError: module.fail_json(msg="fortiosapi module is required") fos = FortiOSAPI() login(module.params, fos) is_error, has_changed, result = fortios_switch_controller_qos( module.params, fos) fos.logout() if not is_error: module.exit_json(changed=has_changed, meta=result) else: module.fail_json(msg="Error in repo", meta=result)
def main(): mkeyname = 'name' fields = { "access_token": { "required": False, "type": "str", "no_log": True }, "vdom": { "required": False, "type": "str", "default": "root" }, "state": { "required": True, "type": "str", "choices": ["present", "absent"] }, "certificate_crl": { "required": False, "type": "dict", "default": None, "options": { "crl": { "required": False, "type": "str" }, "http_url": { "required": False, "type": "str" }, "last_updated": { "required": False, "type": "int" }, "ldap_password": { "required": False, "type": "str" }, "ldap_server": { "required": False, "type": "str" }, "ldap_username": { "required": False, "type": "str" }, "name": { "required": True, "type": "str" }, "range": { "required": False, "type": "str", "choices": ["global", "vdom"] }, "scep_cert": { "required": False, "type": "str" }, "scep_url": { "required": False, "type": "str" }, "source": { "required": False, "type": "str", "choices": ["factory", "user", "bundle"] }, "source_ip": { "required": False, "type": "str" }, "update_interval": { "required": False, "type": "int" }, "update_vdom": { "required": False, "type": "str" } } } } 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_certificate(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)
def main(): argument_spec = vmware_argument_spec() argument_spec.update({ 'name': {}, 'datastore': { 'default': 'datastore1', }, 'datacenter': { 'default': 'ha-datacenter', }, 'cluster': { 'default': None, }, 'deployment_option': { 'default': None, }, 'folder': { 'default': None, }, 'resource_pool': { 'default': 'Resources', }, 'networks': { 'default': { 'VM Network': 'VM Network', }, 'type': 'dict', }, 'ovf': { 'type': path_exists, 'aliases': ['ova'], }, 'disk_provisioning': { 'choices': [ 'flat', 'eagerZeroedThick', 'monolithicSparse', 'twoGbMaxExtentSparse', 'twoGbMaxExtentFlat', 'thin', 'sparse', 'thick', 'seSparse', 'monolithicFlat' ], 'default': 'thin', }, 'power_on': { 'type': 'bool', 'default': True, }, 'properties': { 'type': 'dict', }, 'wait': { 'type': 'bool', 'default': True, }, 'wait_for_ip_address': { 'type': 'bool', 'default': False, }, 'allow_duplicates': { 'type': 'bool', 'default': True, }, 'fail_on_spec_warnings': { 'type': 'bool', 'default': False, }, }) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, ) if not HAS_PYVMOMI: module.fail_json(msg='pyvmomi python library not found') deploy_ovf = VMwareDeployOvf(module) deploy_ovf.upload() deploy_ovf.complete() facts = deploy_ovf.power_on() module.exit_json(instance=facts, changed=True)
class NetAppOntapIgroupInitiator(object): def __init__(self): self.argument_spec = netapp_utils.na_ontap_host_argument_spec() self.argument_spec.update( dict( state=dict(required=False, choices=['present', 'absent'], default='present'), names=dict(required=True, type='list', aliases=['name']), initiator_group=dict(required=True, type='str'), vserver=dict(required=True, type='str'), )) self.module = AnsibleModule(argument_spec=self.argument_spec, supports_check_mode=True) self.na_helper = NetAppModule() self.parameters = self.na_helper.set_parameters(self.module.params) if HAS_NETAPP_LIB is False: self.module.fail_json( msg="the python NetApp-Lib module is required") else: self.server = netapp_utils.setup_na_ontap_zapi( module=self.module, vserver=self.parameters['vserver']) def get_initiators(self): """ Get the existing list of initiators from an igroup :rtype: list() or None """ igroup_info = netapp_utils.zapi.NaElement('igroup-get-iter') attributes = dict( query={ 'initiator-group-info': { 'initiator-group-name': self.parameters['initiator_group'], 'vserver': self.parameters['vserver'] } }) igroup_info.translate_struct(attributes) result, current = None, [] try: result = self.server.invoke_successfully(igroup_info, True) except netapp_utils.zapi.NaApiError as error: self.module.fail_json( msg='Error fetching igroup info %s: %s' % (self.parameters['initiator_group'], to_native(error)), exception=traceback.format_exc()) if result.get_child_by_name('num-records') and int( result.get_child_content('num-records')) >= 1: igroup_info = result.get_child_by_name( 'attributes-list').get_child_by_name('initiator-group-info') if igroup_info.get_child_by_name('initiators') is not None: current = [ initiator['initiator-name'] for initiator in igroup_info['initiators'].get_children() ] return current def modify_initiator(self, initiator_name, zapi): """ Add or remove an initiator to/from an igroup """ options = { 'initiator-group-name': self.parameters['initiator_group'], 'initiator': initiator_name } initiator_modify = netapp_utils.zapi.NaElement.create_node_with_children( zapi, **options) try: self.server.invoke_successfully(initiator_modify, enable_tunneling=True) except netapp_utils.zapi.NaApiError as error: self.module.fail_json( msg='Error modifying igroup initiator %s: %s' % (initiator_name, to_native(error)), exception=traceback.format_exc()) def autosupport_log(self): netapp_utils.ems_log_event("na_ontap_igroup_initiator", self.server) def apply(self): self.autosupport_log() initiators = self.get_initiators() for initiator in self.parameters['names']: present = None if initiator in initiators: present = True cd_action = self.na_helper.get_cd_action(present, self.parameters) if self.na_helper.changed: if self.module.check_mode: pass else: if cd_action == 'create': self.modify_initiator(initiator, 'igroup-add') elif cd_action == 'delete': self.modify_initiator(initiator, 'igroup-remove') self.module.exit_json(changed=self.na_helper.changed)
def main(): """ Module main function """ argument_spec = dict( state=dict(choices=['present', 'absent'], default='present'), acl_number=dict(type='str'), usm_user_name=dict(type='str'), remote_engine_id=dict(type='str'), user_group=dict(type='str'), auth_protocol=dict(choices=['noAuth', 'md5', 'sha']), auth_key=dict(type='str', no_log=True), priv_protocol=dict(choices=[ 'noPriv', 'des56', '3des168', 'aes128', 'aes192', 'aes256' ]), priv_key=dict(type='str', no_log=True), aaa_local_user=dict(type='str')) mutually_exclusive = [("usm_user_name", "local_user_name")] argument_spec.update(ce_argument_spec) module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=mutually_exclusive, supports_check_mode=True) changed = False proposed = dict() existing = dict() end_state = dict() updates = [] state = module.params['state'] acl_number = module.params['acl_number'] usm_user_name = module.params['usm_user_name'] remote_engine_id = module.params['remote_engine_id'] user_group = module.params['user_group'] auth_protocol = module.params['auth_protocol'] auth_key = module.params['auth_key'] priv_protocol = module.params['priv_protocol'] priv_key = module.params['priv_key'] aaa_local_user = module.params['aaa_local_user'] snmp_user_obj = SnmpUser() if not snmp_user_obj: module.fail_json(msg='Error: Init module failed.') # get proposed proposed["state"] = state if acl_number: proposed["acl_number"] = acl_number if usm_user_name: proposed["usm_user_name"] = usm_user_name if remote_engine_id: proposed["remote_engine_id"] = remote_engine_id if user_group: proposed["user_group"] = user_group if auth_protocol: proposed["auth_protocol"] = auth_protocol if auth_key: proposed["auth_key"] = auth_key if priv_protocol: proposed["priv_protocol"] = priv_protocol if priv_key: proposed["priv_key"] = priv_key if aaa_local_user: proposed["aaa_local_user"] = aaa_local_user snmp_v3_usm_user_rst = snmp_user_obj.check_snmp_v3_usm_user_args( module=module) snmp_v3_local_user_rst = snmp_user_obj.check_snmp_v3_local_user_args( module=module) snmp_user_obj.get_snmp_local_engine(module=module) # state exist snmp v3 user config exist_tmp = dict() for item in snmp_v3_usm_user_rst: if item != "need_cfg": exist_tmp[item] = snmp_v3_usm_user_rst[item] if exist_tmp: existing["snmp usm user"] = exist_tmp exist_tmp = dict() for item in snmp_v3_local_user_rst: if item != "need_cfg": exist_tmp[item] = snmp_v3_local_user_rst[item] if exist_tmp: existing["snmp local user"] = exist_tmp if state == "present": if snmp_v3_usm_user_rst["need_cfg"]: if len(snmp_v3_usm_user_rst["usm_user_info"]) != 0: cmd = snmp_user_obj.merge_snmp_v3_usm_user(module=module) changed = True updates.append(cmd) else: cmd = snmp_user_obj.create_snmp_v3_usm_user(module=module) changed = True updates.append(cmd) if snmp_v3_local_user_rst["need_cfg"]: if len(snmp_v3_local_user_rst["local_user_info"]) != 0: cmd = snmp_user_obj.merge_snmp_v3_local_user(module=module) changed = True updates.append(cmd) else: cmd = snmp_user_obj.create_snmp_v3_local_user(module=module) changed = True updates.append(cmd) else: if snmp_v3_usm_user_rst["need_cfg"]: cmd = snmp_user_obj.delete_snmp_v3_usm_user(module=module) changed = True updates.append(cmd) if snmp_v3_local_user_rst["need_cfg"]: cmd = snmp_user_obj.delete_snmp_v3_local_user(module=module) changed = True updates.append(cmd) # state exist snmp v3 user config snmp_v3_usm_user_rst = snmp_user_obj.check_snmp_v3_usm_user_args( module=module) end_tmp = dict() for item in snmp_v3_usm_user_rst: if item != "need_cfg": end_tmp[item] = snmp_v3_usm_user_rst[item] if end_tmp: end_state["snmp usm user"] = end_tmp snmp_v3_local_user_rst = snmp_user_obj.check_snmp_v3_local_user_args( module=module) end_tmp = dict() for item in snmp_v3_local_user_rst: if item != "need_cfg": end_tmp[item] = snmp_v3_local_user_rst[item] if end_tmp: end_state["snmp local user"] = end_tmp results = dict() results['proposed'] = proposed results['existing'] = existing results['changed'] = changed results['end_state'] = end_state results['updates'] = updates module.exit_json(**results)
def main(): module = AnsibleModule( argument_spec=dict( state=dict(default='present', choices=['present', 'absent'], type='str'), digest=dict(default='sha256', type='str'), privatekey_path=dict(require=True, type='path'), privatekey_passphrase=dict(type='str', no_log=True), version=dict(default='1', type='int'), force=dict(default=False, type='bool'), path=dict(required=True, type='path'), subject=dict(type='dict'), countryName=dict(aliases=['C', 'country_name'], type='str'), stateOrProvinceName=dict(aliases=['ST', 'state_or_province_name'], type='str'), localityName=dict(aliases=['L', 'locality_name'], type='str'), organizationName=dict(aliases=['O', 'organization_name'], type='str'), organizationalUnitName=dict(aliases=['OU', 'organizational_unit_name'], type='str'), commonName=dict(aliases=['CN', 'common_name'], type='str'), emailAddress=dict(aliases=['E', 'email_address'], type='str'), subjectAltName=dict(aliases=['subject_alt_name'], type='list'), subjectAltName_critical=dict(aliases=['subject_alt_name_critical'], default=False, type='bool'), keyUsage=dict(aliases=['key_usage'], type='list'), keyUsage_critical=dict(aliases=['key_usage_critical'], default=False, type='bool'), extendedKeyUsage=dict(aliases=['extKeyUsage', 'extended_key_usage'], type='list'), extendedKeyUsage_critical=dict(aliases=['extKeyUsage_critical', 'extended_key_usage_critical'], default=False, type='bool'), basicConstraints=dict(aliases=['basic_constraints'], type='list'), basicConstraints_critical=dict(aliases=['basic_constraints_critical'], default=False, type='bool'), ocspMustStaple=dict(aliases=['ocsp_must_staple'], default=False, type='bool'), ocspMustStaple_critical=dict(aliases=['ocsp_must_staple_critical'], default=False, type='bool'), ), add_file_common_args=True, supports_check_mode=True, ) if not pyopenssl_found: module.fail_json(msg='the python pyOpenSSL module is required') try: getattr(crypto.X509Req, 'get_extensions') except AttributeError: module.fail_json(msg='You need to have PyOpenSSL>=0.15 to generate CSRs') base_dir = os.path.dirname(module.params['path']) or '.' if not os.path.isdir(base_dir): module.fail_json(name=base_dir, msg='The directory %s does not exist or the file is not a directory' % base_dir) csr = CertificateSigningRequest(module) if module.params['state'] == 'present': if module.check_mode: result = csr.dump() result['changed'] = module.params['force'] or not csr.check(module) module.exit_json(**result) try: csr.generate(module) except (CertificateSigningRequestError, crypto_utils.OpenSSLObjectError) as exc: module.fail_json(msg=to_native(exc)) else: if module.check_mode: result = csr.dump() result['changed'] = os.path.exists(module.params['path']) module.exit_json(**result) try: csr.remove() except (CertificateSigningRequestError, crypto_utils.OpenSSLObjectError) as exc: module.fail_json(msg=to_native(exc)) result = csr.dump() module.exit_json(**result)
def main(): jrpc_urls = [ '/cli/global/system/auto-delete' ] perobject_jrpc_urls = [ '/cli/global/system/auto-delete/{auto-delete}' ] url_params = [] module_primary_key = None module_arg_spec = { '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' }, 'system_autodelete': { 'required': False, 'type': 'dict', 'options': { 'dlp-files-auto-deletion': { 'required': False, 'type': 'dict', 'options': { 'retention': { 'required': False, 'choices': [ 'days', 'weeks', 'months' ], 'type': 'str' }, 'runat': { 'required': False, 'type': 'int' }, 'status': { 'required': False, 'choices': [ 'disable', 'enable' ], 'type': 'str' }, 'value': { 'required': False, 'type': 'int' } } }, 'log-auto-deletion': { 'required': False, 'type': 'dict', 'options': { 'retention': { 'required': False, 'choices': [ 'days', 'weeks', 'months' ], 'type': 'str' }, 'runat': { 'required': False, 'type': 'int' }, 'status': { 'required': False, 'choices': [ 'disable', 'enable' ], 'type': 'str' }, 'value': { 'required': False, 'type': 'int' } } }, 'quarantine-files-auto-deletion': { 'required': False, 'type': 'dict', 'options': { 'retention': { 'required': False, 'choices': [ 'days', 'weeks', 'months' ], 'type': 'str' }, 'runat': { 'required': False, 'type': 'int' }, 'status': { 'required': False, 'choices': [ 'disable', 'enable' ], 'type': 'str' }, 'value': { 'required': False, 'type': 'int' } } }, 'report-auto-deletion': { 'required': False, 'type': 'dict', 'options': { 'retention': { 'required': False, 'choices': [ 'days', 'weeks', 'months' ], 'type': 'str' }, 'runat': { 'required': False, 'type': 'int' }, 'status': { 'required': False, 'choices': [ 'disable', 'enable' ], 'type': 'str' }, 'value': { 'required': False, 'type': 'int' } } }, 'status-fake': { 'required': False, 'type': 'int' } } } } params_validation_blob = [] check_galaxy_version(module_arg_spec) module = AnsibleModule(argument_spec=check_parameter_bypass(module_arg_spec, 'system_autodelete'), supports_check_mode=False) fmgr = None if module._socket_path: connection = Connection(module._socket_path) 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_partial_curd() else: module.fail_json(msg='MUST RUN IN HTTPAPI MODE') module.exit_json(meta=module.params)
def main(): fields = { "host": { "required": False, "type": "str" }, "username": { "required": False, "type": "str" }, "password": { "required": False, "type": "str", "default": "", "no_log": True }, "vdom": { "required": False, "type": "str", "default": "root" }, "https": { "required": False, "type": "bool", "default": True }, "ssl_verify": { "required": False, "type": "bool", "default": True }, "state": { "required": False, "type": "str", "choices": ["present", "absent"] }, "firewall_vip6": { "required": False, "type": "dict", "default": None, "options": { "state": { "required": False, "type": "str", "choices": ["present", "absent"] }, "arp_reply": { "required": False, "type": "str", "choices": ["disable", "enable"] }, "color": { "required": False, "type": "int" }, "comment": { "required": False, "type": "str" }, "extip": { "required": False, "type": "str" }, "extport": { "required": False, "type": "str" }, "http_cookie_age": { "required": False, "type": "int" }, "http_cookie_domain": { "required": False, "type": "str" }, "http_cookie_domain_from_host": { "required": False, "type": "str", "choices": ["disable", "enable"] }, "http_cookie_generation": { "required": False, "type": "int" }, "http_cookie_path": { "required": False, "type": "str" }, "http_cookie_share": { "required": False, "type": "str", "choices": ["disable", "same-ip"] }, "http_ip_header": { "required": False, "type": "str", "choices": ["enable", "disable"] }, "http_ip_header_name": { "required": False, "type": "str" }, "http_multiplex": { "required": False, "type": "str", "choices": ["enable", "disable"] }, "https_cookie_secure": { "required": False, "type": "str", "choices": ["disable", "enable"] }, "id": { "required": False, "type": "int" }, "ldb_method": { "required": False, "type": "str", "choices": [ "static", "round-robin", "weighted", "least-session", "least-rtt", "first-alive", "http-host" ] }, "mappedip": { "required": False, "type": "str" }, "mappedport": { "required": False, "type": "str" }, "max_embryonic_connections": { "required": False, "type": "int" }, "monitor": { "required": False, "type": "list", "options": { "name": { "required": True, "type": "str" } } }, "name": { "required": True, "type": "str" }, "outlook_web_access": { "required": False, "type": "str", "choices": ["disable", "enable"] }, "persistence": { "required": False, "type": "str", "choices": ["none", "http-cookie", "ssl-session-id"] }, "portforward": { "required": False, "type": "str", "choices": ["disable", "enable"] }, "protocol": { "required": False, "type": "str", "choices": ["tcp", "udp", "sctp"] }, "realservers": { "required": False, "type": "list", "options": { "client_ip": { "required": False, "type": "str" }, "healthcheck": { "required": False, "type": "str", "choices": ["disable", "enable", "vip"] }, "holddown_interval": { "required": False, "type": "int" }, "http_host": { "required": False, "type": "str" }, "id": { "required": True, "type": "int" }, "ip": { "required": False, "type": "str" }, "max_connections": { "required": False, "type": "int" }, "monitor": { "required": False, "type": "str" }, "port": { "required": False, "type": "int" }, "status": { "required": False, "type": "str", "choices": ["active", "standby", "disable"] }, "weight": { "required": False, "type": "int" } } }, "server_type": { "required": False, "type": "str", "choices": [ "http", "https", "imaps", "pop3s", "smtps", "ssl", "tcp", "udp", "ip" ] }, "src_filter": { "required": False, "type": "list", "options": { "range": { "required": True, "type": "str" } } }, "ssl_algorithm": { "required": False, "type": "str", "choices": ["high", "medium", "low", "custom"] }, "ssl_certificate": { "required": False, "type": "str" }, "ssl_cipher_suites": { "required": False, "type": "list", "options": { "cipher": { "required": False, "type": "str", "choices": [ "TLS-RSA-WITH-3DES-EDE-CBC-SHA", "TLS-DHE-RSA-WITH-DES-CBC-SHA", "TLS-DHE-DSS-WITH-DES-CBC-SHA" ] }, "priority": { "required": True, "type": "int" }, "versions": { "required": False, "type": "str", "choices": ["ssl-3.0", "tls-1.0", "tls-1.1", "tls-1.2"] } } }, "ssl_client_fallback": { "required": False, "type": "str", "choices": ["disable", "enable"] }, "ssl_client_renegotiation": { "required": False, "type": "str", "choices": ["allow", "deny", "secure"] }, "ssl_client_session_state_max": { "required": False, "type": "int" }, "ssl_client_session_state_timeout": { "required": False, "type": "int" }, "ssl_client_session_state_type": { "required": False, "type": "str", "choices": ["disable", "time", "count", "both"] }, "ssl_dh_bits": { "required": False, "type": "str", "choices": ["768", "1024", "1536", "2048", "3072", "4096"] }, "ssl_hpkp": { "required": False, "type": "str", "choices": ["disable", "enable", "report-only"] }, "ssl_hpkp_age": { "required": False, "type": "int" }, "ssl_hpkp_backup": { "required": False, "type": "str" }, "ssl_hpkp_include_subdomains": { "required": False, "type": "str", "choices": ["disable", "enable"] }, "ssl_hpkp_primary": { "required": False, "type": "str" }, "ssl_hpkp_report_uri": { "required": False, "type": "str" }, "ssl_hsts": { "required": False, "type": "str", "choices": ["disable", "enable"] }, "ssl_hsts_age": { "required": False, "type": "int" }, "ssl_hsts_include_subdomains": { "required": False, "type": "str", "choices": ["disable", "enable"] }, "ssl_http_location_conversion": { "required": False, "type": "str", "choices": ["enable", "disable"] }, "ssl_http_match_host": { "required": False, "type": "str", "choices": ["enable", "disable"] }, "ssl_max_version": { "required": False, "type": "str", "choices": ["ssl-3.0", "tls-1.0", "tls-1.1", "tls-1.2"] }, "ssl_min_version": { "required": False, "type": "str", "choices": ["ssl-3.0", "tls-1.0", "tls-1.1", "tls-1.2"] }, "ssl_mode": { "required": False, "type": "str", "choices": ["half", "full"] }, "ssl_pfs": { "required": False, "type": "str", "choices": ["require", "deny", "allow"] }, "ssl_send_empty_frags": { "required": False, "type": "str", "choices": ["enable", "disable"] }, "ssl_server_algorithm": { "required": False, "type": "str", "choices": ["high", "medium", "low", "custom", "client"] }, "ssl_server_cipher_suites": { "required": False, "type": "list", "options": { "cipher": { "required": False, "type": "str", "choices": [ "TLS-RSA-WITH-3DES-EDE-CBC-SHA", "TLS-DHE-RSA-WITH-DES-CBC-SHA", "TLS-DHE-DSS-WITH-DES-CBC-SHA" ] }, "priority": { "required": True, "type": "int" }, "versions": { "required": False, "type": "str", "choices": ["ssl-3.0", "tls-1.0", "tls-1.1", "tls-1.2"] } } }, "ssl_server_max_version": { "required": False, "type": "str", "choices": ["ssl-3.0", "tls-1.0", "tls-1.1", "tls-1.2", "client"] }, "ssl_server_min_version": { "required": False, "type": "str", "choices": ["ssl-3.0", "tls-1.0", "tls-1.1", "tls-1.2", "client"] }, "ssl_server_session_state_max": { "required": False, "type": "int" }, "ssl_server_session_state_timeout": { "required": False, "type": "int" }, "ssl_server_session_state_type": { "required": False, "type": "str", "choices": ["disable", "time", "count", "both"] }, "type": { "required": False, "type": "str", "choices": ["static-nat", "server-load-balance"] }, "uuid": { "required": False, "type": "str" }, "weblogic_server": { "required": False, "type": "str", "choices": ["disable", "enable"] }, "websphere_server": { "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_firewall( module.params, fos) else: module.fail_json(**FAIL_SOCKET_MSG) else: try: from fortiosapi import FortiOSAPI except ImportError: module.fail_json(msg="fortiosapi module is required") fos = FortiOSAPI() login(module.params, fos) is_error, has_changed, result = fortios_firewall(module.params, fos) fos.logout() if not is_error: module.exit_json(changed=has_changed, meta=result) else: module.fail_json(msg="Error in repo", meta=result)
def main(): fields = { "host": {"required": False, "type": "str"}, "username": {"required": False, "type": "str"}, "password": {"required": False, "type": "str", "default": "", "no_log": True}, "vdom": {"required": False, "type": "str", "default": "root"}, "https": {"required": False, "type": "bool", "default": True}, "ssl_verify": {"required": False, "type": "bool", "default": True}, "log_fortianalyzer_setting": { "required": False, "type": "dict", "default": None, "options": { "__change_ip": {"required": False, "type": "int"}, "certificate": {"required": False, "type": "str"}, "conn_timeout": {"required": False, "type": "int"}, "enc_algorithm": {"required": False, "type": "str", "choices": ["high-medium", "high", "low"]}, "faz_type": {"required": False, "type": "int"}, "hmac_algorithm": {"required": False, "type": "str", "choices": ["sha256", "sha1"]}, "ips_archive": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "mgmt_name": {"required": False, "type": "str"}, "monitor_failure_retry_period": {"required": False, "type": "int"}, "monitor_keepalive_period": {"required": False, "type": "int"}, "reliable": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "server": {"required": False, "type": "str"}, "source_ip": {"required": False, "type": "str"}, "ssl_min_proto_version": {"required": False, "type": "str", "choices": ["default", "SSLv3", "TLSv1", "TLSv1-1", "TLSv1-2"]}, "status": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "upload_day": {"required": False, "type": "str"}, "upload_interval": {"required": False, "type": "str", "choices": ["daily", "weekly", "monthly"]}, "upload_option": {"required": False, "type": "str", "choices": ["store-and-upload", "realtime", "1-minute", "5-minute"]}, "upload_time": {"required": False, "type": "str"} } } } module = AnsibleModule(argument_spec=fields, supports_check_mode=False) # legacy_mode refers to using fortiosapi instead of HTTPAPI legacy_mode = 'host' in module.params and module.params['host'] is not None and \ 'username' in module.params and module.params['username'] is not None and \ 'password' in module.params and module.params['password'] is not None if not legacy_mode: if module._socket_path: connection = Connection(module._socket_path) fos = FortiOSHandler(connection) is_error, has_changed, result = fortios_log_fortianalyzer(module.params, fos) else: module.fail_json(**FAIL_SOCKET_MSG) else: try: from fortiosapi import FortiOSAPI except ImportError: module.fail_json(msg="fortiosapi module is required") fos = FortiOSAPI() login(module.params, fos) is_error, has_changed, result = fortios_log_fortianalyzer(module.params, fos) fos.logout() if not is_error: module.exit_json(changed=has_changed, meta=result) else: module.fail_json(msg="Error in repo", meta=result)
def main(): """main entry point for module execution """ argument_spec = dict( gather_subset=dict(default=['!config'], type='list') ) argument_spec.update(enos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) gather_subset = module.params['gather_subset'] runable_subsets = set() exclude_subsets = set() for subset in gather_subset: if subset == 'all': runable_subsets.update(VALID_SUBSETS) continue if subset.startswith('!'): subset = subset[1:] if subset == 'all': exclude_subsets.update(VALID_SUBSETS) continue exclude = True else: exclude = False if subset not in VALID_SUBSETS: module.fail_json(msg='Bad subset') if exclude: exclude_subsets.add(subset) else: runable_subsets.add(subset) if not runable_subsets: runable_subsets.update(VALID_SUBSETS) runable_subsets.difference_update(exclude_subsets) runable_subsets.add('default') facts = dict() facts['gather_subset'] = list(runable_subsets) instances = list() for key in runable_subsets: instances.append(FACT_SUBSETS[key](module)) for inst in instances: inst.populate() facts.update(inst.facts) ansible_facts = dict() for key, value in iteritems(facts): key = 'ansible_net_%s' % key ansible_facts[key] = value warnings = list() check_args(module, warnings) module.exit_json(ansible_facts=ansible_facts, warnings=warnings)
def main(): argument_spec = aci_argument_spec() argument_spec.update( dst_group=dict(type='str', required=False, aliases=['name']), # Not required for querying all objects tenant=dict(type='str', required=False, aliases=['tenant_name']), # Not required for querying all objects description=dict(type='str', aliases=['descr']), state=dict(type='str', default='present', choices=['absent', 'present', 'query']), method=dict(type='str', choices=['delete', 'get', 'post'], aliases=['action'], removed_in_version='2.6'), # Deprecated starting from v2.6 ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, required_if=[ ['state', 'absent', ['dst_group', 'tenant']], ['state', 'present', ['dst_group', 'tenant']], ], ) dst_group = module.params['dst_group'] description = module.params['description'] state = module.params['state'] tenant = module.params['tenant'] aci = ACIModule(module) aci.construct_url( root_class=dict( aci_class='fvTenant', aci_rn='tn-{0}'.format(tenant), filter_target='eq(fvTenant.name, "{0}")'.format(tenant), module_object=tenant, ), subclass_1=dict( aci_class='spanDestGrp', aci_rn='destgrp-{0}'.format(dst_group), filter_target='eq(spanDestGrp.name, "{0}")'.format(dst_group), module_object=dst_group, ), ) aci.get_existing() if state == 'present': # Filter out module parameters with null values aci.payload( aci_class='spanDestGrp', class_config=dict( name=dst_group, descr=description, ), ) # Generate config diff which will be used as POST request body aci.get_diff(aci_class='spanDestGrp') # Submit changes if module not in check_mode and the proposed is different than existing aci.post_config() elif state == 'absent': aci.delete_config() module.exit_json(**aci.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_vxlan": { "required": False, "type": "dict", "default": None, "options": { "dstport": { "required": False, "type": "int" }, "interface": { "required": False, "type": "str" }, "ip_version": { "required": False, "type": "str", "choices": [ "ipv4-unicast", "ipv6-unicast", "ipv4-multicast", "ipv6-multicast" ] }, "multicast_ttl": { "required": False, "type": "int" }, "name": { "required": True, "type": "str" }, "remote_ip": { "required": False, "type": "list", "options": { "ip": { "required": True, "type": "str" } } }, "remote_ip6": { "required": False, "type": "list", "options": { "ip6": { "required": True, "type": "str" } } }, "vni": { "required": False, "type": "int" } } } } module = AnsibleModule(argument_spec=fields, supports_check_mode=False) # legacy_mode refers to using fortiosapi instead of HTTPAPI legacy_mode = 'host' in module.params and module.params['host'] is not None and \ 'username' in module.params and module.params['username'] is not None and \ 'password' in module.params and module.params['password'] is not None if not legacy_mode: if module._socket_path: connection = Connection(module._socket_path) fos = FortiOSHandler(connection) is_error, has_changed, result = fortios_system(module.params, fos) else: module.fail_json(**FAIL_SOCKET_MSG) else: try: from fortiosapi import FortiOSAPI except ImportError: module.fail_json(msg="fortiosapi module is required") fos = FortiOSAPI() login(module.params, fos) is_error, has_changed, result = fortios_system(module.params, fos) fos.logout() if not is_error: module.exit_json(changed=has_changed, meta=result) else: module.fail_json(msg="Error in repo", meta=result)
def main(): result = {} module = AnsibleModule( argument_spec=dict( category=dict(required=True), command=dict(required=True, type='list'), baseuri=dict(required=True), username=dict(required=True), password=dict(required=True, no_log=True), bios_attribute_name=dict(default='null'), bios_attribute_value=dict(default='null', type='raw'), timeout=dict(type='int', default=10) ), supports_check_mode=False ) category = module.params['category'] command_list = module.params['command'] # admin credentials used for authentication creds = {'user': module.params['username'], 'pswd': module.params['password']} # timeout timeout = module.params['timeout'] # BIOS attributes to update bios_attributes = {'bios_attr_name': module.params['bios_attribute_name'], 'bios_attr_value': module.params['bios_attribute_value']} # Build root URI root_uri = "https://" + module.params['baseuri'] rf_uri = "/redfish/v1/" rf_utils = RedfishUtils(creds, root_uri, timeout) # Check that Category is valid if category not in CATEGORY_COMMANDS_ALL: module.fail_json(msg=to_native("Invalid Category '%s'. Valid Categories = %s" % (category, CATEGORY_COMMANDS_ALL.keys()))) # Check that all commands are valid for cmd in command_list: # Fail if even one command given is invalid if cmd not in CATEGORY_COMMANDS_ALL[category]: module.fail_json(msg=to_native("Invalid Command '%s'. Valid Commands = %s" % (cmd, CATEGORY_COMMANDS_ALL[category]))) # Organize by Categories / Commands if category == "Systems": # execute only if we find a System resource result = rf_utils._find_systems_resource(rf_uri) if result['ret'] is False: module.fail_json(msg=to_native(result['msg'])) for command in command_list: if command == "SetBiosDefaultSettings": result = rf_utils.set_bios_default_settings() elif command == "SetBiosAttributes": result = rf_utils.set_bios_attributes(bios_attributes) # Return data back or fail with proper message if result['ret'] is True: module.exit_json(changed=result['changed'], msg=to_native(result['msg'])) else: module.fail_json(msg=to_native(result['msg']))
def main(): arg_spec = dict( name=dict(required=True), state=dict(required=False, default='present', choices=['present', 'latest'], type='str'), virtualenv=dict(default=None, required=False), virtualenv_site_packages=dict(default='no', type='bool'), virtualenv_command=dict(default='virtualenv', required=False), executable=dict(default='easy_install', required=False), ) module = AnsibleModule(argument_spec=arg_spec, supports_check_mode=True) name = module.params['name'] env = module.params['virtualenv'] executable = module.params['executable'] site_packages = module.params['virtualenv_site_packages'] virtualenv_command = module.params['virtualenv_command'] executable_arguments = [] if module.params['state'] == 'latest': executable_arguments.append('--upgrade') rc = 0 err = '' out = '' if env: virtualenv = module.get_bin_path(virtualenv_command, True) if not os.path.exists(os.path.join(env, 'bin', 'activate')): if module.check_mode: module.exit_json(changed=True) command = '%s %s' % (virtualenv, env) if site_packages: command += ' --system-site-packages' cwd = tempfile.gettempdir() rc_venv, out_venv, err_venv = module.run_command(command, cwd=cwd) rc += rc_venv out += out_venv err += err_venv easy_install = _get_easy_install(module, env, executable) cmd = None changed = False installed = _is_package_installed(module, name, easy_install, executable_arguments) if not installed: if module.check_mode: module.exit_json(changed=True) cmd = '%s %s %s' % (easy_install, ' '.join(executable_arguments), name) rc_easy_inst, out_easy_inst, err_easy_inst = module.run_command(cmd) rc += rc_easy_inst out += out_easy_inst err += err_easy_inst changed = True if rc != 0: module.fail_json(msg=err, cmd=cmd) module.exit_json(changed=changed, binary=easy_install, name=name, virtualenv=env)
def main(): module = AnsibleModule( argument_spec=dict( repo=dict(type='str', required=True), state=dict(type='str', default='present', choices=['absent', 'present']), mode=dict(type='raw'), update_cache=dict(type='bool', default=True, aliases=['update-cache']), update_cache_retries=dict(type='int', default=5), update_cache_retry_max_delay=dict(type='int', default=12), filename=dict(type='str'), # This should not be needed, but exists as a failsafe install_python_apt=dict(type='bool', default=True), validate_certs=dict(type='bool', default=True), codename=dict(type='str'), ), supports_check_mode=True, ) params = module.params repo = module.params['repo'] state = module.params['state'] update_cache = module.params['update_cache'] # Note: mode is referenced in SourcesList class via the passed in module (self here) sourceslist = None if not HAVE_PYTHON_APT: if params['install_python_apt']: install_python_apt(module) else: module.fail_json( msg='%s is not installed, and install_python_apt is False' % PYTHON_APT) if not repo: module.fail_json( msg='Please set argument \'repo\' to a non-empty value') if isinstance(distro, aptsources_distro.Distribution): sourceslist = UbuntuSourcesList( module, add_ppa_signing_keys_callback=get_add_ppa_signing_key_callback( module)) else: module.fail_json( msg='Module apt_repository is not supported on target.') sourceslist_before = copy.deepcopy(sourceslist) sources_before = sourceslist.dump() try: if state == 'present': sourceslist.add_source(repo) elif state == 'absent': sourceslist.remove_source(repo) except InvalidSource as err: module.fail_json(msg='Invalid repository string: %s' % to_native(err)) sources_after = sourceslist.dump() changed = sources_before != sources_after if changed and module._diff: diff = [] for filename in set(sources_before.keys()).union(sources_after.keys()): diff.append({ 'before': sources_before.get(filename, ''), 'after': sources_after.get(filename, ''), 'before_header': (filename, '/dev/null')[filename not in sources_before], 'after_header': (filename, '/dev/null')[filename not in sources_after] }) else: diff = {} if changed and not module.check_mode: try: sourceslist.save() if update_cache: err = '' update_cache_retries = module.params.get( 'update_cache_retries') update_cache_retry_max_delay = module.params.get( 'update_cache_retry_max_delay') randomize = random.randint(0, 1000) / 1000.0 for retry in range(update_cache_retries): try: cache = apt.Cache() cache.update() break except apt.cache.FetchFailedException as e: err = to_native(e) # Use exponential backoff with a max fail count, plus a little bit of randomness delay = 2**retry + randomize if delay > update_cache_retry_max_delay: delay = update_cache_retry_max_delay + randomize time.sleep(delay) else: revert_sources_list(sources_before, sources_after, sourceslist_before) module.fail_json(msg='Failed to update apt cache: %s' % (err if err else 'unknown reason')) except (OSError, IOError) as err: revert_sources_list(sources_before, sources_after, sourceslist_before) module.fail_json(msg=to_native(err)) module.exit_json(changed=changed, repo=repo, state=state, diff=diff)
def main(): vsan_element_spec = dict(id=dict(required=True, type='int'), name=dict(type='str'), remove=dict(type='bool'), suspend=dict(type='bool'), interface=dict(type='list', elements='str')) argument_spec = dict( vsan=dict(type='list', elements='dict', options=vsan_element_spec)) argument_spec.update(nxos_argument_spec) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True) warnings = list() messages = list() commands_executed = list() result = {'changed': False} obj = GetVsanInfoFromSwitch(module) dictSwVsanObjs = obj.getVsanInfoObjects() commands = [] vsan_list = module.params['vsan'] for eachvsan in vsan_list: vsanid = str(eachvsan['id']) vsanname = eachvsan['name'] vsanremove = eachvsan['remove'] vsansuspend = eachvsan['suspend'] vsaninterface_list = eachvsan['interface'] if int(vsanid) < 1 or int(vsanid) >= 4095: module.fail_json( msg=vsanid + " - This is an invalid vsan. Supported vsan range is 1-4094") if vsanid in dictSwVsanObjs.keys(): sw_vsanid = vsanid sw_vsanname = dictSwVsanObjs[vsanid].vsanname sw_vsanstate = dictSwVsanObjs[vsanid].vsanstate sw_vsaninterfaces = dictSwVsanObjs[vsanid].vsaninterfaces else: sw_vsanid = None sw_vsanname = None sw_vsanstate = None sw_vsaninterfaces = [] if vsanremove: # Negetive case: if vsanid == '4079' or vsanid == '4094': messages.append( str(vsanid) + " is a reserved vsan, hence cannot be removed") continue if vsanid == sw_vsanid: commands.append("no vsan " + str(vsanid)) messages.append("deleting the vsan " + str(vsanid)) else: messages.append( "There is no vsan " + str(vsanid) + " present in the switch. Hence there is nothing to delete") continue else: # Negetive case: if vsanid == '4079' or vsanid == '4094': messages.append( str(vsanid) + " is a reserved vsan, and always present on the switch") else: if vsanid == sw_vsanid: messages.append( "There is already a vsan " + str(vsanid) + " present in the switch. Hence there is nothing to configure" ) else: commands.append("vsan " + str(vsanid)) messages.append("creating vsan " + str(vsanid)) if vsanname is not None: # Negetive case: if vsanid == '4079' or vsanid == '4094': messages.append( str(vsanid) + " is a reserved vsan, and cannot be renamed") else: if vsanname == sw_vsanname: messages.append( "There is already a vsan " + str(vsanid) + " present in the switch, which has the name " + vsanname + " Hence there is nothing to configure") else: commands.append("vsan " + str(vsanid) + " name " + vsanname) messages.append("setting vsan name to " + vsanname + " for vsan " + str(vsanid)) if vsansuspend: # Negetive case: if vsanid == '4079' or vsanid == '4094': messages.append( str(vsanid) + " is a reserved vsan, and cannot be suspended") else: if sw_vsanstate == 'suspended': messages.append( "There is already a vsan " + str(vsanid) + " present in the switch, which is in suspended state ") else: commands.append("vsan " + str(vsanid) + " suspend") messages.append("suspending the vsan " + str(vsanid)) else: if sw_vsanstate == 'active': messages.append( "There is already a vsan " + str(vsanid) + " present in the switch, which is in active state ") else: commands.append("no vsan " + str(vsanid) + " suspend") messages.append("no suspending the vsan " + str(vsanid)) if vsaninterface_list is not None: for each_interface_name in vsaninterface_list: # For fcip,port-channel,vfc-port-channel need to remove the extra space to compare temp = re.sub(' +', '', each_interface_name) if temp in sw_vsaninterfaces: messages.append(each_interface_name + " is already present in the vsan " + str(vsanid) + " interface list") else: commands.append("vsan " + str(vsanid) + " interface " + each_interface_name) messages.append("adding interface " + each_interface_name + " to vsan " + str(vsanid)) if len(commands) != 0: commands = ["terminal dont-ask"] + ["vsan database"] + commands + [ "no terminal dont-ask" ] cmds = flatten_list(commands) commands_executed = cmds if commands_executed: if module.check_mode: module.exit_json(changed=False, commands=commands_executed, msg="Check Mode: No cmds issued to the hosts") else: result['changed'] = True load_config(module, commands_executed) result['messages'] = messages result['commands'] = commands_executed result['warnings'] = warnings module.exit_json(**result)