Table of contents
1.
Introduction
2.
AnsibleModule
2.1.
add_path_info(kwargs)
2.2.
atomic_move(src, dest, unsafce_writes=False)
2.3.
backup_local(fn)
2.4.
boolean(arg)
2.5.
exit_json(**kwargs)
2.6.
is_executable(path)
2.7.
is_special_selinux_path(path)
3.
Basic
4.
Argument Spec
4.1.
ArgumentSpecValidator
4.1.1.
validate(parameters, *args, **kwargs)
4.2.
ValidationResult
4.2.1.
errors
4.2.2.
property unsupported_parameters
4.2.3.
property error_messages
4.3.
Validation
4.4.
Errors
5.
Frequently Asked Questions
5.1.
What needs to be included in the module to use AnsibleModule's functionality?
5.2.
What needs to be included in the module to use Basic functionality?
5.3.
What is used inplace of ansible.module_utils.basic.get_all_subclasses(cls)?
6.
Conclusion
Last Updated: Mar 27, 2024
Medium

Ansible-Module Utilities

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Ansible is a simple IT automation engine that is used to automate cloud provisioning, configuration management, application deployment, and many other IT requirements. It has the capability for multi-tier deployment. It models the user's IT infrastructure by describing how all of the systems inter-relate, rather than just managing one system at a time. It is very simple to deploy as it uses no agents and requires no additional custom security infrastructure. 

AnsibleModule

Include "from ansible.module_utils.basic import AnsibleModule" in your module in order to use this functionality.

classansible.module_utils.basic.AnsibleModule(argument_spec, bypass_checks=False, no_log=False, 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)


It's a common code generally used for quickly building an ansible module in python, though the user can write modules with anything till it returns a JSON.

add_path_info(kwargs)

In case the results are files, then supplement the information about the file in the return path along with the stats about the file path.

atomic_move(src, dest, unsafce_writes=False)

This atomically moves the src(source) to the dest(destination), copying attributes from the dest, it returns true on success and uses the os.rename to ensure that this is an atomic operation, besides this, the rest of the function is work around limitations, corner cases and ensure selinux context is saved if possible.

backup_local(fn)

This makes a data-marked backup of the file which is specified, and depending on the success or failure, it returns true or false.

boolean(arg)

It converts the argument to a boolean

exit_json(**kwargs)

It returns from the module without any error

is_executable(path)

Whether the given path is executable or not?

Parameters 

  • path:It defines the path of the file which is to be checked.


Limitations

  • FSACLs are not accounted for by this.
  • Most of the time, we want to know whether the current user can execute this file or not. It cannot tell us this, it can only tell if any execute bit is set.

is_special_selinux_path(path)

It returns a tuple which contains(True, selinux_context) if in case the given path is on an NFS else it will return(False, None).

Basic

We need to include "import ansible.module_utils.basic" in the module if we wish to use this functionality.

ansible.module_utils.basic.get_all_subclasses(cls)


Deprecated: Instead of using this, use ansible.module_utils.common._utils.get_all_subclasses

ansible.module_utils.basic.get_platform()


Deprecated: Instead of using this, use platform.system()

It returns a native string that contains the name of the platform the module is running on.

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


It is used to remove strings that look similar to passwords from the log messages.

Argument Spec

It contains classes as well as functions that are used for validating parameters against an argument spec.

ArgumentSpecValidator

classansible.module_utils.common.arg_spec.ArgumentSpecValidator(argument_spec, mutually_exclusive=None, required_together=None, required_one_of=None, required_if=None, required_by=None)


It's an argument spec validation class. It is used to create argument_spec based validator that is used to validate several parameters using the validate() method.

Parameters

  • argument_spec (dict[str, dict]): it specifies valid parameters as well as their types, it can include nested argument specs too.
  • mutually_exclusive(list{str} or list[list[str]]): it specifies a list of lists of terms that can’t be provided together.
  • required_one_of(list[list[str]]): it specifies a list of lists of terms, out of which one in each list is required.


validate(parameters, *args, **kwargs)

It is used to validate parameters over an argument spec.

There may be no_log values in the error messages in the ValidationResult, and therefore it should be sanitized before logging or displaying with the sanitize_keys(). It returns a ValidationResult that contains validated parameters.

Parameters

  • parameters(dic[str,dict]): it contains parameters to validate over the argument spec.


ValidationResult

classansible.module_utils.common.arg_spec.ValidationResult(parameters)


It is the result of argument spec validation. It is returned by ArgumentSpecValidator.validate(). It is an object which contains validated parameters and errors, if any.

errors

The AnsibleValidationErrorMultiple contains all the AnsibleValidationError objects if any failure occurs during validation.

property unsupported_parameters

It is a set that contains the names of unsupported parameters.

property error_messages

It is a list that contains all the error messages from every exception in errors.

Validation

These are the functions used for validating various parameter types. They are standalone functions.

ansible.module_utils.common.validation.check_missing_parameters(parameters, required_parameters=None)


It is used for checking the required parameters when it's not possible to check via argspec because more information is required from what is given in the argspec.

If in case any required parameters are missing, then it raises TypeError. It either returns an empty list or raises TypeError in case the check fails.

Parameters

  • parameters: it is a dictionary of all the parameters.
  • required_parameters: it is a list of all the parameters which are to be looked for in the given parameters.
ansible.module_utils.common.validation.check_mutually_exclusive(terms, parameters, options_context=None)


It is used for checking mutually exclusive terms over argument parameters.

It accepts either a single list or a list of lists that are a group of terms that need to be mutually exclusive. It either returns an empty list or raises TypeError in case the check fails.

Parameters

  • terms: it is a list of all the mutually exclusive parameters
  • parameters: it is a dictionary of the parameters
  • options_context: it is a list of strings of parent key names if in case the terms are in sub-spec.
ansible.module_utils.common.validation.check_required_by(requirements, parameters, options_context=None)


For every key in the requirements, it checks the corresponding list to see if it exists in the parameters or not. It either accepts a single string or a list of values for each key. It either returns an empty dictionary or raises TypeEror.

Parameters

  • requirements: it is a dictionary of all the requirements.
  • parameters: it is a dictionary of the parameters
  • options_context: it is a list of strings of parent key names if in case the requirements are in sub-spec.
ansible.module_utils.common.validation.check_type_bits(value)


It is used to convert human-readable string bits into bits in an integer. If it is unable to convert the value, it will raise a TypeError.

ansible.module_utils.common.validation.check_type_bytes(value)


It is used to convert a human-readable string value into bytes. If it is unable to convert the value, it will raise a TypeError.

ansible.module_utils.common.validation.check_type_float(value) 


It is used to convert the value to float and return it. If it is unable to convert the value, it will raise a TypeError. It returns a float of the given value.

Parameters

  • value: float, int, str, or bytes to either verify or to convert and return.
ansible.module_utils.common.validation.check_type_int(value)


It checks whether the given value is an integer and returns it if it is, or it will convert the value to an integer and then return it. If it is unable to convert the value, then it will raise a TypeError. It returns an int of the given value.

Parameters

  • value: it accepts a string or int to either convert or verify.

Errors

exceptionansible.module_utils.errors.AnsibleFallbackNotFound


It indicates that there was no fallback validator.

exceptionansible.module_utils.errors.AliasError(message)


It indicates error handling aliases

exceptionansible.module_utils.errors.MutuallyExclusiveError(message)


It indicates that they were supplied with mutually exclusive parameters

exceptionansible.module_utils.errors.RequiredDefaultError(message)


It indicates that a default value has been assigned to a required parameter.

exceptionansible.module_utils.errors.RequiredError(message)


It indicates that a required parameter is missing.

exceptionansible.module_utils.errors.SubParameterTypeError(message)


It indicates that the type for the subparameter is incorrect.

exceptionansible.module_utils.errors.UnsupportedError(message)


It indicates that the parameters which are supplied are unsupported.

Frequently Asked Questions

What needs to be included in the module to use AnsibleModule's functionality?

To use the functionality of AnsibleModule, the user needs to include "from ansible.module_utils.basic import AnsibleModule" in their module.

What needs to be included in the module to use Basic functionality?

To use the functionality, the user needs to include "import ansible.module_utils.basic" in their module.

What is used inplace of ansible.module_utils.basic.get_all_subclasses(cls)?

Inplace of ansible.module_utils.basic.get_all_subclasses(cls), we use ansible.module_utils.common._utils.get_all_subclasses.

Conclusion

In this article, we have extensively discussed Ansible-Module Utilities.

After reading about the Ansible-Module Utilities, are you not feeling excited to read/explore more articles on Development? Don't worry; Coding Ninjas has you covered. To learn about system design strategieshow to start learning full-stack web development and what are top web development languages.

If you wish to enhance your skills in Data Structures and AlgorithmsCompetitive ProgrammingJavaScript, etc., you should check out our Guided path column at Coding Ninjas Studio. We at Coding Ninjas Studio organize many contests in which you can participate. You can also prepare for the contests and test your coding skills by giving the mock test series available. In case you have just started the learning process, and your dream is to crack major tech giants like Amazon, Microsoft, etc., then you should check out the most frequently asked problems and the interview experiences of your seniors that will surely help you in landing a job in your dream company. 

Do upvote if you find the blogs helpful.

Happy Learning!

Thank you image
Live masterclass