Ansible Reference: Module Utilities

This page documents utilities intended to be helpful when writingAnsible modules in Python.

AnsibleModule

To use this functionality, include from ansible.module_utils.basic import AnsibleModule in your module.

  • class ansible.moduleutils.basic.AnsibleModule(_argument_spec, bypass_checks=False, no_log=False, check_invalid_arguments=None, mutually_exclusive=None, required_together=None, required_one_of=None, add_file_common_args=False, supports_check_mode=False, required_if=None, required_by=None)
  • Common code for quickly building an ansible module in Python(although you can write modules with anything that can return JSON).

See Ansible module development: getting started for a general introductionand Ansible module architecture for more detailed explanation.

  • addpath_info(_kwargs)
  • for results that are files, supplement the info about the filein the return path with stats about the file path.

  • atomicmove(_src, dest, unsafe_writes=False)

  • atomically move src to dest, copying attributes from dest, returns true on successit uses os.rename to ensure this as it is an atomic operation, rest of the function isto work around limitations, corner cases and ensure selinux context is saved if possible

  • backuplocal(_fn)

  • make a date-marked backup of the specified file, return True or False on success or failure

  • boolean(arg)

  • Convert the argument to a boolean

  • digestfrom_file(_filename, algorithm)

  • Return hex digest of local file for a digest_method specified by name, or None if file is not present.

  • exitjson(**kwargs_)

  • return from the module, without error

  • failjson(**kwargs_)

  • return from the module, with an error message

  • getbin_path(_arg, required=False, opt_dirs=None)

  • Find system executable in PATH.

Parameters:

  1. - **arg** The executable to find.
  2. - **required** if executable is not found and required is <code>True</code>, fail_json
  3. - **opt_dirs** optional list of directories to search in addition to <code>PATH</code>Returns:

if found return full path; otherwise return None

  • isexecutable(_path)
  • is the given path executable?

Parameters:path – The path of the file to check.

Limitations:

  1. - Does not account for FSACLs.
  2. - Most times we really want to know Can the current user execute thisfile”. This function does not tell us that, only if any execute bit is set.
  • isspecial_selinux_path(_path)
  • Returns a tuple containing (True, selinux_context) if the given path is on aNFS or other ‘special’ fs mount point, otherwise the return will be (False, None).

  • loadfile_common_arguments(_params)

  • many modules deal with files, this encapsulates commonoptions that the file module accepts such that it is directlyavailable to all modules and they can share code.

  • md5(filename)

  • Return MD5 hex digest of local file using digest_from_file().

    • Do not use this function unless you have no other choice for:
      • Optional backwards compatibility
      • Compatibility with a third party protocolThis function will not work on systems complying with FIPS-140-2.

Most uses of this function can use the module.sha1 function instead.

  • preservedcopy(_src, dest)
  • Copy a file with preserved ownership, permissions and context

  • runcommand(_args, check_rc=False, close_fds=True, executable=None, data=None, binary_data=False, path_prefix=None, cwd=None, use_unsafe_shell=False, prompt_regex=None, environ_update=None, umask=None, encoding='utf-8', errors='surrogate_or_strict', expand_user_and_vars=True, pass_fds=None, before_communicate_callback=None)

  • Execute a command, returns rc, stdout, and stderr.

Parameters:args – is the command to run If args is a list, the command will be run with shell=False. If args is a string and useunsafe_shell=False it will split args to a list and run with shell=False* If args is a string and use_unsafe_shell=True it runs with shell=True.Kw check_rc:Whether to call fail_json in case of non zero RC.Default FalseKw close_fds:See documentation for subprocess.Popen(). Default TrueKw executable:See documentation for subprocess.Popen(). Default NoneKw data:If given, information to write to the stdin of the commandKw binary_data:If False, append a newline to the data. Default FalseKw path_prefix:If given, additional path to find the command in.This adds to the PATH environment variable so helper commands inthe same directory can also be foundKw cwd:If given, working directory to run the command insideKw use_unsafe_shell: See _args parameter. Default FalseKw promptregex: Regex string (not a compiled regex) which can beused to detect prompts in the stdout which would otherwise causethe execution to hang (especially if no input data is specified)Kw environ_update: dictionary to _update os.environ withKw umask:Umask to be used when running the command. Default NoneKw encoding:Since we return native strings, on python3 we need toknow the encoding to use to transform from bytes to text. If youwant to always get bytes back, use encoding=None. The default is“utf-8”. This does not affect transformation of strings given asargs.Kw errors:Since we return native strings, on python3 we need totransform stdout and stderr from bytes to text. If the bytes areundecodable in the encoding specified, then use this errorhandler to deal with them. The default is surrogate_or_strictwhich means that the bytes will be decoded using thesurrogateescape error handler if available (available on allpython3 versions we support) otherwise a UnicodeError tracebackwill be raised. This does not affect transformations of stringsgiven as args.Kw expand_user_and_vars: When use_unsafe_shell=False this argumentdictates whether ~ is expanded in paths and environment variablesare expanded before running the command. When True a string such as$SHELL will be expanded regardless of escaping. When False anduse_unsafe_shell=False no path or variable expansion will be done.Kw pass_fds:When running on python3 this argumentdictates which file descriptors should be passedto an underlying Popen constructor.Kw before_communicate_callback: This function will be calledafter Popen object will be createdbut before communicating to the process.(Popen object will be passed to callback as a first argument)Returns:A 3-tuple of return code (integer), stdout (native string),and stderr (native string). On python2, stdout and stderr are bothbyte strings. On python3, stdout and stderr are text strings convertedaccording to the encoding and errors parameters. If you want bytestrings on python3, use encoding=None to turn decoding to text off.

  • sha1(filename)
  • Return SHA1 hex digest of local file using digest_from_file().

  • sha256(filename)

  • Return SHA-256 hex digest of local file using digest_from_file().

Basic

To use this functionality, include import ansible.module_utils.basic in your module.

  • exception ansible.module_utils.basic.AnsibleFallbackNotFound
  • ansible.moduleutils.basic.env_fallback(args, *kwargs_)
  • Load value from environment
  • ansible.moduleutils.basic.get_all_subclasses(_cls)
  • Deprecated: Use ansible.module_utils.common._utils.get_all_subclasses instead

Returns:Name of the platform the module is running on in a native string

Returns a native string that labels the platform (“Linux”, “Solaris”, etc). Currently, this isthe result of calling platform.system().

  • ansible.moduleutils.basic.heuristic_log_sanitize(_data, no_log_values=None)
  • Remove strings that look like passwords from log messages
  • ansible.moduleutils.basic.load_platform_subclass(_cls, *args, **kwargs)
  • Deprecated: Use ansible.module_utils.common.sys_info.get_platform_subclass instead
  • ansible.moduleutils.basic.remove_values(_value, no_log_strings)
  • Remove strings in no_log_strings from value. If value is a containertype, then remove a lot more