W3cubDocs

/Ansible 2.9

Ansible Reference: Module Utilities

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

AnsibleModule

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

class ansible.module_utils.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 introduction and Ansible module architecture for more detailed explanation.

add_path_info(kwargs)

for results that are files, supplement the info about the file in the return path with stats about the file path.

atomic_move(src, dest, unsafe_writes=False)

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

backup_local(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

digest_from_file(filename, algorithm)

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

exit_json(**kwargs)

return from the module, without error

fail_json(**kwargs)

return from the module, with an error message

get_bin_path(arg, required=False, opt_dirs=None)

Find system executable in PATH.

Parameters:
  • arg – The executable to find.
  • required – if executable is not found and required is True, fail_json
  • opt_dirs – optional list of directories to search in addition to PATH
Returns:

if found return full path; otherwise return None

is_executable(path)

is the given path executable?

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

Limitations:

  • Does not account for FSACLs.
  • Most times we really want to know “Can the current user execute this file”. This function does not tell us that, only if any execute bit is set.
is_special_selinux_path(path)

Returns a tuple containing (True, selinux_context) if the given path is on a NFS or other ‘special’ fs mount point, otherwise the return will be (False, None).

load_file_common_arguments(params)

many modules deal with files, this encapsulates common options that the file module accepts such that it is directly available 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:
  1. Optional backwards compatibility
  2. Compatibility with a third party protocol

This function will not work on systems complying with FIPS-140-2.

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

preserved_copy(src, dest)

Copy a file with preserved ownership, permissions and context

run_command(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 use_unsafe_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 False
Kw close_fds: See documentation for subprocess.Popen(). Default True
Kw executable: See documentation for subprocess.Popen(). Default None
Kw data: If given, information to write to the stdin of the command
Kw binary_data: If False, append a newline to the data. Default False
Kw path_prefix: If given, additional path to find the command in. This adds to the PATH environment variable so helper commands in the same directory can also be found
Kw cwd: If given, working directory to run the command inside
Kw use_unsafe_shell:
See args parameter. Default False
Kw prompt_regex:
Regex string (not a compiled regex) which can be used to detect prompts in the stdout which would otherwise cause the execution to hang (especially if no input data is specified)
Kw environ_update:
dictionary to update os.environ with
Kw umask: Umask to be used when running the command. Default None
Kw encoding: Since we return native strings, on python3 we need to know the encoding to use to transform from bytes to text. If you want to always get bytes back, use encoding=None. The default is “utf-8”. This does not affect transformation of strings given as args.
Kw errors: Since we return native strings, on python3 we need to transform stdout and stderr from bytes to text. If the bytes are undecodable in the encoding specified, then use this error handler to deal with them. The default is surrogate_or_strict which means that the bytes will be decoded using the surrogateescape error handler if available (available on all python3 versions we support) otherwise a UnicodeError traceback will be raised. This does not affect transformations of strings given as args.
Kw expand_user_and_vars:
When use_unsafe_shell=False this argument dictates whether ~ is expanded in paths and environment variables are expanded before running the command. When True a string such as $SHELL will be expanded regardless of escaping. When False and use_unsafe_shell=False no path or variable expansion will be done.
Kw pass_fds: When running on Python 3 this argument dictates which file descriptors should be passed to an underlying Popen constructor. On Python 2, this will set close_fds to False.
Kw before_communicate_callback:
This function will be called after Popen object will be created but 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 both byte strings. On python3, stdout and stderr are text strings converted according to the encoding and errors parameters. If you want byte strings 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.module_utils.basic.env_fallback(*args, **kwargs)

Load value from environment

ansible.module_utils.basic.get_all_subclasses(cls)

Deprecated: Use ansible.module_utils.common._utils.get_all_subclasses instead

ansible.module_utils.basic.get_platform()

Deprecated Use platform.system() directly.

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 is the result of calling platform.system().

ansible.module_utils.basic.heuristic_log_sanitize(data, no_log_values=None)

Remove strings that look like passwords from log messages

ansible.module_utils.basic.load_platform_subclass(cls, *args, **kwargs)

Deprecated: Use ansible.module_utils.common.sys_info.get_platform_subclass instead

ansible.module_utils.basic.remove_values(value, no_log_strings)

Remove strings in no_log_strings from value. If value is a container type, then remove a lot more.

Use of deferred_removals exists, rather than a pure recursive solution, because of the potential to hit the maximum recursion depth when dealing with large amounts of data (see issue #24560).

ansible.module_utils.basic.sanitize_keys(obj, no_log_strings, ignore_keys=frozenset())

Sanitize the keys in a container object by removing no_log values from key names.

This is a companion function to the remove_values() function. Similar to that function, we make use of deferred_removals to avoid hitting maximum recursion depth in cases of large data structures.

Parameters:
  • obj – The container object to sanitize. Non-container objects are returned unmodified.
  • no_log_strings – A set of string values we do not want logged.
  • ignore_keys – A set of string values of keys to not sanitize.
Returns:

An object with sanitized keys.

© 2012–2018 Michael DeHaan
© 2018–2019 Red Hat, Inc.
Licensed under the GNU General Public License version 3.
https://docs.ansible.com/ansible/2.9/reference_appendices/module_utils.html