def _main(): """ Entrypoint. """ module = AnsibleModule( argument_spec={ 'name': {'required': True, 'type': 'str'}, 'version': {'default': None, 'required': False, 'type': 'str'}, 'state': { 'default': 'present', 'required': False, 'choices': ['present', 'absent', 'latest'] }, 'channels': {'default': None, 'required': False}, 'executable': {'default': None, 'required': False}, 'extra_args': {'default': None, 'required': False, 'type': 'str'} }, supports_check_mode=True) conda = find_conda(module.params['executable']) name = module.params['name'] state = module.params['state'] version = module.params['version'] if state == 'latest' and version is not None: module.fail_json(msg='`version` must not be set if `state == "latest"` (`latest` upgrades to newest version)') def command_runner(command): return _run_conda_command(module, command) run_package_operation( conda, name, version, state, module.check_mode, command_runner, module.fail_json, module.exit_json)
def main(): argument_spec = rax_argument_spec() argument_spec.update( dict( name=dict(required=True), public_key=dict(), state=dict(default='present', choices=['absent', 'present']), ) ) module = AnsibleModule( argument_spec=argument_spec, required_together=rax_required_together(), ) if not HAS_PYRAX: module.fail_json(msg='pyrax is required for this module') name = module.params.get('name') public_key = module.params.get('public_key') state = module.params.get('state') setup_rax_module(module, pyrax) rax_keypair(module, name, public_key, state)
def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict( load_balancer_arn=dict(type='str'), target_group_arns=dict(type='list'), names=dict(type='list') ) ) module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=['load_balancer_arn', 'target_group_arns', 'names'], supports_check_mode=True ) if not HAS_BOTO3: module.fail_json(msg='boto3 required for this module') region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True) if region: connection = boto3_conn(module, conn_type='client', resource='elbv2', region=region, endpoint=ec2_url, **aws_connect_params) else: module.fail_json(msg="region must be specified") list_target_groups(connection, module)
def main(): argument_specs = dict( state=dict(default='present', choices=['absent', 'present']), admin_auth_configuration=dict(type='dict',), dns_configuration=dict(type='dict',), dns_virtualservice_refs=dict(type='list',), docker_mode=dict(type='bool',), email_configuration=dict(type='dict',), global_tenant_config=dict(type='dict',), linux_configuration=dict(type='dict',), mgmt_ip_access_control=dict(type='dict',), ntp_configuration=dict(type='dict',), portal_configuration=dict(type='dict',), proxy_configuration=dict(type='dict',), snmp_configuration=dict(type='dict',), ssh_ciphers=dict(type='list',), ssh_hmacs=dict(type='list',), url=dict(type='str',), uuid=dict(type='str',), ) argument_specs.update(avi_common_argument_spec()) module = AnsibleModule( argument_spec=argument_specs, supports_check_mode=True) if not HAS_AVI: return module.fail_json(msg=( 'Avi python API SDK (avisdk>=17.1) is not installed. ' 'For more details visit https://github.com/avinetworks/sdk.')) return avi_ansible_api(module, 'systemconfiguration', set([]))
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(): """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 = ec2_argument_spec() argument_spec.update( dict( name=dict(required=True, type='str'), adjustment_type=dict(type='str', choices=['ChangeInCapacity', 'ExactCapacity', 'PercentChangeInCapacity']), asg_name=dict(required=True, type='str'), scaling_adjustment=dict(type='int'), min_adjustment_step=dict(type='int'), cooldown=dict(type='int'), state=dict(default='present', choices=['present', 'absent']), ) ) module = AnsibleModule(argument_spec=argument_spec) if not HAS_BOTO: module.fail_json(msg='boto required for this module') region, ec2_url, aws_connect_params = get_aws_connection_info(module) state = module.params.get('state') try: connection = connect_to_aws(boto.ec2.autoscale, region, **aws_connect_params) except (boto.exception.NoAuthHandlerFound, AnsibleAWSError) as e: module.fail_json(msg=str(e)) if state == 'present': create_scaling_policy(connection, module) elif state == 'absent': delete_scaling_policy(connection, module)
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 = rax_argument_spec() argument_spec.update( dict( state=dict(default='present', choices=['present', 'absent']), label=dict(required=True), notification_type=dict(required=True, choices=['webhook', 'email', 'pagerduty']), details=dict(required=True, type='dict') ) ) module = AnsibleModule( argument_spec=argument_spec, required_together=rax_required_together() ) if not HAS_PYRAX: module.fail_json(msg='pyrax is required for this module') state = module.params.get('state') label = module.params.get('label') notification_type = module.params.get('notification_type') details = module.params.get('details') setup_rax_module(module, pyrax) notification(module, state, label, notification_type, details)
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(): 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(): ''' 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 = 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(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(): 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(): ''' ansible oc module for secrets ''' module = AnsibleModule( argument_spec=dict( query=dict(default='offer', choices=['offer', 'operation']), publisher=dict(default='redhat', type='str'), debug=dict(default=False, type='bool'), tenant_id=dict(default=os.environ.get('AZURE_TENANT_ID'), type='str'), client_id=dict(default=os.environ.get('AZURE_CLIENT_ID'), type='str'), client_secret=dict(default=os.environ.get('AZURE_CLIENT_SECRET'), type='str'), offer=dict(default=None, type='str'), operation=dict(default=None, type='str'), status=dict(default=None, type='str'), ), ) # Verify we recieved either a valid key or edits with valid keys when receiving a src file. # A valid key being not None or not ''. if (module.params['tenant_id'] is None or module.params['client_id'] is None or module.params['client_secret'] is None): return module.fail_json(**{'failed': True, 'msg': 'Please specify tenant_id, client_id, and client_secret'}) rval = AzurePublisher.run_ansible(module.params) if int(rval['status_code']) == 404: rval['msg'] = 'Offer does not exist.' elif int(rval['status_code']) >= 300: rval['msg'] = 'Error.' return module.fail_json(**rval) return module.exit_json(**rval)
def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict( name=dict(required=True, type='str'), managed_policy=dict(default=[], type='list'), state=dict(choices=['present', 'absent'], required=True), purge_policy=dict(default=False, type='bool') ) ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True ) if not HAS_BOTO3: module.fail_json(msg='boto3 required for this module') region, ec2_url, aws_connect_params = get_aws_connection_info(module, boto3=True) connection = boto3_conn(module, conn_type='client', resource='iam', region=region, endpoint=ec2_url, **aws_connect_params) state = module.params.get("state") if state == 'present': create_or_update_user(connection, module) else: destroy_user(connection, module)
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(): """ 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(): argument_specs = dict( state=dict(default='present', choices=['absent', 'present']), avi_api_update_method=dict(default='put', choices=['put', 'patch']), avi_api_patch_op=dict(choices=['add', 'replace', 'delete']), bgp_profile=dict(type='dict',), cloud_ref=dict(type='str',), debugvrfcontext=dict(type='dict',), description=dict(type='str',), gateway_mon=dict(type='list',), internal_gateway_monitor=dict(type='dict',), name=dict(type='str', required=True), static_routes=dict(type='list',), system_default=dict(type='bool',), tenant_ref=dict(type='str',), url=dict(type='str',), uuid=dict(type='str',), ) argument_specs.update(avi_common_argument_spec()) module = AnsibleModule( argument_spec=argument_specs, supports_check_mode=True) if not HAS_AVI: return module.fail_json(msg=( 'Avi python API SDK (avisdk>=17.1) is not installed. ' 'For more details visit https://github.com/avinetworks/sdk.')) return avi_ansible_api(module, 'vrfcontext', set([]))
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(): 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(): 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'), 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(): 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(): """ 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(): 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_specs = dict( state=dict(default='present', choices=['absent', 'present']), cloud_config_cksum=dict(type='str',), cloud_ref=dict(type='str',), created_by=dict(type='str',), deployment_policy_ref=dict(type='str',), description=dict(type='str',), fail_action=dict(type='dict',), members=dict(type='list',), min_servers=dict(type='int',), name=dict(type='str', required=True), priority_labels_ref=dict(type='str',), tenant_ref=dict(type='str',), url=dict(type='str',), uuid=dict(type='str',), ) argument_specs.update(avi_common_argument_spec()) module = AnsibleModule( argument_spec=argument_specs, supports_check_mode=True) if not HAS_AVI: return module.fail_json(msg=( 'Avi python API SDK (avisdk>=17.1) is not installed. ' 'For more details visit https://github.com/avinetworks/sdk.')) return avi_ansible_api(module, 'poolgroup', set([]))
def main(): argument_specs = dict( state=dict(default='present', choices=['absent', 'present']), avi_api_update_method=dict(default='put', choices=['put', 'patch']), avi_api_patch_op=dict(choices=['add', 'replace', 'delete']), backup_config_ref=dict(type='str',), enabled=dict(type='bool',), end_date_time=dict(type='str',), frequency=dict(type='int',), frequency_unit=dict(type='str',), name=dict(type='str', required=True), run_mode=dict(type='str',), run_script_ref=dict(type='str',), scheduler_action=dict(type='str',), start_date_time=dict(type='str',), tenant_ref=dict(type='str',), url=dict(type='str',), uuid=dict(type='str',), ) argument_specs.update(avi_common_argument_spec()) module = AnsibleModule( argument_spec=argument_specs, supports_check_mode=True) if not HAS_AVI: return module.fail_json(msg=( 'Avi python API SDK (avisdk>=17.1) is not installed. ' 'For more details visit https://github.com/avinetworks/sdk.')) return avi_ansible_api(module, 'scheduler', set([]))
def main(): ''' This function is the main function of this module ''' # argument_spec = postgres_common_argument_spec() argument_spec = dict() argument_spec.update(address=dict(type='str', default='samehost', aliases=['source', 'src']), backup_file=dict(type='str'), contype=dict(type='str', default=None, choices=PG_HBA_TYPES), create=dict(type='bool', default=False), databases=dict(type='str', default='all'), dest=dict(type='path', required=True), method=dict(type='str', default='md5', choices=PG_HBA_METHODS), netmask=dict(type='str'), options=dict(type='str'), order=dict(type='str', default="sdu", choices=PG_HBA_ORDERS), state=dict(type='str', default="present", choices=["absent", "present"]), users=dict(type='str', default='all')) module = AnsibleModule(argument_spec=argument_spec, add_file_common_args=True, supports_check_mode=True) if not HAS_IPADDRESS: module.fail_json(msg=missing_required_lib('psycopg2'), exception=IPADDRESS_IMP_ERR) contype = module.params["contype"] create = bool(module.params["create"] or module.check_mode) if module.check_mode: backup = False else: backup = module.params['backup'] backup_file = module.params['backup_file'] databases = module.params["databases"] dest = module.params["dest"] method = module.params["method"] netmask = module.params["netmask"] options = module.params["options"] order = module.params["order"] source = module.params["address"] state = module.params["state"] users = module.params["users"] ret = {'msgs': []} try: pg_hba = PgHba(dest, order, backup=backup, create=create) except PgHbaError as error: module.fail_json(msg='Error reading file:\n{0}'.format(error)) if contype: try: for database in databases.split(','): for user in users.split(','): rule = PgHbaRule(contype, database, user, source, netmask, method, options) if state == "present": ret['msgs'].append('Adding') pg_hba.add_rule(rule) else: ret['msgs'].append('Removing') pg_hba.remove_rule(rule) except PgHbaError as error: module.fail_json(msg='Error modifying rules:\n{0}'.format(error)) file_args = module.load_file_common_arguments(module.params) ret['changed'] = changed = pg_hba.changed() if changed: ret['msgs'].append('Changed') ret['diff'] = pg_hba.diff if not module.check_mode: ret['msgs'].append('Writing') try: if pg_hba.write(backup_file): module.set_fs_attributes_if_different(file_args, True, pg_hba.diff, expand=False) except PgHbaError as error: module.fail_json( msg='Error writing file:\n{0}'.format(error)) if pg_hba.last_backup: ret['backup_file'] = pg_hba.last_backup ret['pg_hba'] = [rule for rule in pg_hba.get_rules()] module.exit_json(**ret)
def main(): module = AnsibleModule(argument_spec=get_argspec(), supports_check_mode=True) result = run_command(module) module.exit_json(**result)
def main(): argument_spec = mso_argument_spec() argument_spec.update( source_schema=dict(type='str'), destination_schema=dict(type='str'), destination_tenant=dict(type='str'), source_template_name=dict(type='str'), destination_template_name=dict(type='str'), destination_template_display_name=dict(type='str'), state=dict(type='str', default='clone', choices=['clone']), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, required_if=[ ['state', 'clone', ['destination_schema', 'destination_tenant']], ], ) source_schema = module.params.get('source_schema') destination_schema = module.params.get('destination_schema') destination_tenant = module.params.get('destination_tenant') source_template_name = module.params.get('source_template_name') destination_template_name = module.params.get('destination_template_name') destination_template_display_name = module.params.get( 'destination_template_display_name') state = module.params.get('state') mso = MSOModule(module) destination_schema_id = None # Get source schema id and destination schema id schema_summary = mso.query_objs('schemas/list-identity', key='schemas') for schema in schema_summary: if schema.get('displayName') == source_schema: source_schema_id = schema.get('id') if schema.get('displayName') == destination_schema: destination_schema_id = schema.get('id') destination_schema = None break if destination_schema_id is None: mso.fail_json(msg="Schema with the name '{0}' does not exist.".format( destination_schema)) # Get destination tenant id destination_tenant_id = mso.lookup_tenant(destination_tenant) path = 'schemas/cloneTemplates' if state == 'clone': if destination_template_display_name is None: destination_template_display_name = destination_template_name payload = dict( destTenantId=destination_tenant_id, destSchemaId=destination_schema_id, destSchemaName=destination_schema, templatesToBeCloned=[ dict( schemaId=source_schema_id, templateName=source_template_name, destTemplateName=destination_template_name, destTempDisplayName=destination_template_display_name, ) ], ) mso.sanitize(payload, collate=True) mso.previous = {} if not mso.existing: if module.check_mode: mso.existing = {} else: mso.existing = mso.request(path, method='POST', data=mso.sent) mso.exit_json()
def main(): # Module arguments argument_spec = url_argument_spec() argument_spec.update( group=dict(default='jenkins'), jenkins_home=dict(default='/var/lib/jenkins'), mode=dict(default='0644', type='raw'), name=dict(required=True), owner=dict(default='jenkins'), params=dict(type='dict'), state=dict( choices=[ 'present', 'absent', 'pinned', 'unpinned', 'enabled', 'disabled', 'latest'], default='present'), timeout=dict(default=30, type="int"), updates_expiration=dict(default=86400, type="int"), updates_url=dict(default='https://updates.jenkins-ci.org'), url=dict(default='http://localhost:8080'), url_password=dict(no_log=True), version=dict(), with_dependencies=dict(default=True, type='bool'), ) # Module settings module = AnsibleModule( argument_spec=argument_spec, add_file_common_args=True, supports_check_mode=True, ) # Params was removed # https://meetbot.fedoraproject.org/ansible-meeting/2017-09-28/ansible_dev_meeting.2017-09-28-15.00.log.html if module.params['params']: module.fail_json(msg="The params option to jenkins_plugin was removed in Ansible 2.5" "since it circumvents Ansible's option handling") # Force basic authentication module.params['force_basic_auth'] = True # Convert timeout to float try: module.params['timeout'] = float(module.params['timeout']) except ValueError as e: module.fail_json( msg='Cannot convert %s to float.' % module.params['timeout'], details=to_native(e)) # Set version to latest if state is latest if module.params['state'] == 'latest': module.params['state'] = 'present' module.params['version'] = 'latest' # Create some shortcuts name = module.params['name'] state = module.params['state'] # Initial change state of the task changed = False # Instantiate the JenkinsPlugin object jp = JenkinsPlugin(module) # Perform action depending on the requested state if state == 'present': changed = jp.install() elif state == 'absent': changed = jp.uninstall() elif state == 'pinned': changed = jp.pin() elif state == 'unpinned': changed = jp.unpin() elif state == 'enabled': changed = jp.enable() elif state == 'disabled': changed = jp.disable() # Print status of the change module.exit_json(changed=changed, plugin=name, state=state)
def init_module(self): """init module""" self.module = AnsibleModule( argument_spec=self.spec, supports_check_mode=True)
class VxlanGlobal(object): """ Manages global attributes of VXLAN and bridge domain. """ def __init__(self, argument_spec): self.spec = argument_spec self.module = None self.init_module() # module input info self.tunnel_mode_vxlan = self.module.params['tunnel_mode_vxlan'] self.nvo3_prevent_loops = self.module.params['nvo3_prevent_loops'] self.nvo3_acl_extend = self.module.params['nvo3_acl_extend'] self.nvo3_gw_enhanced = self.module.params['nvo3_gw_enhanced'] self.nvo3_service_extend = self.module.params['nvo3_service_extend'] self.nvo3_eth_trunk_hash = self.module.params['nvo3_eth_trunk_hash'] self.nvo3_ecmp_hash = self.module.params['nvo3_ecmp_hash'] self.bridge_domain_id = self.module.params['bridge_domain_id'] self.state = self.module.params['state'] # state self.config = "" # current config self.bd_info = list() self.changed = False self.updates_cmd = list() self.commands = list() self.results = dict() self.proposed = dict() self.existing = dict() self.end_state = dict() def init_module(self): """init module""" self.module = AnsibleModule( argument_spec=self.spec, supports_check_mode=True) def cli_load_config(self, commands): """load config by cli""" if not self.module.check_mode: load_config(self.module, commands) def get_config(self, flags=None): """Retrieves the current config from the device or cache """ flags = [] if flags is None else flags cmd = 'display current-configuration ' cmd += ' '.join(flags) cmd = cmd.strip() rc, out, err = exec_command(self.module, cmd) if rc != 0: self.module.fail_json(msg=err) cfg = str(out).strip() return cfg def get_current_config(self): """get current configuration""" flags = list() exp = " include-default | include vxlan|assign | exclude undo" flags.append(exp) return self.get_config(flags) def cli_add_command(self, command, undo=False): """add command to self.update_cmd and self.commands""" if undo and command.lower() not in ["quit", "return"]: cmd = "undo " + command else: cmd = command self.commands.append(cmd) # set to device if command.lower() not in ["quit", "return"]: self.updates_cmd.append(cmd) # show updates result def get_bd_list(self): """get bridge domain list""" flags = list() bd_info = list() exp = " include-default | include bridge-domain | exclude undo" flags.append(exp) bd_str = self.get_config(flags) if not bd_str: return bd_info bd_num = re.findall(r'bridge-domain\s*([0-9]+)', bd_str) bd_info.extend(bd_num) return bd_info def config_bridge_domain(self): """manage bridge domain""" if not self.bridge_domain_id: return cmd = "bridge-domain %s" % self.bridge_domain_id exist = self.bridge_domain_id in self.bd_info if self.state == "present": if not exist: self.cli_add_command(cmd) self.cli_add_command("quit") else: if exist: self.cli_add_command(cmd, undo=True) def config_tunnel_mode(self): """config tunnel mode vxlan""" # ip tunnel mode vxlan if self.tunnel_mode_vxlan: cmd = "ip tunnel mode vxlan" exist = is_config_exist(self.config, cmd) if self.tunnel_mode_vxlan == "enable": if not exist: self.cli_add_command(cmd) else: if exist: self.cli_add_command(cmd, undo=True) def config_assign_forward(self): """config assign forward command""" # [undo] assign forward nvo3-gateway enhanced {l2|l3) if self.nvo3_gw_enhanced: cmd = "assign forward nvo3-gateway enhanced %s" % self.nvo3_gw_enhanced exist = is_config_exist(self.config, cmd) if self.state == "present": if not exist: self.cli_add_command(cmd) else: if exist: self.cli_add_command(cmd, undo=True) # [undo] assign forward nvo3 f-linecard compatibility enable if self.nvo3_prevent_loops: cmd = "assign forward nvo3 f-linecard compatibility enable" exist = is_config_exist(self.config, cmd) if self.nvo3_prevent_loops == "enable": if not exist: self.cli_add_command(cmd) else: if exist: self.cli_add_command(cmd, undo=True) # [undo] assign forward nvo3 acl extend enable if self.nvo3_acl_extend: cmd = "assign forward nvo3 acl extend enable" exist = is_config_exist(self.config, cmd) if self.nvo3_acl_extend == "enable": if not exist: self.cli_add_command(cmd) else: if exist: self.cli_add_command(cmd, undo=True) # [undo] assign forward nvo3 service extend enable if self.nvo3_service_extend: cmd = "assign forward nvo3 service extend enable" exist = is_config_exist(self.config, cmd) if self.nvo3_service_extend == "enable": if not exist: self.cli_add_command(cmd) else: if exist: self.cli_add_command(cmd, undo=True) # assign forward nvo3 eth-trunk hash {enable|disable} if self.nvo3_eth_trunk_hash: cmd = "assign forward nvo3 eth-trunk hash enable" exist = is_config_exist(self.config, cmd) if self.nvo3_eth_trunk_hash == "enable": if not exist: self.cli_add_command(cmd) else: if exist: self.cli_add_command(cmd, undo=True) # [undo] assign forward nvo3 ecmp hash enable if self.nvo3_ecmp_hash: cmd = "assign forward nvo3 ecmp hash enable" exist = is_config_exist(self.config, cmd) if self.nvo3_ecmp_hash == "enable": if not exist: self.cli_add_command(cmd) else: if exist: self.cli_add_command(cmd, undo=True) def check_params(self): """Check all input params""" # bridge domain id check if self.bridge_domain_id: if not self.bridge_domain_id.isdigit(): self.module.fail_json( msg="Error: bridge domain id is not digit.") if int(self.bridge_domain_id) < 1 or int(self.bridge_domain_id) > 16777215: self.module.fail_json( msg="Error: bridge domain id is not in the range from 1 to 16777215.") def get_proposed(self): """get proposed info""" if self.tunnel_mode_vxlan: self.proposed["tunnel_mode_vxlan"] = self.tunnel_mode_vxlan if self.nvo3_prevent_loops: self.proposed["nvo3_prevent_loops"] = self.nvo3_prevent_loops if self.nvo3_acl_extend: self.proposed["nvo3_acl_extend"] = self.nvo3_acl_extend if self.nvo3_gw_enhanced: self.proposed["nvo3_gw_enhanced"] = self.nvo3_gw_enhanced if self.nvo3_service_extend: self.proposed["nvo3_service_extend"] = self.nvo3_service_extend if self.nvo3_eth_trunk_hash: self.proposed["nvo3_eth_trunk_hash"] = self.nvo3_eth_trunk_hash if self.nvo3_ecmp_hash: self.proposed["nvo3_ecmp_hash"] = self.nvo3_ecmp_hash if self.bridge_domain_id: self.proposed["bridge_domain_id"] = self.bridge_domain_id self.proposed["state"] = self.state def get_existing(self): """get existing info""" self.existing["bridge_domain"] = self.bd_info cmd = "ip tunnel mode vxlan" exist = is_config_exist(self.config, cmd) if exist: self.existing["tunnel_mode_vxlan"] = "enable" else: self.existing["tunnel_mode_vxlan"] = "disable" cmd = "assign forward nvo3 f-linecard compatibility enable" exist = is_config_exist(self.config, cmd) if exist: self.existing["nvo3_prevent_loops"] = "enable" else: self.existing["nvo3_prevent_loops"] = "disable" cmd = "assign forward nvo3 acl extend enable" exist = is_config_exist(self.config, cmd) if exist: self.existing["nvo3_acl_extend"] = "enable" else: self.existing["nvo3_acl_extend"] = "disable" self.existing["nvo3_gw_enhanced"] = get_nvo3_gw_enhanced( self.config) cmd = "assign forward nvo3 service extend enable" exist = is_config_exist(self.config, cmd) if exist: self.existing["nvo3_service_extend"] = "enable" else: self.existing["nvo3_service_extend"] = "disable" cmd = "assign forward nvo3 eth-trunk hash enable" exist = is_config_exist(self.config, cmd) if exist: self.existing["nvo3_eth_trunk_hash"] = "enable" else: self.existing["nvo3_eth_trunk_hash"] = "disable" cmd = "assign forward nvo3 ecmp hash enable" exist = is_config_exist(self.config, cmd) if exist: self.existing["nvo3_ecmp_hash"] = "enable" else: self.existing["nvo3_ecmp_hash"] = "disable" def get_end_state(self): """get end state info""" config = self.get_current_config() self.end_state["bridge_domain"] = self.get_bd_list() cmd = "ip tunnel mode vxlan" exist = is_config_exist(config, cmd) if exist: self.end_state["tunnel_mode_vxlan"] = "enable" else: self.end_state["tunnel_mode_vxlan"] = "disable" cmd = "assign forward nvo3 f-linecard compatibility enable" exist = is_config_exist(config, cmd) if exist: self.end_state["nvo3_prevent_loops"] = "enable" else: self.end_state["nvo3_prevent_loops"] = "disable" cmd = "assign forward nvo3 acl extend enable" exist = is_config_exist(config, cmd) if exist: self.end_state["nvo3_acl_extend"] = "enable" else: self.end_state["nvo3_acl_extend"] = "disable" self.end_state["nvo3_gw_enhanced"] = get_nvo3_gw_enhanced(config) cmd = "assign forward nvo3 service extend enable" exist = is_config_exist(config, cmd) if exist: self.end_state["nvo3_service_extend"] = "enable" else: self.end_state["nvo3_service_extend"] = "disable" cmd = "assign forward nvo3 eth-trunk hash enable" exist = is_config_exist(config, cmd) if exist: self.end_state["nvo3_eth_trunk_hash"] = "enable" else: self.end_state["nvo3_eth_trunk_hash"] = "disable" cmd = "assign forward nvo3 ecmp hash enable" exist = is_config_exist(config, cmd) if exist: self.end_state["nvo3_ecmp_hash"] = "enable" else: self.end_state["nvo3_ecmp_hash"] = "disable" if self.existing == self.end_state: self.changed = True def work(self): """worker""" self.check_params() self.config = self.get_current_config() self.bd_info = self.get_bd_list() self.get_existing() self.get_proposed() # deal present or absent self.config_bridge_domain() self.config_tunnel_mode() self.config_assign_forward() if self.commands: self.cli_load_config(self.commands) self.changed = True self.get_end_state() self.results['changed'] = self.changed self.results['proposed'] = self.proposed self.results['existing'] = self.existing self.results['end_state'] = self.end_state if self.changed: self.results['updates'] = self.updates_cmd else: self.results['updates'] = list() self.module.exit_json(**self.results)
def main(): argument_spec = aci_argument_spec() argument_spec.update( description=dict(type='str', aliases=['descr']), pool=dict(type='str', aliases=['name', 'pool_name' ]), # Not required for querying all objects pool_allocation_mode=dict(type='str', aliases=['allocation_mode', 'mode'], choices=['dynamic', 'static']), pool_type=dict(type='str', aliases=['type'], choices=['vlan', 'vxlan', 'vsan'], required=True), state=dict(type='str', default='present', choices=['absent', 'present', 'query']), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, required_if=[ ['state', 'absent', ['pool']], ['state', 'present', ['pool']], ], ) description = module.params['description'] pool = module.params['pool'] pool_type = module.params['pool_type'] pool_allocation_mode = module.params['pool_allocation_mode'] state = module.params['state'] aci_class = ACI_MAPPING[pool_type]["aci_class"] aci_mo = ACI_MAPPING[pool_type]["aci_mo"] pool_name = pool # ACI Pool URL requires the pool_allocation mode for vlan and vsan pools (ex: uni/infra/vlanns-[poolname]-static) if pool_type != 'vxlan' and pool is not None: if pool_allocation_mode is not None: pool_name = '[{0}]-{1}'.format(pool, pool_allocation_mode) else: module.fail_json( msg= "ACI requires parameter 'pool_allocation_mode' for 'pool_type' of 'vlan' and 'vsan' when parameter 'pool' is provided" ) # Vxlan pools do not support pool allocation modes if pool_type == 'vxlan' and pool_allocation_mode is not None: module.fail_json( msg= "vxlan pools do not support setting the 'pool_allocation_mode'; please remove this parameter from the task" ) aci = ACIModule(module) aci.construct_url(root_class=dict( aci_class=aci_class, aci_rn='{0}{1}'.format(aci_mo, pool_name), module_object=pool, target_filter={'name': pool}, ), ) aci.get_existing() if state == 'present': # Filter out module parameters with null values aci.payload(aci_class=aci_class, class_config=dict( allocMode=pool_allocation_mode, descr=description, name=pool, )) # Generate config diff which will be used as POST request body aci.get_diff(aci_class=aci_class) # Submit changes if module not in check_mode and the proposed is different than existing aci.post_config() elif state == 'absent': aci.delete_config() aci.exit_json()
def main(): helper = get_connection( template=True, template_stack=True, with_state=True, with_classic_provider_spec=True, argument_spec=setup_args(), ) module = AnsibleModule( argument_spec=helper.argument_spec, supports_check_mode=True, required_one_of=helper.required_one_of, ) # Verify libs, setup pandevice object tree. parent = helper.get_pandevice_parent(module) vr = VirtualRouter(module.params["vr_name"]) parent.add(vr) try: vr.refresh() except PanDeviceError as e: module.fail_json(msg="Failed refresh: {0}".format(e)) bgp = vr.find("", Bgp) if bgp is None: module.fail_json(msg='BGP is not configured for "{0}".'.format(vr.name)) group = bgp.find(module.params["peer_group"], BgpPeerGroup) if group is None: module.fail_json( msg="BGP peer group does not exist: {0}.".format( module.params["peer_group"] ) ) listing = group.findall(BgpPeer) spec = { "name": module.params["name"], "enable": module.params["enable"], "peer_as": module.params["peer_as"], "enable_mp_bgp": module.params["enable_mp_bgp"], "address_family_identifier": module.params["address_family_identifier"], "subsequent_address_unicast": module.params["subsequent_address_unicast"], "subsequent_address_multicast": module.params["subsequent_address_multicast"], "local_interface": module.params["local_interface"], "local_interface_ip": module.params["local_interface_ip"], "peer_address_ip": module.params["peer_address_ip"], "connection_authentication": module.params["connection_authentication"], "connection_keep_alive_interval": module.params[ "connection_keep_alive_interval" ], "connection_min_route_adv_interval": module.params[ "connection_min_route_adv_interval" ], "connection_multihop": module.params["connection_multihop"], "connection_open_delay_time": module.params["connection_open_delay_time"], "connection_hold_time": module.params["connection_hold_time"], "connection_idle_hold_time": module.params["connection_idle_hold_time"], "connection_incoming_allow": module.params["connection_incoming_allow"], "connection_outgoing_allow": module.params["connection_outgoing_allow"], "connection_incoming_remote_port": module.params[ "connection_incoming_remote_port" ], "connection_outgoing_local_port": module.params[ "connection_outgoing_local_port" ], "enable_sender_side_loop_detection": module.params[ "enable_sender_side_loop_detection" ], "reflector_client": module.params["reflector_client"], "peering_type": module.params["peering_type"], "max_prefixes": module.params["max_prefixes"], "bfd_profile": module.params["bfd_profile"], } obj = BgpPeer(**spec) group.add(obj) changed, diff = helper.apply_state(obj, listing, module) if changed and module.params["commit"]: helper.commit(module) module.exit_json(changed=changed, diff=diff, msg="done")
def main(): argument_spec = rax_argument_spec() argument_spec.update( dict(comment=dict(), data=dict(required=True), domain=dict(), loadbalancer=dict(), name=dict(required=True), overwrite=dict(type='bool', default=True), priority=dict(type='int'), server=dict(), state=dict(default='present', choices=['present', 'absent']), ttl=dict(type='int', default=3600), type=dict(required=True, choices=[ 'A', 'AAAA', 'CNAME', 'MX', 'NS', 'SRV', 'TXT', 'PTR' ]))) module = AnsibleModule( argument_spec=argument_spec, required_together=rax_required_together(), mutually_exclusive=[ ['server', 'loadbalancer', 'domain'], ], required_one_of=[ ['server', 'loadbalancer', 'domain'], ], ) if not HAS_PYRAX: module.fail_json(msg='pyrax is required for this module') comment = module.params.get('comment') data = module.params.get('data') domain = module.params.get('domain') loadbalancer = module.params.get('loadbalancer') name = module.params.get('name') overwrite = module.params.get('overwrite') priority = module.params.get('priority') server = module.params.get('server') state = module.params.get('state') ttl = module.params.get('ttl') record_type = module.params.get('type') setup_rax_module(module, pyrax, False) if record_type.upper() == 'PTR': if not server and not loadbalancer: module.fail_json(msg='one of the following is required: ' 'server,loadbalancer') rax_dns_record_ptr(module, data=data, comment=comment, loadbalancer=loadbalancer, name=name, server=server, state=state, ttl=ttl) else: rax_dns_record(module, comment=comment, data=data, domain=domain, name=name, overwrite=overwrite, priority=priority, record_type=record_type, state=state, ttl=ttl)
def main(): argument_spec = dict( group=dict(required=True, type="str"), interface=dict(required=True), version=dict(choices=["1", "2"], default="1", required=False), priority=dict(type="str", required=False), preempt=dict( type="str", choices=["disabled", "enabled"], required=False ), vip=dict(type="str", required=False), auth_type=dict(choices=["text", "md5"], required=False), auth_string=dict(type="str", required=False), state=dict( choices=["absent", "present"], required=False, default="present" ), ) argument_spec.update(nxos_argument_spec) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True ) warnings = list() results = dict(changed=False, warnings=warnings) interface = module.params["interface"].lower() group = module.params["group"] version = module.params["version"] state = module.params["state"] priority = module.params["priority"] preempt = module.params["preempt"] vip = module.params["vip"] auth_type = module.params["auth_type"] auth_full_string = module.params["auth_string"] auth_enc = "0" auth_string = None if auth_full_string: kstr = auth_full_string.split() if len(kstr) == 2: auth_enc = kstr[0] auth_string = kstr[1] elif len(kstr) == 1: auth_string = kstr[0] else: module.fail_json(msg="Invalid auth_string") if auth_enc != "0" and auth_enc != "7": module.fail_json(msg="Invalid auth_string, only 0 or 7 allowed") device_info = get_capabilities(module) network_api = device_info.get("network_api", "nxapi") intf_type = get_interface_type(interface) if intf_type != "ethernet" and network_api == "cliconf": if is_default(interface, module) == "DNE": module.fail_json( msg="That interface does not exist yet. Create " "it first.", interface=interface, ) if intf_type == "loopback": module.fail_json( msg="Loopback interfaces don't support HSRP.", interface=interface, ) mode = get_interface_mode(interface, intf_type, module) if mode == "layer2": module.fail_json( msg="That interface is a layer2 port.\nMake it " "a layer 3 port first.", interface=interface, ) if auth_type or auth_string: if not (auth_type and auth_string): module.fail_json( msg="When using auth parameters, you need BOTH " "auth_type AND auth_string." ) args = dict( group=group, version=version, priority=priority, preempt=preempt, vip=vip, auth_type=auth_type, auth_string=auth_string, auth_enc=auth_enc, ) proposed = dict((k, v) for k, v in args.items() if v is not None) existing = get_hsrp_group(group, interface, module) # This will enforce better practice with md5 and hsrp version. if proposed.get("auth_type", None) == "md5": if proposed["version"] == "1": module.fail_json( msg="It's recommended to use HSRP v2 " "when auth_type=md5" ) elif not proposed.get("auth_type", None) and existing: if ( proposed["version"] == "1" and existing["auth_type"] == "md5" ) and state == "present": module.fail_json( msg="Existing auth_type is md5. It's recommended " "to use HSRP v2 when using md5" ) commands = [] if state == "present": delta = dict(set(proposed.items()).difference(existing.items())) if delta: command = get_commands_config_hsrp( delta, interface, args, existing ) commands.extend(command) elif state == "absent": if existing: command = get_commands_remove_hsrp(group, interface) commands.extend(command) if commands: if module.check_mode: module.exit_json(**results) else: load_config(module, commands) # validate IP if network_api == "cliconf" and state == "present": commands.insert(0, "config t") body = run_commands(module, commands) validate_config(body, vip, module) results["changed"] = True if "configure" in commands: commands.pop(0) results["commands"] = commands module.exit_json(**results)
def main(): """ Module execution :return: """ argument_spec = keycloak_argument_spec() protmapper_spec = dict( consentRequired=dict(type='bool'), consentText=dict(type='str'), id=dict(type='str'), name=dict(type='str'), protocol=dict(type='str', choices=['openid-connect', 'saml']), protocolMapper=dict(type='str'), config=dict(type='dict'), ) meta_args = dict( state=dict(default='present', choices=['present', 'absent']), realm=dict(type='str', default='master'), id=dict(type='str'), client_id=dict(type='str', aliases=['clientId']), name=dict(type='str'), description=dict(type='str'), root_url=dict(type='str', aliases=['rootUrl']), admin_url=dict(type='str', aliases=['adminUrl']), base_url=dict(type='str', aliases=['baseUrl']), surrogate_auth_required=dict(type='bool', aliases=['surrogateAuthRequired']), enabled=dict(type='bool'), client_authenticator_type=dict(type='str', choices=['client-secret', 'client-jwt'], aliases=['clientAuthenticatorType']), secret=dict(type='str', no_log=True), registration_access_token=dict(type='str', aliases=['registrationAccessToken'], no_log=True), default_roles=dict(type='list', elements='str', aliases=['defaultRoles']), redirect_uris=dict(type='list', elements='str', aliases=['redirectUris']), web_origins=dict(type='list', elements='str', aliases=['webOrigins']), not_before=dict(type='int', aliases=['notBefore']), bearer_only=dict(type='bool', aliases=['bearerOnly']), consent_required=dict(type='bool', aliases=['consentRequired']), standard_flow_enabled=dict(type='bool', aliases=['standardFlowEnabled']), implicit_flow_enabled=dict(type='bool', aliases=['implicitFlowEnabled']), direct_access_grants_enabled=dict(type='bool', aliases=['directAccessGrantsEnabled']), service_accounts_enabled=dict(type='bool', aliases=['serviceAccountsEnabled']), authorization_services_enabled=dict(type='bool', aliases=['authorizationServicesEnabled']), public_client=dict(type='bool', aliases=['publicClient']), frontchannel_logout=dict(type='bool', aliases=['frontchannelLogout']), protocol=dict(type='str', choices=['openid-connect', 'saml']), attributes=dict(type='dict'), full_scope_allowed=dict(type='bool', aliases=['fullScopeAllowed']), node_re_registration_timeout=dict(type='int', aliases=['nodeReRegistrationTimeout']), registered_nodes=dict(type='dict', aliases=['registeredNodes']), client_template=dict(type='str', aliases=['clientTemplate']), use_template_config=dict(type='bool', aliases=['useTemplateConfig']), use_template_scope=dict(type='bool', aliases=['useTemplateScope']), use_template_mappers=dict(type='bool', aliases=['useTemplateMappers']), protocol_mappers=dict(type='list', elements='dict', options=protmapper_spec, aliases=['protocolMappers']), authorization_settings=dict(type='dict', aliases=['authorizationSettings']), ) argument_spec.update(meta_args) module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True, required_one_of=([['client_id', 'id']])) result = dict(changed=False, msg='', diff={}, proposed={}, existing={}, end_state={}) # Obtain access token, initialize API try: connection_header = get_token( base_url=module.params.get('auth_keycloak_url'), validate_certs=module.params.get('validate_certs'), auth_realm=module.params.get('auth_realm'), client_id=module.params.get('auth_client_id'), auth_username=module.params.get('auth_username'), auth_password=module.params.get('auth_password'), client_secret=module.params.get('auth_client_secret'), ) except KeycloakError as e: module.fail_json(msg=str(e)) kc = KeycloakAPI(module, connection_header) realm = module.params.get('realm') cid = module.params.get('id') state = module.params.get('state') # convert module parameters to client representation parameters (if they belong in there) client_params = [x for x in module.params if x not in list(keycloak_argument_spec().keys()) + ['state', 'realm'] and module.params.get(x) is not None] keycloak_argument_spec().keys() # See whether the client already exists in Keycloak if cid is None: before_client = kc.get_client_by_clientid(module.params.get('client_id'), realm=realm) if before_client is not None: cid = before_client['id'] else: before_client = kc.get_client_by_id(cid, realm=realm) if before_client is None: before_client = dict() # Build a proposed changeset from parameters given to this module changeset = dict() for client_param in client_params: new_param_value = module.params.get(client_param) # some lists in the Keycloak API are sorted, some are not. if isinstance(new_param_value, list): if client_param in ['attributes']: try: new_param_value = sorted(new_param_value) except TypeError: pass # Unfortunately, the ansible argument spec checker introduces variables with null values when # they are not specified if client_param == 'protocol_mappers': new_param_value = [dict((k, v) for k, v in x.items() if x[k] is not None) for x in new_param_value] changeset[camel(client_param)] = new_param_value # Whether creating or updating a client, take the before-state and merge the changeset into it updated_client = before_client.copy() updated_client.update(changeset) result['proposed'] = sanitize_cr(changeset) result['existing'] = sanitize_cr(before_client) # If the client does not exist yet, before_client is still empty if before_client == dict(): if state == 'absent': # do nothing and exit if module._diff: result['diff'] = dict(before='', after='') result['msg'] = 'Client does not exist, doing nothing.' module.exit_json(**result) # create new client result['changed'] = True if 'clientId' not in updated_client: module.fail_json(msg='client_id needs to be specified when creating a new client') if module._diff: result['diff'] = dict(before='', after=sanitize_cr(updated_client)) if module.check_mode: module.exit_json(**result) kc.create_client(updated_client, realm=realm) after_client = kc.get_client_by_clientid(updated_client['clientId'], realm=realm) result['end_state'] = sanitize_cr(after_client) result['msg'] = 'Client %s has been created.' % updated_client['clientId'] module.exit_json(**result) else: if state == 'present': # update existing client result['changed'] = True if module.check_mode: # We can only compare the current client with the proposed updates we have if module._diff: result['diff'] = dict(before=sanitize_cr(before_client), after=sanitize_cr(updated_client)) result['changed'] = (before_client != updated_client) module.exit_json(**result) kc.update_client(cid, updated_client, realm=realm) after_client = kc.get_client_by_id(cid, realm=realm) if before_client == after_client: result['changed'] = False if module._diff: result['diff'] = dict(before=sanitize_cr(before_client), after=sanitize_cr(after_client)) result['end_state'] = sanitize_cr(after_client) result['msg'] = 'Client %s has been updated.' % updated_client['clientId'] module.exit_json(**result) else: # Delete existing client result['changed'] = True if module._diff: result['diff']['before'] = sanitize_cr(before_client) result['diff']['after'] = '' if module.check_mode: module.exit_json(**result) kc.delete_client(cid, realm=realm) result['proposed'] = dict() result['end_state'] = dict() result['msg'] = 'Client %s has been deleted.' % before_client['clientId'] module.exit_json(**result) module.exit_json(**result)
def main(): jrpc_urls = [ '/dvmdb/adom/{adom}/device/{device}', '/dvmdb/device/{device}' ] url_schema = [{ 'name': 'adom', 'type': 'string' }, { 'name': 'device', 'type': 'string' }] body_schema = { 'schema_objects': { 'object0': [{ 'name': 'option', 'type': 'dict', 'dict': { 'type': 'string', 'enum': ['object member', 'chksum'] }, 'api_tag': 0 }, { 'type': 'string', 'name': 'url', 'api_tag': 0 }], 'object1': [{ 'name': 'data', 'type': 'dict', 'dict': { 'adm_pass': { 'type': 'array', 'items': { 'type': 'string' } }, 'adm_usr': { 'type': 'string' }, 'app_ver': { 'type': 'string' }, 'av_ver': { 'type': 'string' }, 'beta': { 'type': 'integer' }, 'branch_pt': { 'type': 'integer' }, 'build': { 'type': 'integer' }, 'checksum': { 'type': 'string' }, 'conf_status': { 'type': 'string', 'enum': ['unknown', 'insync', 'outofsync'] }, 'conn_mode': { 'type': 'string', 'enum': ['active', 'passive'] }, 'conn_status': { 'type': 'string', 'enum': ['UNKNOWN', 'up', 'down'] }, 'db_status': { 'type': 'string', 'enum': ['unknown', 'nomod', 'mod'] }, 'desc': { 'type': 'string' }, 'dev_status': { 'type': 'string', 'enum': [ 'none', 'unknown', 'checkedin', 'inprogress', 'installed', 'aborted', 'sched', 'retry', 'canceled', 'pending', 'retrieved', 'changed_conf', 'sync_fail', 'timeout', 'rev_revert', 'auto_updated' ] }, 'fap_cnt': { 'type': 'integer' }, 'faz.full_act': { 'type': 'integer' }, 'faz.perm': { 'type': 'integer' }, 'faz.quota': { 'type': 'integer' }, 'faz.used': { 'type': 'integer' }, 'fex_cnt': { 'type': 'integer' }, 'flags': { 'type': 'array', 'items': { 'type': 'string', 'enum': [ 'has_hdd', 'vdom_enabled', 'discover', 'reload', 'interim_build', 'offline_mode', 'is_model', 'fips_mode', 'linked_to_model', 'ip-conflict', 'faz-autosync' ] } }, 'foslic_cpu': { 'type': 'integer' }, 'foslic_dr_site': { 'type': 'string', 'enum': ['disable', 'enable'] }, 'foslic_inst_time': { 'type': 'integer' }, 'foslic_last_sync': { 'type': 'integer' }, 'foslic_ram': { 'type': 'integer' }, 'foslic_type': { 'type': 'string', 'enum': ['temporary', 'trial', 'regular', 'trial_expired'] }, 'foslic_utm': { 'type': 'array', 'items': { 'type': 'string', 'enum': ['fw', 'av', 'ips', 'app', 'url', 'utm', 'fwb'] } }, 'fsw_cnt': { 'type': 'integer' }, 'ha_group_id': { 'type': 'integer' }, 'ha_group_name': { 'type': 'string' }, 'ha_mode': { 'type': 'string', 'enum': [ 'standalone', 'AP', 'AA', 'ELBC', 'DUAL', 'enabled', 'unknown' ] }, 'hdisk_size': { 'type': 'integer' }, 'hostname': { 'type': 'string' }, 'hw_rev_major': { 'type': 'integer' }, 'hw_rev_minor': { 'type': 'integer' }, 'ip': { 'type': 'string' }, 'ips_ext': { 'type': 'integer' }, 'ips_ver': { 'type': 'string' }, 'last_checked': { 'type': 'integer' }, 'last_resync': { 'type': 'integer' }, 'latitude': { 'type': 'string' }, 'lic_flags': { 'type': 'integer' }, 'lic_region': { 'type': 'string' }, 'location_from': { 'type': 'string' }, 'logdisk_size': { 'type': 'integer' }, 'longitude': { 'type': 'string' }, 'maxvdom': { 'type': 'integer', 'default': 10, 'example': 10 }, 'meta fields': { 'type': 'string' }, 'mgmt_id': { 'type': 'integer' }, 'mgmt_if': { 'type': 'string' }, 'mgmt_mode': { 'type': 'string', 'enum': ['unreg', 'fmg', 'faz', 'fmgfaz'] }, 'mgt_vdom': { 'type': 'string' }, 'mr': { 'type': 'integer', 'default': -1, 'example': -1 }, 'name': { 'type': 'string' }, 'os_type': { 'type': 'string', 'enum': [ 'unknown', 'fos', 'fsw', 'foc', 'fml', 'faz', 'fwb', 'fch', 'fct', 'log', 'fmg', 'fsa', 'fdd', 'fac', 'fpx' ] }, 'os_ver': { 'type': 'string', 'enum': [ 'unknown', '0.0', '1.0', '2.0', '3.0', '4.0', '5.0', '6.0' ] }, 'patch': { 'type': 'integer' }, 'platform_str': { 'type': 'string' }, 'psk': { 'type': 'string' }, 'sn': { 'type': 'string' }, 'vdom': { 'type': 'array', 'items': { 'comments': { 'type': 'string' }, 'name': { 'type': 'string' }, 'opmode': { 'type': 'string', 'enum': ['nat', 'transparent'] }, 'rtm_prof_id': { 'type': 'integer' }, 'status': { 'type': 'string' } } }, 'version': { 'type': 'integer' }, 'vm_cpu': { 'type': 'integer' }, 'vm_cpu_limit': { 'type': 'integer' }, 'vm_lic_expire': { 'type': 'integer' }, 'vm_mem': { 'type': 'integer' }, 'vm_mem_limit': { 'type': 'integer' }, 'vm_status': { 'type': 'integer' } }, 'api_tag': 0 }, { 'type': 'string', 'name': 'url', 'api_tag': 0 }] }, 'method_mapping': { 'get': 'object0', 'set': 'object1', 'update': 'object1' } } module_arg_spec = { 'loose_validation': { 'type': 'bool', 'required': False, 'default': False }, 'workspace_locking_adom': { 'type': 'str', 'required': False }, 'workspace_locking_timeout': { 'type': 'int', 'required': False, 'default': 300 }, 'params': { 'type': 'list', 'required': False }, 'method': { 'type': 'str', 'required': True, 'choices': ['get', 'set', 'update'] }, 'url_params': { 'type': 'dict', 'required': False } } module = AnsibleModule(argument_spec=module_arg_spec, supports_check_mode=False) method = module.params['method'] loose_validation = module.params['loose_validation'] fmgr = None payload = None response = DEFAULT_RESULT_OBJ if module._socket_path: connection = Connection(module._socket_path) tools = FMGRCommon() if loose_validation is False: tools.validate_module_params(module, body_schema) tools.validate_module_url_params(module, jrpc_urls, url_schema) full_url = tools.get_full_url_path(module, jrpc_urls) payload = tools.get_full_payload(module, full_url) fmgr = FortiManagerHandler(connection, module) fmgr.tools = tools else: module.fail_json(**FAIL_SOCKET_MSG) try: response = fmgr._conn.send_request(method, payload) fmgr.govern_response(module=module, results=response, msg='Operation Finished', ansible_facts=fmgr.construct_ansible_facts( response, module.params, module.params)) except Exception as e: raise FMGBaseException(e) module.exit_json(meta=response[1])
def main(): """ Main function :returns: SSL Profile Information """ module = AnsibleModule( argument_spec=dict( auth=dict(type='dict'), region=dict(default='na', type='str'), datacenter=dict(required=True, type='str'), network_domain=dict(required=True, type='str'), id=dict(required=False, default=None, type='str'), name=dict(required=False, default=None, type='str'), description=dict(required=False, default=None, type='str'), chain=dict(required=False, default=None, type='dict'), certificate=dict(required=False, default=None, type='dict'), new_name=dict(required=False, default=None, type='str'), ciphers=dict(required=False, default=None, type='str'), state=dict(default='present', choices=['present', 'absent']) ), supports_check_mode=True ) try: credentials = get_credentials(module) except ImportError as e: module.fail_json(msg='{0}'.format(e)) network_domain_name = module.params.get('network_domain') datacenter = module.params.get('datacenter') state = module.params.get('state') name = module.params.get('name') profile = cert = new_cert = cert_chain = new_cert_chain = None # Check Imports if not HAS_OPENSSL: module.fail_json(msg='Missing Python module: pyOpenSSL') # Check the region supplied is valid regions = get_regions() if module.params.get('region') not in regions: module.fail_json(msg='Invalid region. Regions must be one of {0}'.format(regions)) if credentials is False: module.fail_json(msg='Error: Could not load the user credentials') try: client = NTTMCPClient(credentials, module.params.get('region')) except NTTMCPAPIException as e: module.fail_json(msg=e.msg) # Get the CND try: network = client.get_network_domain_by_name(name=network_domain_name, datacenter=datacenter) network_domain_id = network.get('id') except (KeyError, IndexError, AttributeError, NTTMCPAPIException): module.fail_json(msg='Could not find the Cloud Network Domain: {0}'.format(network_domain_name)) # Verify SSL certificate and certificate chain schema if state == 'present': verify_cert_schema(module, client, network_domain_id) verify_cert_chain_schema(module, client, network_domain_id) # Check if the SSL certificate and chain already exist try: certs = client.list_vip_ssl(network_domain_id=network_domain_id, ssl_type='sslDomainCertificate', name=module.params.get('certificate').get('name')) if len(certs) == 1: new_cert = certs[0] new_cert_id = new_cert.get('id') except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as exc: module.fail_json(msg='Failed to get a list of current SSL certificates: {0}'.format(exc)) try: cert_chains = client.list_vip_ssl(network_domain_id=network_domain_id, ssl_type='sslCertificateChain', name=module.params.get('chain').get('name')) if len(cert_chains) == 1: new_cert_chain = cert_chains[0] new_cert_chain_id = new_cert_chain.get('id') except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as exc: module.fail_json(msg='Failed to get a list of current SSL certificate chains: {0}'.format(exc)) # Check if the SSL Profile already exists if name: try: profiles = client.list_vip_ssl(network_domain_id=network_domain_id, ssl_type='sslOffloadProfile', name=name) if len(profiles) == 1: if profiles[0].get('name'): profile = profiles[0] cert = client.get_vip_ssl(ssl_type='sslDomainCertificate', ssl_id=profiles[0].get('sslDomainCertificate').get('id')) cert_chain = client.get_vip_ssl(ssl_type='sslCertificateChain', ssl_id=profiles[0].get('sslCertificateChain').get('id')) except (KeyError, IndexError, AttributeError, NTTMCPAPIException) as exc: module.fail_json(msg='Failed getting a list of SSL Offload Profiles to check against - {0}'.format(exc)) if state == 'present': # Implement Check Mode if module.check_mode and not profile: module.exit_json(msg='A new SSL Offload Profile will be created') # Handle new certificates and certificate chains first if not new_cert: new_cert_id = import_ssl_cert(module, client, network_domain_id) if not new_cert_chain: new_cert_chain_id = import_ssl_cert_chain(module, client, network_domain_id) if not profile: create_ssl_offload_profile(module, client, network_domain_id, new_cert_id, new_cert_chain_id) else: if compare_ssl_profile(module, profile): update_ssl_offload_profile(module, client, profile, new_cert_id, new_cert_chain_id) else: module.exit_json(data=profile.get('id')) elif state == 'absent': if not profile: module.exit_json(msg='The SSL Profile was not found. Nothing to remove.') # Implement Check Mode if module.check_mode: module.exit_json(msg='The SSL Offload Profile with ID {0} will be deleted'.format(profile.get('id'))) delete_ssl_profile(module, client, network_domain_id, profile.get('id'), cert, cert_chain)
def main(): argument_spec = dict(interface=dict(required=True, type='str'), version=dict(required=False, type='str'), startup_query_interval=dict(required=False, type='str'), startup_query_count=dict(required=False, type='str'), robustness=dict(required=False, type='str'), querier_timeout=dict(required=False, type='str'), query_mrt=dict(required=False, type='str'), query_interval=dict(required=False, type='str'), last_member_qrt=dict(required=False, type='str'), last_member_query_count=dict(required=False, type='str'), group_timeout=dict(required=False, type='str'), report_llg=dict(type='bool'), immediate_leave=dict(type='bool'), oif_routemap=dict(required=False, type='str'), oif_prefix=dict(required=False, type='str', removed_in_version='2.10'), oif_source=dict(required=False, type='str', removed_in_version='2.10'), oif_ps=dict(required=False, type='raw'), restart=dict(type='bool', default=False), state=dict(choices=['present', 'absent', 'default'], default='present')) argument_spec.update(nxos_argument_spec) mutually_exclusive = [('oif_ps', 'oif_prefix'), ('oif_ps', 'oif_source'), ('oif_ps', 'oif_routemap'), ('oif_prefix', 'oif_routemap')] module = AnsibleModule(argument_spec=argument_spec, mutually_exclusive=mutually_exclusive, supports_check_mode=True) warnings = list() state = module.params['state'] interface = module.params['interface'] oif_prefix = module.params['oif_prefix'] oif_source = module.params['oif_source'] oif_routemap = module.params['oif_routemap'] oif_ps = module.params['oif_ps'] if oif_source and not oif_prefix: module.fail_json(msg='oif_prefix required when setting oif_source') elif oif_source and oif_prefix: oif_ps = [{'source': oif_source, 'prefix': oif_prefix}] elif not oif_source and oif_prefix: oif_ps = [{'prefix': oif_prefix}] intf_type = get_interface_type(interface) if get_interface_mode(interface, intf_type, module) == 'layer2': module.fail_json(msg='this module only works on Layer 3 interfaces') existing = get_igmp_interface(module, interface) existing_copy = existing.copy() end_state = existing_copy if not existing.get('version'): module.fail_json(msg='pim needs to be enabled on the interface') existing_oif_prefix_source = existing.get('oif_prefix_source') # not json serializable existing.pop('oif_prefix_source') if oif_routemap and existing_oif_prefix_source: module.fail_json(msg='Delete static-oif configurations on this ' 'interface if you want to use a routemap') if oif_ps and existing.get('oif_routemap'): module.fail_json(msg='Delete static-oif route-map configuration ' 'on this interface if you want to config ' 'static entries') args = [ 'version', 'startup_query_interval', 'startup_query_count', 'robustness', 'querier_timeout', 'query_mrt', 'query_interval', 'last_member_qrt', 'last_member_query_count', 'group_timeout', 'report_llg', 'immediate_leave', 'oif_routemap', ] changed = False commands = [] proposed = dict((k, v) for k, v in module.params.items() if v is not None and k in args) CANNOT_ABSENT = [ 'version', 'startup_query_interval', 'startup_query_count', 'robustness', 'querier_timeout', 'query_mrt', 'query_interval', 'last_member_qrt', 'last_member_query_count', 'group_timeout', 'report_llg', 'immediate_leave' ] if state == 'absent': for each in CANNOT_ABSENT: if each in proposed: module.fail_json(msg='only params: oif_prefix, oif_source, ' 'oif_ps, oif_routemap can be used when ' 'state=absent') # delta check for all params except oif_ps delta = dict(set(proposed.items()).difference(existing.items())) if oif_ps: if oif_ps == 'default': delta['oif_ps'] = [] else: delta['oif_ps'] = oif_ps if state == 'present': if delta: command = config_igmp_interface(delta, existing, existing_oif_prefix_source) if command: commands.append(command) elif state == 'default': command = config_default_igmp_interface(existing, delta) if command: commands.append(command) elif state == 'absent': command = None if existing.get('oif_routemap') or existing_oif_prefix_source: command = config_remove_oif(existing, existing_oif_prefix_source) if command: commands.append(command) command = config_default_igmp_interface(existing, delta) if command: commands.append(command) cmds = [] results = {} if commands: commands.insert(0, ['interface {0}'.format(interface)]) cmds = flatten_list(commands) if module.check_mode: module.exit_json(changed=True, commands=cmds) else: load_config(module, cmds) changed = True end_state = get_igmp_interface(module, interface) if 'configure' in cmds: cmds.pop(0) if module.params['restart']: cmd = {'command': 'restart igmp', 'output': 'text'} run_commands(module, cmd) results['proposed'] = proposed results['existing'] = existing_copy results['updates'] = cmds results['changed'] = changed results['warnings'] = warnings results['end_state'] = end_state module.exit_json(**results)
def main(): argument_spec = ec2_argument_spec() argument_spec.update(dict( state=dict(aliases=['command'], choices=['present', 'absent', 'get', 'create', 'delete'], required=True), zone=dict(required=True), hosted_zone_id=dict(required=False, default=None), record=dict(required=True), ttl=dict(required=False, type='int', default=3600), type=dict(choices=['A', 'CNAME', 'MX', 'AAAA', 'TXT', 'PTR', 'SRV', 'SPF', 'NS', 'SOA'], required=True), alias=dict(required=False, type='bool'), alias_hosted_zone_id=dict(required=False), alias_evaluate_target_health=dict(required=False, type='bool', default=False), value=dict(required=False, type='list', default=[]), overwrite=dict(required=False, type='bool'), retry_interval=dict(required=False, default=500), private_zone=dict(required=False, type='bool', default=False), identifier=dict(required=False, default=None), weight=dict(required=False, type='int'), region=dict(required=False), health_check=dict(required=False), failover=dict(required=False, choices=['PRIMARY', 'SECONDARY']), vpc_id=dict(required=False), wait=dict(required=False, type='bool', default=False), wait_timeout=dict(required=False, type='int', default=300), )) # state=present, absent, create, delete THEN value is required required_if = [('state', 'present', ['value']), ('state', 'create', ['value'])] required_if.extend([('state', 'absent', ['value']), ('state', 'delete', ['value'])]) # If alias is True then you must specify alias_hosted_zone as well required_together = [['alias', 'alias_hosted_zone_id']] # failover, region, and weight are mutually exclusive mutually_exclusive = [('failover', 'region', 'weight')] module = AnsibleModule(argument_spec=argument_spec, required_together=required_together, required_if=required_if, mutually_exclusive=mutually_exclusive) if not HAS_BOTO: module.fail_json(msg='boto required for this module') if distutils.version.StrictVersion(boto.__version__) < distutils.version.StrictVersion(MINIMUM_BOTO_VERSION): module.fail_json(msg='Found boto in version %s, but >= %s is required' % (boto.__version__, MINIMUM_BOTO_VERSION)) if module.params['state'] in ('present', 'create'): command_in = 'create' elif module.params['state'] in ('absent', 'delete'): command_in = 'delete' elif module.params['state'] == 'get': command_in = 'get' zone_in = module.params.get('zone').lower() hosted_zone_id_in = module.params.get('hosted_zone_id') ttl_in = module.params.get('ttl') record_in = module.params.get('record').lower() type_in = module.params.get('type') value_in = module.params.get('value') alias_in = module.params.get('alias') alias_hosted_zone_id_in = module.params.get('alias_hosted_zone_id') alias_evaluate_target_health_in = module.params.get('alias_evaluate_target_health') retry_interval_in = module.params.get('retry_interval') if module.params['vpc_id'] is not None: private_zone_in = True else: private_zone_in = module.params.get('private_zone') identifier_in = module.params.get('identifier') weight_in = module.params.get('weight') region_in = module.params.get('region') health_check_in = module.params.get('health_check') failover_in = module.params.get('failover') vpc_id_in = module.params.get('vpc_id') wait_in = module.params.get('wait') wait_timeout_in = module.params.get('wait_timeout') region, ec2_url, aws_connect_kwargs = get_aws_connection_info(module) if zone_in[-1:] != '.': zone_in += "." if record_in[-1:] != '.': record_in += "." if command_in == 'create' or command_in == 'delete': if alias_in and len(value_in) != 1: module.fail_json(msg="parameter 'value' must contain a single dns name for alias records") if (weight_in is not None or region_in is not None or failover_in is not None) and identifier_in is None: module.fail_json(msg="If you specify failover, region or weight you must also specify identifier") if (weight_in is None and region_in is None and failover_in is None) and identifier_in is not None: module.fail_json(msg="You have specified identifier which makes sense only if you specify one of: weight, region or failover.") # connect to the route53 endpoint try: conn = Route53Connection(**aws_connect_kwargs) except boto.exception.BotoServerError as e: module.fail_json(msg=e.error_message) # Find the named zone ID zone = get_zone_by_name(conn, module, zone_in, private_zone_in, hosted_zone_id_in, vpc_id_in) # Verify that the requested zone is already defined in Route53 if zone is None: errmsg = "Zone %s does not exist in Route53" % zone_in module.fail_json(msg=errmsg) record = {} found_record = False wanted_rset = Record(name=record_in, type=type_in, ttl=ttl_in, identifier=identifier_in, weight=weight_in, region=region_in, health_check=health_check_in, failover=failover_in) for v in value_in: if alias_in: wanted_rset.set_alias(alias_hosted_zone_id_in, v, alias_evaluate_target_health_in) else: wanted_rset.add_value(v) sets = invoke_with_throttling_retries(conn.get_all_rrsets, zone.id, name=record_in, type=type_in, identifier=identifier_in) sets_iter = iter(sets) while True: try: rset = invoke_with_throttling_retries(next, sets_iter) except StopIteration: break # Due to a bug in either AWS or Boto, "special" characters are returned as octals, preventing round # tripping of things like * and @. decoded_name = rset.name.replace(r'\052', '*') decoded_name = decoded_name.replace(r'\100', '@') # Need to save this changes in rset, because of comparing rset.to_xml() == wanted_rset.to_xml() in next block rset.name = decoded_name if identifier_in is not None: identifier_in = str(identifier_in) if rset.type == type_in and decoded_name.lower() == record_in.lower() and rset.identifier == identifier_in: found_record = True record['zone'] = zone_in record['type'] = rset.type record['record'] = decoded_name record['ttl'] = rset.ttl record['value'] = ','.join(sorted(rset.resource_records)) record['values'] = sorted(rset.resource_records) if hosted_zone_id_in: record['hosted_zone_id'] = hosted_zone_id_in record['identifier'] = rset.identifier record['weight'] = rset.weight record['region'] = rset.region record['failover'] = rset.failover record['health_check'] = rset.health_check if hosted_zone_id_in: record['hosted_zone_id'] = hosted_zone_id_in if rset.alias_dns_name: record['alias'] = True record['value'] = rset.alias_dns_name record['values'] = [rset.alias_dns_name] record['alias_hosted_zone_id'] = rset.alias_hosted_zone_id record['alias_evaluate_target_health'] = rset.alias_evaluate_target_health else: record['alias'] = False record['value'] = ','.join(sorted(rset.resource_records)) record['values'] = sorted(rset.resource_records) if command_in == 'create' and rset.to_xml() == wanted_rset.to_xml(): module.exit_json(changed=False) # We need to look only at the first rrset returned by the above call, # so break here. The returned elements begin with the one matching our # requested name, type, and identifier, if such an element exists, # followed by all others that come after it in alphabetical order. # Therefore, if the first set does not match, no subsequent set will # match either. break if command_in == 'get': if type_in == 'NS': ns = record.get('values', []) else: # Retrieve name servers associated to the zone. z = invoke_with_throttling_retries(conn.get_zone, zone_in) ns = invoke_with_throttling_retries(z.get_nameservers) module.exit_json(changed=False, set=record, nameservers=ns) if command_in == 'delete' and not found_record: module.exit_json(changed=False) changes = ResourceRecordSets(conn, zone.id) if command_in == 'create' or command_in == 'delete': if command_in == 'create' and found_record: if not module.params['overwrite']: module.fail_json(msg="Record already exists with different value. Set 'overwrite' to replace it") command = 'UPSERT' else: command = command_in.upper() changes.add_change_record(command, wanted_rset) try: result = invoke_with_throttling_retries(commit, changes, retry_interval_in, wait_in, wait_timeout_in) except boto.route53.exception.DNSServerError as e: txt = e.body.split("<Message>")[1] txt = txt.split("</Message>")[0] if "but it already exists" in txt: module.exit_json(changed=False) else: module.fail_json(msg=txt) except TimeoutError: module.fail_json(msg='Timeout waiting for changes to replicate') module.exit_json(changed=True)
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_affinity_interrupt": { "required": False, "type": "dict", "default": None, "options": { "affinity_cpumask": { "required": False, "type": "str" }, "id": { "required": True, "type": "int" }, "interrupt": { "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_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(): jrpc_urls = [ '/pm/config/adom/{adom}/obj/antivirus/profile/{profile}/http', '/pm/config/global/obj/antivirus/profile/{profile}/http' ] perobject_jrpc_urls = [ '/pm/config/adom/{adom}/obj/antivirus/profile/{profile}/http/{http}', '/pm/config/global/obj/antivirus/profile/{profile}/http/{http}' ] url_params = ['adom', 'profile'] 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' }, 'adom': { 'required': True, 'type': 'str' }, 'profile': { 'required': True, 'type': 'str' }, 'antivirus_profile_http': { 'required': False, 'type': 'dict', 'options': { 'archive-block': { 'required': False, 'type': 'list', 'choices': [ 'encrypted', 'corrupted', 'multipart', 'nested', 'mailbomb', 'unhandled', 'partiallycorrupted', 'fileslimit', 'timeout' ] }, 'archive-log': { 'required': False, 'type': 'list', 'choices': [ 'encrypted', 'corrupted', 'multipart', 'nested', 'mailbomb', 'unhandled', 'partiallycorrupted', 'fileslimit', 'timeout' ] }, 'content-disarm': { 'required': False, 'choices': [ 'disable', 'enable' ], 'type': 'str' }, 'emulator': { 'required': False, 'choices': [ 'disable', 'enable' ], 'type': 'str' }, 'options': { 'required': False, 'type': 'list', 'choices': [ 'scan', 'file-filter', 'quarantine', 'avquery', 'avmonitor', 'strict-file' ] }, 'outbreak-prevention': { 'required': False, 'choices': [ 'disabled', 'files', 'full-archive' ], 'type': 'str' } } } } params_validation_blob = [] check_galaxy_version(module_arg_spec) module = AnsibleModule(argument_spec=check_parameter_bypass(module_arg_spec, 'antivirus_profile_http'), 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(): mkeyname = 'name' fields = { "access_token": {"required": False, "type": "str", "no_log": True}, "vdom": {"required": False, "type": "str", "default": "root"}, "state": {"required": False, "type": "str", "choices": ["present", "absent"]}, "firewall_wildcard_fqdn_custom": { "required": False, "type": "dict", "default": None, "options": { "state": {"required": False, "type": "str", "choices": ["present", "absent"]}, "color": {"required": False, "type": "int"}, "comment": {"required": False, "type": "str"}, "name": {"required": True, "type": "str"}, "uuid": {"required": False, "type": "str"}, "visibility": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "wildcard_fqdn": {"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_firewall_wildcard_fqdn(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(): # # Open Stack 共通引数取得 # argument_spec = openstack_full_argument_spec( name=dict(required=True), size=dict(default=100, type='int', choices=[100, 250, 500, 1000, 2000, 4000, 8000, 12000]), iops_per_gb=dict(default='2', choices=['2', '4']), initiator_iqns=dict(default=[], type='list'), virtual_storage=dict(required=False), availability_zone=dict(required=False), state=dict(default='present', choices=['absent', 'present'])) module_kwargs = openstack_module_kwargs() # # Ansible Module の 定義 # module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True, **module_kwargs) # # Ansible引数の取得 # name = module.params['name'] state = module.params['state'] # # ECLSDKがインストールされているかの確認 # if HAS_ECLSDK == False: module.fail_json(msg='ECLSDK is not exist.') # # ECLへの接続 # ecl2 = _get_ecl_connection_from_module(module) volume = _find_storage_volume_by_name(ecl2, name) # # 仮想ストレージの作成 # if state == 'present': # # 既に仮想ボリュームが存在する場合 # if not volume == None: module.exit_json( msg='Virtual storage volume(%s) is already exist.' % (name), changed=False) # # 仮想ストレージボリュームの作成 # _create_storage_volume(module, ecl2) # # 正常終了 # module.exit_json(changed=True) return True else: # # 既に仮想ストレージが存在しない場合 # if volume == None: module.exit_json(msg='Virtual storage volume(%s) is not exist.' % (name), changed=False) # # 仮想ストレージボリュームの削除 # _delete_storage_volume_by_name(module, ecl2) # # 正常終了 # module.exit_json(changed=True) return True
class LinkStatus(object): """Get interface link status information""" def __init__(self, argument_spec): self.spec = argument_spec self.module = None self.init_module() # interface name self.interface = self.module.params['interface'] self.interface = self.interface.replace(' ', '').lower() self.param_type = None self.if_type = None # state self.results = dict() self.result = dict() def check_params(self): """Check all input params""" if not self.interface: self.module.fail_json(msg='Error: Interface name cannot be empty.') if self.interface and self.interface != 'all': if not self.if_type: self.module.fail_json( msg='Error: Interface name of %s is error.' % self.interface) def init_module(self): """Init module object""" self.module = AnsibleModule(argument_spec=self.spec, supports_check_mode=True) def show_result(self): """Show result""" self.results['result'] = self.result self.module.exit_json(**self.results) def get_intf_dynamic_info(self, dyn_info, intf_name): """Get interface dynamic information""" if not intf_name: return if dyn_info: for eles in dyn_info: if eles.tag in [ "ifPhyStatus", "ifV4State", "ifV6State", "ifLinkStatus" ]: if eles.tag == "ifPhyStatus": self.result[intf_name][ 'Current physical state'] = eles.text elif eles.tag == "ifLinkStatus": self.result[intf_name][ 'Current link state'] = eles.text elif eles.tag == "ifV4State": self.result[intf_name][ 'Current IPv4 state'] = eles.text elif eles.tag == "ifV6State": self.result[intf_name][ 'Current IPv6 state'] = eles.text def get_intf_statistics_info(self, stat_info, intf_name): """Get interface statistics information""" if not intf_name: return if_type = get_interface_type(intf_name) if if_type == 'fcoe-port' or if_type == 'nve' or if_type == 'tunnel' or \ if_type == 'vbdif' or if_type == 'vlanif': return if stat_info: for eles in stat_info: if eles.tag in [ "receiveByte", "sendByte", "rcvUniPacket", "rcvMutiPacket", "rcvBroadPacket", "sendUniPacket", "sendMutiPacket", "sendBroadPacket", "rcvErrorPacket", "rcvDropPacket", "sendErrorPacket", "sendDropPacket" ]: if eles.tag == "receiveByte": self.result[intf_name][ 'Inbound octets(bytes)'] = eles.text elif eles.tag == "rcvUniPacket": self.result[intf_name][ 'Inbound unicast(pkts)'] = eles.text elif eles.tag == "rcvMutiPacket": self.result[intf_name][ 'Inbound multicast(pkts)'] = eles.text elif eles.tag == "rcvBroadPacket": self.result[intf_name][ 'Inbound broadcast(pkts)'] = eles.text elif eles.tag == "rcvErrorPacket": self.result[intf_name][ 'Inbound error(pkts)'] = eles.text elif eles.tag == "rcvDropPacket": self.result[intf_name][ 'Inbound drop(pkts)'] = eles.text elif eles.tag == "sendByte": self.result[intf_name][ 'Outbound octets(bytes)'] = eles.text elif eles.tag == "sendUniPacket": self.result[intf_name][ 'Outbound unicast(pkts)'] = eles.text elif eles.tag == "sendMutiPacket": self.result[intf_name][ 'Outbound multicast(pkts)'] = eles.text elif eles.tag == "sendBroadPacket": self.result[intf_name][ 'Outbound broadcast(pkts)'] = eles.text elif eles.tag == "sendErrorPacket": self.result[intf_name][ 'Outbound error(pkts)'] = eles.text elif eles.tag == "sendDropPacket": self.result[intf_name][ 'Outbound drop(pkts)'] = eles.text def get_intf_cleared_stat(self, clr_stat, intf_name): """Get interface cleared state information""" if not intf_name: return if_type = get_interface_type(intf_name) if if_type == 'fcoe-port' or if_type == 'nve' or if_type == 'tunnel' or \ if_type == 'vbdif' or if_type == 'vlanif': return if clr_stat: for eles in clr_stat: if eles.tag in [ "inByteRate", "inPacketRate", "outByteRate", "outPacketRate" ]: if eles.tag == "inByteRate": self.result[intf_name][ 'Inbound rate(byte/sec)'] = eles.text elif eles.tag == "inPacketRate": self.result[intf_name][ 'Inbound rate(pkts/sec)'] = eles.text elif eles.tag == "outByteRate": self.result[intf_name][ 'Outbound rate(byte/sec)'] = eles.text elif eles.tag == "outPacketRate": self.result[intf_name][ 'Outbound rate(pkts/sec)'] = eles.text def get_all_interface_info(self, intf_type=None): """Get interface information all or by interface type""" xml_str = CE_NC_GET_INT_STATISTICS % '' con_obj = get_nc_config(self.module, xml_str) if "<data/>" in con_obj: return xml_str = con_obj.replace('\r', '').replace('\n', '').\ replace('xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"', "").\ replace('xmlns="http://www.huawei.com/netconf/vrp"', "") # get link status information root = ElementTree.fromstring(xml_str) intfs_info = root.find("ifm/interfaces") if not intfs_info: return intf_name = '' flag = False for eles in intfs_info: if eles.tag == "interface": for ele in eles: if ele.tag in [ "ifName", "ifDynamicInfo", "ifStatistics", "ifClearedStat" ]: if ele.tag == "ifName": intf_name = ele.text.lower() if intf_type: if get_interface_type( intf_name) != intf_type.lower(): break else: flag = True self.init_interface_data(intf_name) if is_ethernet_port(intf_name): self.get_port_info(intf_name) if ele.tag == "ifDynamicInfo": self.get_intf_dynamic_info(ele, intf_name) elif ele.tag == "ifStatistics": self.get_intf_statistics_info(ele, intf_name) elif ele.tag == "ifClearedStat": self.get_intf_cleared_stat(ele, intf_name) if intf_type and not flag: self.module.fail_json( msg='Error: %s interface type does not exist.' % intf_type.upper()) def get_interface_info(self): """Get interface information""" xml_str = CE_NC_GET_INT_STATISTICS % self.interface.upper() con_obj = get_nc_config(self.module, xml_str) if "<data/>" in con_obj: self.module.fail_json(msg='Error: %s interface does not exist.' % self.interface.upper()) return xml_str = con_obj.replace('\r', '').replace('\n', '').\ replace('xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"', "").\ replace('xmlns="http://www.huawei.com/netconf/vrp"', "") # get link status information root = ElementTree.fromstring(xml_str) intf_info = root.find("ifm/interfaces/interface") if intf_info: for eles in intf_info: if eles.tag in [ "ifDynamicInfo", "ifStatistics", "ifClearedStat" ]: if eles.tag == "ifDynamicInfo": self.get_intf_dynamic_info(eles, self.interface) elif eles.tag == "ifStatistics": self.get_intf_statistics_info(eles, self.interface) elif eles.tag == "ifClearedStat": self.get_intf_cleared_stat(eles, self.interface) def init_interface_data(self, intf_name): """Init interface data""" # init link status data self.result[intf_name] = dict() self.result[intf_name]['Current physical state'] = 'down' self.result[intf_name]['Current link state'] = 'down' self.result[intf_name]['Current IPv4 state'] = 'down' self.result[intf_name]['Current IPv6 state'] = 'down' self.result[intf_name]['Inbound octets(bytes)'] = '--' self.result[intf_name]['Inbound unicast(pkts)'] = '--' self.result[intf_name]['Inbound multicast(pkts)'] = '--' self.result[intf_name]['Inbound broadcast(pkts)'] = '--' self.result[intf_name]['Inbound error(pkts)'] = '--' self.result[intf_name]['Inbound drop(pkts)'] = '--' self.result[intf_name]['Inbound rate(byte/sec)'] = '--' self.result[intf_name]['Inbound rate(pkts/sec)'] = '--' self.result[intf_name]['Outbound octets(bytes)'] = '--' self.result[intf_name]['Outbound unicast(pkts)'] = '--' self.result[intf_name]['Outbound multicast(pkts)'] = '--' self.result[intf_name]['Outbound broadcast(pkts)'] = '--' self.result[intf_name]['Outbound error(pkts)'] = '--' self.result[intf_name]['Outbound drop(pkts)'] = '--' self.result[intf_name]['Outbound rate(byte/sec)'] = '--' self.result[intf_name]['Outbound rate(pkts/sec)'] = '--' self.result[intf_name]['Speed'] = '--' def get_port_info(self, interface): """Get port information""" if_type = get_interface_type(interface) if if_type == 'meth': xml_str = CE_NC_GET_PORT_SPEED % interface.lower().replace( 'meth', 'MEth') else: xml_str = CE_NC_GET_PORT_SPEED % interface.upper() con_obj = get_nc_config(self.module, xml_str) if "<data/>" in con_obj: return xml_str = con_obj.replace('\r', '').replace('\n', '').\ replace('xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"', "").\ replace('xmlns="http://www.huawei.com/netconf/vrp"', "") # get link status information root = ElementTree.fromstring(xml_str) port_info = root.find("devm/ports/port") if port_info: for eles in port_info: if eles.tag == "ethernetPort": for ele in eles: if ele.tag == 'speed': self.result[interface]['Speed'] = ele.text def get_link_status(self): """Get link status information""" if self.param_type == INTERFACE_FULL_NAME: self.init_interface_data(self.interface) self.get_interface_info() if is_ethernet_port(self.interface): self.get_port_info(self.interface) elif self.param_type == INTERFACE_TYPE: self.get_all_interface_info(self.interface) else: self.get_all_interface_info() def get_intf_param_type(self): """Get the type of input interface parameter""" if self.interface == 'all': self.param_type = INTERFACE_ALL return if self.if_type == self.interface: self.param_type = INTERFACE_TYPE return self.param_type = INTERFACE_FULL_NAME def work(self): """Worker""" self.if_type = get_interface_type(self.interface) self.check_params() self.get_intf_param_type() self.get_link_status() self.show_result()
def main(): fields = { "host": {"required": False, "type": "str"}, "username": {"required": False, "type": "str"}, "password": {"required": False, "type": "str", "default": "", "no_log": True}, "vdom": {"required": False, "type": "str", "default": "root"}, "https": {"required": False, "type": "bool", "default": True}, "ssl_verify": {"required": False, "type": "bool", "default": True}, "state": {"required": False, "type": "str", "choices": ["present", "absent"]}, "report_chart": { "required": False, "type": "dict", "default": None, "options": { "state": {"required": False, "type": "str", "choices": ["present", "absent"]}, "background": {"required": False, "type": "str"}, "category": {"required": False, "type": "str", "choices": ["misc", "traffic", "event", "virus", "webfilter", "attack", "spam", "dlp", "app-ctrl", "vulnerability"]}, "category_series": {"required": False, "type": "dict", "options": { "databind": {"required": False, "type": "str"}, "font_size": {"required": False, "type": "int"} }}, "color_palette": {"required": False, "type": "str"}, "column": {"required": False, "type": "list", "options": { "detail_unit": {"required": False, "type": "str"}, "detail_value": {"required": False, "type": "str"}, "footer_unit": {"required": False, "type": "str"}, "footer_value": {"required": False, "type": "str"}, "header_value": {"required": False, "type": "str"}, "id": {"required": True, "type": "int"}, "mapping": {"required": False, "type": "list", "options": { "displayname": {"required": False, "type": "str"}, "id": {"required": True, "type": "int"}, "op": {"required": False, "type": "str", "choices": ["none", "greater", "greater-equal", "less", "less-equal", "equal", "between"]}, "value_type": {"required": False, "type": "str", "choices": ["integer", "string"]}, "value1": {"required": False, "type": "str"}, "value2": {"required": False, "type": "str"} }} }}, "comments": {"required": False, "type": "str"}, "dataset": {"required": False, "type": "str"}, "dimension": {"required": False, "type": "str", "choices": ["2D", "3D"]}, "drill_down_charts": {"required": False, "type": "list", "options": { "chart_name": {"required": False, "type": "str"}, "id": {"required": True, "type": "int"}, "status": {"required": False, "type": "str", "choices": ["enable", "disable"]} }}, "favorite": {"required": False, "type": "str", "choices": ["no", "yes"]}, "graph_type": {"required": False, "type": "str", "choices": ["none", "bar", "pie", "line", "flow"]}, "legend": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "legend_font_size": {"required": False, "type": "int"}, "name": {"required": True, "type": "str"}, "period": {"required": False, "type": "str", "choices": ["last24h", "last7d"]}, "policy": {"required": False, "type": "int"}, "style": {"required": False, "type": "str", "choices": ["auto", "manual"]}, "title": {"required": False, "type": "str"}, "title_font_size": {"required": False, "type": "int"}, "type": {"required": False, "type": "str", "choices": ["graph", "table"]}, "value_series": {"required": False, "type": "dict", "options": { "databind": {"required": False, "type": "str"} }}, "x_series": {"required": False, "type": "dict", "options": { "caption": {"required": False, "type": "str"}, "caption_font_size": {"required": False, "type": "int"}, "databind": {"required": False, "type": "str"}, "font_size": {"required": False, "type": "int"}, "is_category": {"required": False, "type": "str", "choices": ["yes", "no"]}, "label_angle": {"required": False, "type": "str", "choices": ["45-degree", "vertical", "horizontal"]}, "scale_direction": {"required": False, "type": "str", "choices": ["decrease", "increase"]}, "scale_format": {"required": False, "type": "str", "choices": ["YYYY-MM-DD-HH-MM", "YYYY-MM-DD HH", "YYYY-MM-DD", "YYYY-MM", "YYYY", "HH-MM", "MM-DD"]}, "scale_step": {"required": False, "type": "int"}, "scale_unit": {"required": False, "type": "str", "choices": ["minute", "hour", "day", "month", "year"]}, "unit": {"required": False, "type": "str"} }}, "y_series": {"required": False, "type": "dict", "options": { "caption": {"required": False, "type": "str"}, "caption_font_size": {"required": False, "type": "int"}, "databind": {"required": False, "type": "str"}, "extra_databind": {"required": False, "type": "str"}, "extra_y": {"required": False, "type": "str", "choices": ["enable", "disable"]}, "extra_y_legend": {"required": False, "type": "str"}, "font_size": {"required": False, "type": "int"}, "group": {"required": False, "type": "str"}, "label_angle": {"required": False, "type": "str", "choices": ["45-degree", "vertical", "horizontal"]}, "unit": {"required": False, "type": "str"}, "y_legend": {"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_report(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_report(module.params, fos) fos.logout() if not is_error: module.exit_json(changed=has_changed, meta=result) else: module.fail_json(msg="Error in repo", meta=result)
def main(): argument_spec = aci_argument_spec argument_spec.update( compare_export_policy=dict(type='str'), compare_snapshot=dict(type='str'), description=dict(type='str', aliases=['descr']), export_policy=dict(type='str'), fail_on_decrypt=dict(type='bool'), import_mode=dict(type='str', choices=['atomic', 'best-effort']), import_policy=dict(type='str'), import_type=dict(type='str', choices=['merge', 'replace']), snapshot=dict(type='str', required=True), state=dict(type='str', default='rollback', choices=['preview', 'rollback']), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=False, required_if=[ [ 'state', 'preview', ['compare_export_policy', 'compare_snapshot'] ], ['state', 'rollback', ['import_policy']], ], ) description = module.params['description'] export_policy = module.params['export_policy'] fail_on_decrypt = module.params['fail_on_decrypt'] if fail_on_decrypt is True: fail_on_decrypt = 'yes' elif fail_on_decrypt is False: fail_on_decrypt = 'no' import_mode = module.params['import_mode'] import_policy = module.params['import_policy'] import_type = module.params['import_type'] snapshot = module.params['snapshot'] state = module.params['state'] aci = ACIModule(module) if state == 'rollback': if snapshot.startswith('run-'): snapshot = snapshot.replace('run-', '', 1) if not snapshot.endswith('.tar.gz'): snapshot += '.tar.gz' filename = 'ce2_{0}-{1}'.format(export_policy, snapshot) aci.construct_url(root_class=dict( aci_class='configImportP', aci_rn='fabric/configimp-{}'.format(import_policy), filter_target='eq(configImportP.name, "{}")'.format(import_policy), module_object=import_policy, ), ) aci.get_existing() # Filter out module parameters with null values aci.payload( aci_class='configImportP', class_config=dict( adminSt='triggered', descr=description, failOnDecryptErrors=fail_on_decrypt, fileName=filename, importMode=import_mode, importType=import_type, name=import_policy, snapshot='yes', ), ) # Generate config diff which will be used as POST request body aci.get_diff(aci_class='configImportP') # Submit changes if module not in check_mode and the proposed is different than existing aci.post_config() elif state == 'preview': aci.result[ 'url'] = '%(protocol)s://%(hostname)s/mqapi2/snapshots.diff.xml' % module.params aci.result['filter_string'] = ( '?s1dn=uni/backupst/snapshots-[uni/fabric/configexp-%(export_policy)s]/snapshot-%(snapshot)s&' 's2dn=uni/backupst/snapshots-[uni/fabric/configexp-%(compare_export_policy)s]/snapshot-%(compare_snapshot)s' ) % module.params # Generate rollback comparison get_preview(aci) module.exit_json(**aci.result)
def main(): argument_spec = aci_argument_spec() argument_spec.update( group=dict(type='str', aliases=['group']), # Not required for querying all objects node=dict(type='str', aliases=['node']), state=dict(type='str', default='present', choices=['absent', 'present', 'query']), name_alias=dict(type='str'), ) module = AnsibleModule( argument_spec=argument_spec, supports_check_mode=True, required_if=[ ['state', 'absent', ['node', 'group']], ['state', 'present', ['node', 'group']], ], ) state = module.params.get('state') group = module.params.get('group') node = module.params.get('node') name_alias = module.params.get('name_alias') aci = ACIModule(module) aci.construct_url( root_class=dict( aci_class='firmwareFwGrp', aci_rn='fabric/fwgrp-{0}'.format(group), target_filter={'name': group}, module_object=group, ), subclass_1=dict( aci_class='fabricNodeBlk', aci_rn='nodeblk-blk{0}-{0}'.format(node), target_filter={'name': node}, module_object=node, ), ) aci.get_existing() if state == 'present': aci.payload( aci_class='fabricNodeBlk', class_config=dict( from_=node, to_=node, nameAlias=name_alias, ), ) aci.get_diff(aci_class='fabricNodeBlk') aci.post_config() elif state == 'absent': aci.delete_config() aci.exit_json()
def main(): module = AnsibleModule( argument_spec=dict( state=dict(type='str', default='present', choices=['present', 'absent']), force=dict(type='bool', default=False), path=dict(type='path', required=True), privatekey_path=dict(type='path'), privatekey_content=dict(type='str', no_log=True), format=dict(type='str', default='PEM', choices=['OpenSSH', 'PEM']), privatekey_passphrase=dict(type='str', no_log=True), backup=dict(type='bool', default=False), select_crypto_backend=dict(type='str', choices=['auto', 'pyopenssl', 'cryptography'], default='auto'), return_content=dict(type='bool', default=False), ), supports_check_mode=True, add_file_common_args=True, required_if=[('state', 'present', ['privatekey_path', 'privatekey_content'], True)], mutually_exclusive=( ['privatekey_path', 'privatekey_content'], ), ) minimal_cryptography_version = MINIMAL_CRYPTOGRAPHY_VERSION if module.params['format'] == 'OpenSSH': minimal_cryptography_version = MINIMAL_CRYPTOGRAPHY_VERSION_OPENSSH backend = module.params['select_crypto_backend'] if backend == 'auto': # Detection what is possible can_use_cryptography = CRYPTOGRAPHY_FOUND and CRYPTOGRAPHY_VERSION >= LooseVersion(minimal_cryptography_version) can_use_pyopenssl = PYOPENSSL_FOUND and PYOPENSSL_VERSION >= LooseVersion(MINIMAL_PYOPENSSL_VERSION) # Decision if can_use_cryptography: backend = 'cryptography' elif can_use_pyopenssl: if module.params['format'] == 'OpenSSH': module.fail_json( msg=missing_required_lib('cryptography >= {0}'.format(MINIMAL_CRYPTOGRAPHY_VERSION_OPENSSH)), exception=CRYPTOGRAPHY_IMP_ERR ) backend = 'pyopenssl' # Success? if backend == 'auto': module.fail_json(msg=("Can't detect any of the required Python libraries " "cryptography (>= {0}) or PyOpenSSL (>= {1})").format( minimal_cryptography_version, MINIMAL_PYOPENSSL_VERSION)) if module.params['format'] == 'OpenSSH' and backend != 'cryptography': module.fail_json(msg="Format OpenSSH requires the cryptography backend.") if backend == 'pyopenssl': if not PYOPENSSL_FOUND: module.fail_json(msg=missing_required_lib('pyOpenSSL >= {0}'.format(MINIMAL_PYOPENSSL_VERSION)), exception=PYOPENSSL_IMP_ERR) module.deprecate('The module is using the PyOpenSSL backend. This backend has been deprecated', version='2.0.0', collection_name='community.crypto') elif backend == 'cryptography': if not CRYPTOGRAPHY_FOUND: module.fail_json(msg=missing_required_lib('cryptography >= {0}'.format(minimal_cryptography_version)), exception=CRYPTOGRAPHY_IMP_ERR) 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 ) try: public_key = PublicKey(module, backend) if public_key.state == 'present': if module.check_mode: result = public_key.dump() result['changed'] = module.params['force'] or not public_key.check(module) module.exit_json(**result) public_key.generate(module) else: if module.check_mode: result = public_key.dump() result['changed'] = os.path.exists(module.params['path']) module.exit_json(**result) public_key.remove(module) result = public_key.dump() module.exit_json(**result) except OpenSSLObjectError as exc: module.fail_json(msg=to_native(exc))
def main(): module = AnsibleModule(argument_spec=dict( outputfile=dict(required=True), host=dict(required=True), username=dict(required=True), password=dict(required=True, no_log=True), enablePassword=dict(required=False, no_log=True), deviceType=dict(required=True), ), supports_check_mode=False) username = module.params['username'] password = module.params['password'] enablePassword = module.params['enablePassword'] cliCommand = "save erase \n" outputfile = module.params['outputfile'] hostIP = module.params['host'] deviceType = module.params['deviceType'] output = "" # Create instance of SSHClient object remote_conn_pre = paramiko.SSHClient() # Automatically add untrusted hosts (make sure okay for security policy in your environment) remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # initiate SSH connection with the switch remote_conn_pre.connect(hostIP, username=username, password=password) time.sleep(2) # Use invoke_shell to establish an 'interactive session' remote_conn = remote_conn_pre.invoke_shell() time.sleep(2) # Enable and enter configure terminal then send command output = output + cnos.waitForDeviceResponse("\n", ">", 2, remote_conn) output = output + cnos.enterEnableModeForDevice(enablePassword, 3, remote_conn) # Make terminal length = 0 output = output + cnos.waitForDeviceResponse("terminal length 0\n", "#", 2, remote_conn) # cnos.debugOutput(cliCommand) # Send the CLi command output = output + cnos.waitForDeviceResponse(cliCommand, "[n]", 2, remote_conn) output = output + cnos.waitForDeviceResponse("y" + "\n", "#", 2, remote_conn) # Save it into the file file = open(outputfile, "a") file.write(output) file.close() errorMsg = cnos.checkOutputForError(output) if (errorMsg is None): module.exit_json( changed=True, msg="Switch Startup Config is Reset to factory settings ") else: module.fail_json(msg=errorMsg)
def main(): module = AnsibleModule( argument_spec=dict( state=dict(default="present", choices=["present", "latest", "absent"], required=False), name=dict(aliases=["pkg"], required=True, type='list', elements='str'), cached=dict(default=False, type='bool'), ignore_osver=dict(default=False, required=False, type='bool'), annotation=dict(default="", required=False), pkgsite=dict(default="", required=False), rootdir=dict(default="", required=False, type='path'), chroot=dict(default="", required=False, type='path'), jail=dict(default="", required=False, type='str'), autoremove=dict(default=False, type='bool')), supports_check_mode=True, mutually_exclusive=[["rootdir", "chroot", "jail"]]) pkgng_path = module.get_bin_path('pkg', True) p = module.params pkgs = p["name"] changed = False msgs = [] stdout = "" stderr = "" dir_arg = "" if p["rootdir"] != "": old_pkgng = pkgng_older_than(module, pkgng_path, [1, 5, 0]) if old_pkgng: module.fail_json(msg="To use option 'rootdir' pkg version must be 1.5 or greater") else: dir_arg = "--rootdir %s" % (p["rootdir"]) if p["ignore_osver"]: old_pkgng = pkgng_older_than(module, pkgng_path, [1, 11, 0]) if old_pkgng: module.fail_json(msg="To use option 'ignore_osver' pkg version must be 1.11 or greater") if p["chroot"] != "": dir_arg = '--chroot %s' % (p["chroot"]) if p["jail"] != "": dir_arg = '--jail %s' % (p["jail"]) if pkgs == ['*'] and p["state"] == 'latest': # Operate on all installed packages. Only state: latest makes sense here. _changed, _msg, _stdout, _stderr = upgrade_packages(module, pkgng_path, dir_arg) changed = changed or _changed stdout += _stdout stderr += _stderr msgs.append(_msg) # Operate on named packages named_packages = [pkg for pkg in pkgs if pkg != '*'] if p["state"] in ("present", "latest") and named_packages: _changed, _msg, _out, _err = install_packages(module, pkgng_path, named_packages, p["cached"], p["pkgsite"], dir_arg, p["state"], p["ignore_osver"]) stdout += _out stderr += _err changed = changed or _changed msgs.append(_msg) elif p["state"] == "absent" and named_packages: _changed, _msg, _out, _err = remove_packages(module, pkgng_path, named_packages, dir_arg) stdout += _out stderr += _err changed = changed or _changed msgs.append(_msg) if p["autoremove"]: _changed, _msg, _stdout, _stderr = autoremove_packages(module, pkgng_path, dir_arg) changed = changed or _changed stdout += _stdout stderr += _stderr msgs.append(_msg) if p["annotation"]: _changed, _msg = annotate_packages(module, pkgng_path, pkgs, p["annotation"], dir_arg) changed = changed or _changed msgs.append(_msg) module.exit_json(changed=changed, msg=", ".join(msgs), stdout=stdout, stderr=stderr)
class NetAppCDOTVolume(object): def __init__(self): self._size_unit_map = dict( bytes=1, b=1, kb=1024, mb=1024 ** 2, gb=1024 ** 3, tb=1024 ** 4, pb=1024 ** 5, eb=1024 ** 6, zb=1024 ** 7, yb=1024 ** 8 ) self.argument_spec = netapp_utils.ontap_sf_host_argument_spec() self.argument_spec.update(dict( state=dict(required=True, choices=['present', 'absent']), name=dict(required=True, type='str'), is_infinite=dict(required=False, type='bool', default=False, aliases=['infinite']), is_online=dict(required=False, type='bool', default=True, aliases=['online']), size=dict(type='int'), size_unit=dict(default='gb', choices=['bytes', 'b', 'kb', 'mb', 'gb', 'tb', 'pb', 'eb', 'zb', 'yb'], type='str'), aggregate_name=dict(type='str'), vserver=dict(required=True, type='str', default=None), )) self.module = AnsibleModule( argument_spec=self.argument_spec, required_if=[ ('state', 'present', ['aggregate_name', 'size']) ], supports_check_mode=True ) p = self.module.params # set up state variables self.state = p['state'] self.name = p['name'] self.is_infinite = p['is_infinite'] self.is_online = p['is_online'] self.size_unit = p['size_unit'] self.vserver = p['vserver'] if p['size'] is not None: self.size = p['size'] * self._size_unit_map[self.size_unit] else: self.size = None self.aggregate_name = p['aggregate_name'] if HAS_NETAPP_LIB is False: self.module.fail_json(msg="the python NetApp-Lib module is required") else: self.server = netapp_utils.setup_ontap_zapi(module=self.module, vserver=self.vserver) def get_volume(self): """ Return details about the volume :param: name : Name of the volume :return: Details about the volume. None if not found. :rtype: dict """ volume_info = netapp_utils.zapi.NaElement('volume-get-iter') volume_attributes = netapp_utils.zapi.NaElement('volume-attributes') volume_id_attributes = netapp_utils.zapi.NaElement('volume-id-attributes') volume_id_attributes.add_new_child('name', self.name) volume_attributes.add_child_elem(volume_id_attributes) query = netapp_utils.zapi.NaElement('query') query.add_child_elem(volume_attributes) volume_info.add_child_elem(query) result = self.server.invoke_successfully(volume_info, True) return_value = None if result.get_child_by_name('num-records') and \ int(result.get_child_content('num-records')) >= 1: volume_attributes = result.get_child_by_name( 'attributes-list').get_child_by_name( 'volume-attributes') # Get volume's current size volume_space_attributes = volume_attributes.get_child_by_name( 'volume-space-attributes') current_size = volume_space_attributes.get_child_content('size') # Get volume's state (online/offline) volume_state_attributes = volume_attributes.get_child_by_name( 'volume-state-attributes') current_state = volume_state_attributes.get_child_content('state') is_online = None if current_state == "online": is_online = True elif current_state == "offline": is_online = False return_value = { 'name': self.name, 'size': current_size, 'is_online': is_online, } return return_value def create_volume(self): volume_create = netapp_utils.zapi.NaElement.create_node_with_children( 'volume-create', **{'volume': self.name, 'containing-aggr-name': self.aggregate_name, 'size': str(self.size)}) try: self.server.invoke_successfully(volume_create, enable_tunneling=True) except netapp_utils.zapi.NaApiError as e: self.module.fail_json(msg='Error provisioning volume %s of size %s: %s' % (self.name, self.size, to_native(e)), exception=traceback.format_exc()) def delete_volume(self): if self.is_infinite: volume_delete = netapp_utils.zapi.NaElement.create_node_with_children( 'volume-destroy-async', **{'volume-name': self.name}) else: volume_delete = netapp_utils.zapi.NaElement.create_node_with_children( 'volume-destroy', **{'name': self.name, 'unmount-and-offline': 'true'}) try: self.server.invoke_successfully(volume_delete, enable_tunneling=True) except netapp_utils.zapi.NaApiError as e: self.module.fail_json(msg='Error deleting volume %s: %s' % (self.name, to_native(e)), exception=traceback.format_exc()) def rename_volume(self): """ Rename the volume. Note: 'is_infinite' needs to be set to True in order to rename an Infinite Volume. """ if self.is_infinite: volume_rename = netapp_utils.zapi.NaElement.create_node_with_children( 'volume-rename-async', **{'volume-name': self.name, 'new-volume-name': str( self.name)}) else: volume_rename = netapp_utils.zapi.NaElement.create_node_with_children( 'volume-rename', **{'volume': self.name, 'new-volume-name': str( self.name)}) try: self.server.invoke_successfully(volume_rename, enable_tunneling=True) except netapp_utils.zapi.NaApiError as e: self.module.fail_json(msg='Error renaming volume %s: %s' % (self.name, to_native(e)), exception=traceback.format_exc()) def resize_volume(self): """ Re-size the volume. Note: 'is_infinite' needs to be set to True in order to rename an Infinite Volume. """ if self.is_infinite: volume_resize = netapp_utils.zapi.NaElement.create_node_with_children( 'volume-size-async', **{'volume-name': self.name, 'new-size': str( self.size)}) else: volume_resize = netapp_utils.zapi.NaElement.create_node_with_children( 'volume-size', **{'volume': self.name, 'new-size': str( self.size)}) try: self.server.invoke_successfully(volume_resize, enable_tunneling=True) except netapp_utils.zapi.NaApiError as e: self.module.fail_json(msg='Error re-sizing volume %s: %s' % (self.name, to_native(e)), exception=traceback.format_exc()) def change_volume_state(self): """ Change volume's state (offline/online). Note: 'is_infinite' needs to be set to True in order to change the state of an Infinite Volume. """ state_requested = None if self.is_online: # Requested state is 'online'. state_requested = "online" if self.is_infinite: volume_change_state = netapp_utils.zapi.NaElement.create_node_with_children( 'volume-online-async', **{'volume-name': self.name}) else: volume_change_state = netapp_utils.zapi.NaElement.create_node_with_children( 'volume-online', **{'name': self.name}) else: # Requested state is 'offline'. state_requested = "offline" if self.is_infinite: volume_change_state = netapp_utils.zapi.NaElement.create_node_with_children( 'volume-offline-async', **{'volume-name': self.name}) else: volume_change_state = netapp_utils.zapi.NaElement.create_node_with_children( 'volume-offline', **{'name': self.name}) try: self.server.invoke_successfully(volume_change_state, enable_tunneling=True) except netapp_utils.zapi.NaApiError as e: self.module.fail_json(msg='Error changing the state of volume %s to %s: %s' % (self.name, state_requested, to_native(e)), exception=traceback.format_exc()) def apply(self): changed = False volume_exists = False rename_volume = False resize_volume = False volume_detail = self.get_volume() if volume_detail: volume_exists = True if self.state == 'absent': changed = True elif self.state == 'present': if str(volume_detail['size']) != str(self.size): resize_volume = True changed = True if (volume_detail['is_online'] is not None) and (volume_detail['is_online'] != self.is_online): changed = True if self.is_online is False: # Volume is online, but requested state is offline pass else: # Volume is offline but requested state is online pass else: if self.state == 'present': changed = True if changed: if self.module.check_mode: pass else: if self.state == 'present': if not volume_exists: self.create_volume() else: if resize_volume: self.resize_volume() if volume_detail['is_online'] is not \ None and volume_detail['is_online'] != \ self.is_online: self.change_volume_state() # Ensure re-naming is the last change made. if rename_volume: self.rename_volume() elif self.state == 'absent': self.delete_volume() self.module.exit_json(changed=changed)
def main(): jrpc_urls = [ '/cli/global/system/log/settings/rolling-local' ] perobject_jrpc_urls = [ '/cli/global/system/log/settings/rolling-local/{rolling-local}' ] url_params = [] module_primary_key = None module_arg_spec = { 'enable_log': { 'type': 'bool', 'required': False, 'default': False }, 'proposed_method': { 'type': 'str', 'required': False, 'choices': [ 'set', 'update', 'add' ] }, 'bypass_validation': { 'type': 'bool', 'required': False, 'default': False }, 'workspace_locking_adom': { 'type': 'str', 'required': False }, 'workspace_locking_timeout': { 'type': 'int', 'required': False, 'default': 300 }, 'rc_succeeded': { 'required': False, 'type': 'list' }, 'rc_failed': { 'required': False, 'type': 'list' }, 'system_log_settings_rollinglocal': { 'required': False, 'type': 'dict', 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'options': { 'days': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'list', 'choices': [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ] }, 'del-files': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'choices': [ 'disable', 'enable' ], 'type': 'str' }, 'directory': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'str' }, 'file-size': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'int' }, 'gzip-format': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'choices': [ 'disable', 'enable' ], 'type': 'str' }, 'hour': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'int' }, 'ip': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'str' }, 'ip2': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'str' }, 'ip3': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'str' }, 'log-format': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'choices': [ 'native', 'text', 'csv' ], 'type': 'str' }, 'min': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'int' }, 'password': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'str' }, 'password2': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'str' }, 'password3': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'str' }, 'server-type': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'choices': [ 'ftp', 'sftp', 'scp' ], 'type': 'str' }, 'upload': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'choices': [ 'disable', 'enable' ], 'type': 'str' }, 'upload-hour': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'int' }, 'upload-mode': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'choices': [ 'backup', 'mirror' ], 'type': 'str' }, 'upload-trigger': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'choices': [ 'on-roll', 'on-schedule' ], 'type': 'str' }, 'username': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'str' }, 'username2': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'str' }, 'username3': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'str' }, 'when': { 'required': False, 'revision': { '6.0.0': True, '6.2.1': True, '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'choices': [ 'none', 'daily', 'weekly' ], 'type': 'str' }, 'port': { 'required': False, 'revision': { '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'int' }, 'port2': { 'required': False, 'revision': { '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'int' }, 'port3': { 'required': False, 'revision': { '6.2.3': True, '6.2.5': True, '6.4.0': True, '6.4.2': True, '6.4.5': True, '7.0.0': True }, 'type': 'int' } } } } params_validation_blob = [] check_galaxy_version(module_arg_spec) module = AnsibleModule(argument_spec=check_parameter_bypass(module_arg_spec, 'system_log_settings_rollinglocal'), supports_check_mode=False) fmgr = None if module._socket_path: connection = Connection(module._socket_path) connection.set_option('enable_log', module.params['enable_log'] if 'enable_log' in module.params else False) fmgr = NAPIManager(jrpc_urls, perobject_jrpc_urls, module_primary_key, url_params, module, connection, top_level_schema_name='data') fmgr.validate_parameters(params_validation_blob) fmgr.process_partial_curd(argument_specs=module_arg_spec) else: module.fail_json(msg='MUST RUN IN HTTPAPI MODE') module.exit_json(meta=module.params)
def main(): module = AnsibleModule( argument_spec=dict( state=dict(type='str', default='present', choices=['present', 'absent']), name=dict(type='str', required=True), sysname=dict(type='str', required=True), url=dict(type='str', required=True), user=dict(type='str', required=True), password=dict(type='str', required=True, aliases=['pwd'], no_log=True), validate_certs=dict(type='bool', default=True), ) ) state = module.params['state'] channelname = module.params['name'] systname = module.params['sysname'] saturl = module.params['url'] user = module.params['user'] password = module.params['password'] validate_certs = module.params['validate_certs'] ssl_context = None if not validate_certs: try: # Python 2.7.9 and newer ssl_context = ssl.create_unverified_context() except AttributeError: # Legacy Python that doesn't verify HTTPS certificates by default ssl._create_default_context = ssl._create_unverified_context else: # Python 2.7.8 and older ssl._create_default_https_context = ssl._create_unverified_https_context # initialize connection if ssl_context: client = xmlrpc_client.ServerProxy(saturl, context=ssl_context) else: client = xmlrpc_client.Server(saturl) try: session = client.auth.login(user, password) except Exception as e: module.fail_json(msg="Unable to establish session with Satellite server: %s " % to_text(e)) if not session: module.fail_json(msg="Failed to establish session with Satellite server.") # get systemid try: sys_id = get_systemid(client, session, systname) except Exception as e: module.fail_json(msg="Unable to get system id: %s " % to_text(e)) if not sys_id: module.fail_json(msg="Failed to get system id.") # get channels for system try: chans = base_channels(client, session, sys_id) except Exception as e: module.fail_json(msg="Unable to get channel information: %s " % to_text(e)) try: if state == 'present': if channelname in chans: module.exit_json(changed=False, msg="Channel %s already exists" % channelname) else: subscribe_channels(channelname, client, session, systname, sys_id) module.exit_json(changed=True, msg="Channel %s added" % channelname) if state == 'absent': if channelname not in chans: module.exit_json(changed=False, msg="Not subscribed to channel %s." % channelname) else: unsubscribe_channels(channelname, client, session, systname, sys_id) module.exit_json(changed=True, msg="Channel %s removed" % channelname) except Exception as e: module.fail_json(msg='Unable to %s channel (%s): %s' % ('add' if state == 'present' else 'remove', channelname, to_text(e))) finally: client.auth.logout(session)
def main(): module = AnsibleModule(argument_spec=dict( server_url=dict(type='str', required=True, aliases=['url']), login_user=dict(type='str', required=True), login_password=dict(type='str', required=True, no_log=True), host_name=dict(type='str', default='', required=False), host_ip=dict(type='list', default=[], required=False), http_login_user=dict(type='str', required=False, default=None), http_login_password=dict(type='str', required=False, default=None, no_log=True), validate_certs=dict(type='bool', required=False, default=True), timeout=dict(type='int', default=10), exact_match=dict(type='bool', required=False, default=False), remove_duplicate=dict(type='bool', required=False, default=True), host_inventory=dict(type='list', default=[], required=False)), supports_check_mode=True) if module._name == 'zabbix_host_facts': module.deprecate( "The 'zabbix_host_facts' module has been renamed to 'zabbix_host_info'", version='2.13') if not HAS_ZABBIX_API: module.fail_json(msg=missing_required_lib( 'zabbix-api', url='https://pypi.org/project/zabbix-api/'), exception=ZBX_IMP_ERR) server_url = module.params['server_url'] login_user = module.params['login_user'] login_password = module.params['login_password'] http_login_user = module.params['http_login_user'] http_login_password = module.params['http_login_password'] validate_certs = module.params['validate_certs'] host_name = module.params['host_name'] host_ips = module.params['host_ip'] timeout = module.params['timeout'] exact_match = module.params['exact_match'] is_remove_duplicate = module.params['remove_duplicate'] host_inventory = module.params['host_inventory'] if not host_inventory: host_inventory = 'extend' zbx = None # login to zabbix try: zbx = ZabbixAPI(server_url, timeout=timeout, user=http_login_user, passwd=http_login_password, validate_certs=validate_certs) zbx.login(login_user, login_password) atexit.register(zbx.logout) except Exception as e: module.fail_json(msg="Failed to connect to Zabbix server: %s" % e) host = Host(module, zbx) if host_name: hosts = host.get_hosts_by_host_name(host_name, exact_match, host_inventory) if is_remove_duplicate: hosts = host.delete_duplicate_hosts(hosts) extended_hosts = [] for zabbix_host in hosts: zabbix_host['hostinterfaces'] = host._zapi.hostinterface.get({ 'output': 'extend', 'hostids': zabbix_host['hostid'] }) extended_hosts.append(zabbix_host) module.exit_json(ok=True, hosts=extended_hosts) elif host_ips: extended_hosts = host.get_hosts_by_ip(host_ips, host_inventory) if is_remove_duplicate: hosts = host.delete_duplicate_hosts(extended_hosts) module.exit_json(ok=True, hosts=extended_hosts) else: module.exit_json(ok=False, hosts=[], result="No Host present")