def validate_int(self): for int_key in self._INT_ARGS: key_value = self._task.args.get(int_key, 1) re_raise = False # workaround to pass the raise-missing-from pylint issue try: validation.check_type_int(key_value) if key_value < 0: raise AnsibleError('The value of %s must not be less than 0' % (int_key)) except (TypeError, ValueError): re_raise = True # workaround to pass the raise-missing-from pylint issue if re_raise: raise AnsibleError("The value of argument %s is %s which can't be converted to int" % (int_key, key_value)) return None
def validate_int(self): for int_key in self._INT_ARGS: key_value = self._task.args.get(int_key, 1) try: validation.check_type_int(key_value) if key_value < 0: raise AnsibleError( 'The value of %s must not be less than 0' % (int_key)) except (TypeError, ValueError): raise AnsibleError( "The value of argument %s is %s which can't be converted to int" % (int_key, key_value)) return None
def process_playbook_values(self): ''' Get playbook values and perform input validation ''' argument_spec = dict( vrf=dict(type='str', default='management'), connect_ssh_port=dict(type='int', default=22), file_system=dict(type='str', default='bootflash:'), file_pull=dict(type='bool', default=False), file_pull_timeout=dict(type='int', default=300), file_pull_compact=dict(type='bool', default=False), file_pull_kstack=dict(type='bool', default=False), local_file=dict(type='path'), local_file_directory=dict(type='path'), remote_file=dict(type='path'), remote_scp_server=dict(type='str'), remote_scp_server_user=dict(type='str'), remote_scp_server_password=dict(no_log=True), ) playvals = {} # Process key value pairs from playbook task for key in argument_spec.keys(): playvals[key] = self._task.args.get(key, argument_spec[key].get('default')) if playvals[key] is None: continue option_type = argument_spec[key].get('type', 'str') try: if option_type == 'str': playvals[key] = validation.check_type_str(playvals[key]) elif option_type == 'int': playvals[key] = validation.check_type_int(playvals[key]) elif option_type == 'bool': playvals[key] = validation.check_type_bool(playvals[key]) elif option_type == 'path': playvals[key] = validation.check_type_path(playvals[key]) else: raise AnsibleError('Unrecognized type <{0}> for playbook parameter <{1}>'.format(option_type, key)) except (TypeError, ValueError) as e: raise AnsibleError("argument %s is of type %s and we were unable to convert to %s: %s" % (key, type(playvals[key]), option_type, to_native(e))) # Validate playbook dependencies if playvals['file_pull']: if playvals.get('remote_file') is None: raise AnsibleError('Playbook parameter <remote_file> required when <file_pull> is True') if playvals.get('remote_scp_server') is None: raise AnsibleError('Playbook parameter <remote_scp_server> required when <file_pull> is True') if playvals['remote_scp_server'] or \ playvals['remote_scp_server_user']: if None in (playvals['remote_scp_server'], playvals['remote_scp_server_user']): params = '<remote_scp_server>, <remote_scp_server_user>' raise AnsibleError('Playbook parameters {0} must be set together'.format(params)) return playvals
def ensure_type(value, type_name): if type_name == 'str': return check_type_str(value) if type_name == 'list': return check_type_list(value) if type_name == 'dict': return check_type_dict(value) if type_name == 'bool': return check_type_bool(value) if type_name == 'int': return check_type_int(value) if type_name == 'float': return check_type_float(value) return value
def _process_option_retries(self): '''check if retries option is int or dict and interpret it appropriately''' # this method focuses on validating the option, and setting a valid Retry object construction dict # it intentionally does not build the Session object, which will be done elsewhere retries_opt = self._options.get_option('retries') if retries_opt is None: return # we'll start with a copy of our defaults retries = self._RETRIES_DEFAULT_PARAMS.copy() try: # try int # on int, retry the specified number of times, and use the defaults for everything else # on zero, disable retries retries_int = check_type_int(retries_opt) if retries_int < 0: raise ValueError("Number of retries must be >= 0 (got %i)" % retries_int) elif retries_int == 0: retries = None else: retries['total'] = retries_int except TypeError: try: # try dict # on dict, use the value directly (will be used as the kwargs to initialize the Retry instance) retries = check_type_dict(retries_opt) except TypeError: raise TypeError( "retries option must be interpretable as int or dict. Got: %r" % retries_opt) self._options.set_option('retries', retries)
def _check_type_int(self, value): return check_type_int(value)
def process_playbook_values(self): """ Get playbook values and perform input validation """ argument_spec = dict( vrf=dict(type="str", default="management"), connect_ssh_port=dict(type="int", default=22), file_system=dict(type="str", default="bootflash:"), file_pull=dict(type="bool", default=False), file_pull_timeout=dict(type="int", default=300), file_pull_protocol=dict( type="str", default="scp", choices=["scp", "sftp", "http", "https", "tftp", "ftp"], ), file_pull_compact=dict(type="bool", default=False), file_pull_kstack=dict(type="bool", default=False), local_file=dict(type="path"), local_file_directory=dict(type="path"), remote_file=dict(type="path"), remote_scp_server=dict(type="str"), remote_scp_server_user=dict(type="str"), remote_scp_server_password=dict(no_log=True), ) playvals = {} # Process key value pairs from playbook task for key in argument_spec.keys(): playvals[key] = self._task.args.get( key, argument_spec[key].get("default")) if playvals[key] is None: continue option_type = argument_spec[key].get("type", "str") try: if option_type == "str": playvals[key] = validation.check_type_str(playvals[key]) elif option_type == "int": playvals[key] = validation.check_type_int(playvals[key]) elif option_type == "bool": playvals[key] = validation.check_type_bool(playvals[key]) elif option_type == "path": playvals[key] = validation.check_type_path(playvals[key]) else: raise AnsibleError( "Unrecognized type <{0}> for playbook parameter <{1}>". format(option_type, key)) except (TypeError, ValueError) as e: raise AnsibleError( "argument %s is of type %s and we were unable to convert to %s: %s" % (key, type(playvals[key]), option_type, to_native(e))) if "choices" in argument_spec[key] and playvals[ key] not in argument_spec[key].get("choices"): raise AnsibleError( "argument {0} with value {1} is not valid. Allowed values are {2}" .format( key, playvals[key], ", ".join(argument_spec[key].get("choices")), )) # Validate playbook dependencies if playvals["file_pull"]: if playvals.get("remote_file") is None: raise AnsibleError( "Playbook parameter <remote_file> required when <file_pull> is True" ) if playvals.get("remote_scp_server") is None: raise AnsibleError( "Playbook parameter <remote_scp_server> required when <file_pull> is True" ) if playvals["remote_scp_server"] or playvals["remote_scp_server_user"]: if None in ( playvals["remote_scp_server"], playvals["remote_scp_server_user"], ): params = "<remote_scp_server>, <remote_scp_server_user>" raise AnsibleError( "Playbook parameters {0} must be set together".format( params)) return playvals
def run(self, tmp=None, task_vars=None): ''' handler for template operations ''' if task_vars == None: task_vars = dict() super(ActionModule, self).run(tmp, task_vars) module_args = self._task.args.copy() # assign to local vars category = module_args.get('category', None) url = module_args.get('url', self.DEFAULT_URL) user = module_args.get('user', self.DEFAULT_USER) password = module_args.get('password', self.DEFAULT_PASSWORD) state = module_args.get('state', self.DEFAULT_STATE) retry = module_args.get('retry', self.DEFAULT_RETRY) group = module_args.get('group', None) node = module_args.get('node', None) foreign_id = module_args.get('foreign_id', None) try: retry = check_type_int(retry) except TypeError: raise AnsibleError("'retry' is not an integer") # logical validation if category is None: raise AnsibleError("'category' is an undefined required variable") elif state != 'present' and state != 'absent': raise AnsibleError("'state' is not a valid value") elif retry < 0: raise AnsibleError("'retry' is a non positive integer") #elif group != None and node != None and foreign_id != None: # raise AnsibleError("you have specified more than one type of group, node, or foreign_id") display.debug("{action}: The category is: ".format( action=self._task.action ) + to_text(category)) display.debug("{action}: The state is: ".format( action = self._task.action ) + to_text(state)) _retry = retry while _retry >= 0: module_return = self.get_uri(url=url, user=user, password=password, task_vars=task_vars, tmp=tmp) if module_return.get('status', 200) != 200: _retry -= 1 else: break # Return error if module failed to run if module_return.get('failed', False): raise AnsibleError('Failed to GET from the REST api, the original error: %s' % to_native(module_return.get('msg'))) if module_return.get('failed', False): raise AnsibleError('The GET request returned a non successful status code {status}: {msg}'.format( status=module_return.get('status', None), msg=module_return.get('content', None) )) # setup result var result = dict() json = module_return.get('json', None) if json is None: raise AnsibleError('Error retrieving JSON from URI results') display.debug('{action}: the JSON returned: {json}'.format( action=self._task.action, json=json )) category_exist = self.check_category(category=category, api_request=json) #result['category_exist'] = category_exist if not category_exist and state == 'present': _retry = retry while _retry >= 0: module_return = self.post_uri(url=url, user=user, password=password, category=category, task_vars=task_vars, tmp=tmp) if module_return.get('status', 201) != 201: _retry -= 1 else: break if module_return.get('failed', False): raise AnsibleError('The POST request returned a non successful status code {status}: {msg}'.format( status=module_return.get('status', None), msg=module_return.get('content', None) )) display.debug('{action}: Action has made a change on the system'.format( action=self._task.action )) result['changed'] = True if group != None: pass return dict(result)