Table of contents
1.
Introduction😃
2.
Ansible Playbook📚
3.
Distribution Facts in Ansible Playbook📑
4.
Importing Handlers in Ansible🙌
5.
Jinja Undefined Values in Ansible♾️
6.
Ansible Module Optional Conversion to String🧵
7.
Command Line Fact in Ansible💻
8.
Bare Variables in Ansible Conditionals🔠
8.1.
Updating Playbook in Ansible▶️
8.2.
Nested Variables in Ansible🧭
9.
Gathering Facts in Ansible🗒️
10.
Discovery of Python Interpreter🌍
10.1.
Default Retry File Creation in Ansible📂
11.
Command Line in Ansible😄
12.
Deprecating in Ansible 🌝
13.
Plugins in Ansible 🔌
14.
Porting Custom Scripts in Ansible🛃
14.1.
Display Class in Porting Custom Scripts🏛️
14.2.
Networking in Porting Custom Scripts🌍
15.
Frequently Asked Questions❔
15.1.
When should you put playbooks and roles to the test?
15.2.
What exactly are Ansible Modules?
15.3.
When should playbooks and roles be tested?
16.
Conclusion📌
Last Updated: Mar 27, 2024
Medium

Ansible 2.8 Porting Guide

Author Ayush Mishra
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction😃

Ansible is written in Python. It is a piece of software. It is useful when deploying any application over SSH with no downtime. This tool allows users to manage and configure software applications quickly.

In this blog, we will discuss Ansible 2.8 Porting Guide in detail.

Ansible 2.8 Porting Guide

Ansible Playbook📚

Playbooks are files that contain Ansible code. Playbooks are written in the YAML language. YAML is an abbreviation for Yet Another Markup Language. Playbooks are one of Ansible's core features that tell it what to do. They function similarly to a to-do list for Ansible, containing a list of tasks.

Distribution Facts in Ansible Playbook📑

In the Ansible 2.8 Porting Guide, the data returned for the ansible_distribution_* fact group may have changed slightly from Ansible 2.7. 

Ansible 2.8 makes use of a new backend library for distribution data: nir0s/distro.

This library is compatible with Python-3.8 and fixes numerous bugs, including the correction of release and version names. 

Importing Handlers in Ansible🙌

In the Ansible 2.8 Porting Guide, import_tasks or a static include specified in handlers cannot be notified by a task. The main goal of a static import is to act as a pre-processor, replacing the import with the functions defined in the imported file.

A task can alert any of the named tasks using import. It can tell the task's name but not the import's name. Use include_tasks or listen to achieve the results of notifying a single name but running multiple handlers.

Jinja Undefined Values in Ansible♾️

jinja undefined value

In the Ansible 2.8 Porting Guide, attempting to access an attribute of an Undefined value will return another Undefined value instead of immediately throwing an error in Jinja. When you do not know if the average values are defined, you can simply use the default with a value in a nested variable. If you are unsure whether the intermediate values are defined, simply use the default with a value in a nested data structure.

In the 2.8 version of Ansible:-

{{ foo.bar.baz | default('DEFAULT') }}

 

In the older version of Ansible:-

{{ ((foo | default({})).bar | default({})).baz | default('DEFAULT') }}

{{ foo.bar.baz if (foo is defined and foo.bar is defined and foo.bar.baz is defined) else 'DEFAULT' }}

Ansible Module Optional Conversion to String🧵

The Ansible 2.8 Porting Guide will issue a warning if a module expects a string but receives a non-string value that is automatically converted to a string.

Suppose a yes or true is converted to the string 'True,' or when version number 1.10 is converted to '1.1', it highlights potential problems. Depending on the context, such conversions can produce unexpected behavior.

This behavior can be changed to an error or ignored by setting the ANSIBLE_STRING _CONVERSION ACTION environment variable.

Command Line Fact in Ansible💻

Command line fact

In the Ansible 2.8 Porting Guide, the return of cmdline facts in the system will be deprecated in favor of proc_cmdline. This modification addresses the particular case in which a Kernel command line parameter contains multiple values with the same key.

Bare Variables in Ansible Conditionals🔠

In ansible 2.7, Top-level variables in and earlier sometimes treated boolean strings as boolean values. This resulted in inconsistent conditional tests based on top-level variables defined as strings.

In Ansible 2.8 Porting Guide, this behavior changes. For example, consider the following two conditions:

tasks:
  - include_tasks: teardown.yml
    when: teardown

  - include_tasks: provision.yml
    when: not teardown

Based on a string variable defined above :

✅ In Ansible 2.7 and earlier, if teardown: 'true,' the two conditions above were evaluated as True and False, respectively.

✅ In Ansible 2.7 and earlier, if teardown: 'false,' both conditions were evaluated as False.

✅ In Ansible 2.8 and later, one can disable bare conditional variables. So when teardown is a non-empty string (including 'true' or 'false'), teardown always evaluates as True; otherwise, teardown always evaluates as False.

Updating Playbook in Ansible▶️

updating playbook

In the Ansible 2.8 Porting Guide, To prepare your playbooks for the new behavior, you must update your conditional statements to accept only boolean values.

You can also re-define your variables as boolean values rather than Strings:
 

vars:
  teardown: 'false'


tasks:
  - include_tasks: teardown.yml
    when: teardown | bool


  - include_tasks: provision.yml
    when: not teardown | bool

Alternatively, you can re-define your variables as boolean values rather than Strings:

vars:
  teardown: false


tasks:
  - include_tasks: teardown.yml
    when: teardown


  - include_tasks: provision.yml
    when: not teardown

 

For dictionaries and lists, use the length filter to determine whether a dictionary or list exists:

- debug:
  when: my_list | length > 0


- debug:
  when: my_dictionary | length > 0

In Ansible, the bool filter should not be used with lists or dictionaries. When you use bool with a list or dict, Ansible will always return False.

Nested Variables in Ansible🧭

In Ansible 2.8 Porting Guide, Nested variables are unaffected by the  conditional_bare_variables setting. Any string value allot to a subkey is automatically respected and is not interpreted as a boolean value.

If complex variable['subkey'] is not empty, then when: complex variable['subkey'] is always True and when: not complex variable['subkey'] is always False.

Gathering Facts in Ansible🗒️

Ansible 2.8 Porting Guide changed the "Gathering Facts" task in a play to obey play tags. Before Ansible 2.8, it ignored play tags and command line tags and always ran in a task.

In Ansible 2.8, supplying —tags nginx skips the implicit "Gathering Facts" task, as the task now inherits the tag webserver instead of every time.

If no play level tags are assigned, the "Gathering Facts" task will be given an always tag, effectively matching previous behavior.

Using an explicit gather facts task in your tasks list, you can achieve results similar to the pre-2.8 behavior.

- name: Configure Webservers
  hosts: webserver
  gather_facts: false
  tags:
    - webserver
  tasks:
    - name: Gathering Facts
      gather_facts:
      tags:
        - always


    - name: Install nginx
      package:
        name: nginx
      tags:
        - nginx

Discovery of Python Interpreter🌍

Discovery of Python Interpreter

In Ansible 2.8 Porting Guide, Ansible looks for the correct Python interpreter path and executable name on each target system, first in a lookup table of default Python interpreters for common distributions, then in an ordered fallback list of possible Python interpreter names/paths.

Ansible notifies you when it uses a Python interpreter found in the fallback list. If you see this alert, the best solution is to explicitly set an ansible python interpreter to the path of the appropriate interpreter for those target systems.

If you installed Python and its dependencies (boto, etc.) to /usr/bin/python as a workaround on distros that use a different default Python interpreter, you have two choices:

➡️ Transfer is existing Python dependencies to the platform/distribution/default version's Python.

➡️ Use auto_legacy. This setting instructs Ansible to look for and use the workaround Python on hosts that have it, while also looking for the correct default Python on newer hosts. But keep in mind that the default will change in four releases.

Default Retry File Creation in Ansible📂

In Ansible 2.8 Porting Guide, retry_files_enabled now defaults to False rather than True. The behavior can be restored to the previous version by editing the default ansible.cfg file and set the value to True.

Command Line in Ansible😄

Command Line in Ansible

In Ansible 2.8 Porting Guide, we will discuss prompting. Ansible will prompt you for a password for elevated privileges using the word BECOME.

ansible-playbook --become --ask-become-pass site.yml
BECOME password:

Deprecating in Ansible 🌝

Setting the async directory as a task/play environment key with ANSIBLE_ASYNC_DIR is deprecated and will be removed in Ansible 2.12. You can get the same result by declaring ansible async dir as a variable, such as:

- name: run task with custom async directory
  command: sleep 5
  async: 10
  vars:
    ansible_async_dir: /tmp/.ansible_async

Plugins in Ansible 🔌

In the following given below steps, we will discuss various plugins:-

👉 If you want to keep macOS's pre-2.8 behavior, you may alternatively explicitly specify the connection type to paramiko.

👉 Async dir in the Powershell shell plugin now defines the async path for the results file, and the default value is now %USERPROFILE%.ansible async. To manage this path right now, set the ansible async dir variable or the async dir value in the Powershell section of the configuration.

👉 In the newly updated list of enabled inventory plugins (INVENTORY_ENABLED), auto now comes before YAML and in. The callback plugins' CallbackBase class no longer has the private _options attribute. Utilize the following code rather than attempting to use self._options if you have a third-party callback plugin that requires access to the command line arguments

from ansible import context
[...]
tags = context.CLIARGS['tags']

 

context.CLIARGS is a read-only dictionary, so standard dictionary retrieval methods like. CLIARGS['tags'] and get('tags') work as expected, but you won't be able to change the CLI arguments.

👉 Rescued tasks are those that fail and then run a rescue segment. Remember that, unlike in Ansible 2.7, rescued tasks are no longer counted as failed. Say was given the osx_say callback plugin's old name. Caching is now supported by inventory plugins through cache plugins.

Porting Custom Scripts in Ansible🛃

In Ansible 2.8 Porting Guide, we will discuss the Display class and networking in Porting Custom Scripts in Ansible.

Display Class in Porting Custom Scripts🏛️

The Display class is now a "singleton," as in Ansible 2.8. Each file should import and instantiate Ansible.utils.display rather than utilizing __main __.display, display all by itself.

OLD Accessing the display object in Ansible 2.7 (and older) required the usage of the following:

try:
    from __main__ import display
except ImportError:
    from Ansible.utils.display import Display
    display = Display()

 

The following new command should be used with Ansible 2.8:

from Ansible.utils.display import Display
display = Display()

Networking in Porting Custom Scripts🌍

Networking in Porting Custom scripts

The deprecated save and force parameters have been removed from the eos_config, ios_config, and nxos_config modules; the save_when parameter now replicates their functionality.

The safi argument is no longer included in the nxos_vrf_af module. The module has not been affected by this argument since Ansible 2.4 when it was declared deprecated.

Frequently Asked Questions❔

Frequently Asked Questions

When should you put playbooks and roles to the test?

Tests in Ansible can be added to either new or existing Playbooks. As a result, the majority of testing jobs provide clean hosting every time. You will need to make very few to no code changes if you use this testing methodology.

What exactly are Ansible Modules?

Ansible modules are discrete code units used from the command line or in a playbook task. They are also known as task plugins or library plugins in Ansible.

Users may also create their modules. These modules can manage services, system resources, files, and packages and execute system commands.

When should playbooks and roles be tested?

Tests in Ansible can be added to either new or existing Playbooks. As a result, most testing jobs provide clean hosting every time. Using this testing methodology, you will need to make very few to no code changes.

Conclusion📌

Congratulations on finishing the blog! We have discussed Ansible 2.8 Porting Guide. Playbooks, plugins, porting custom scripts, and networking.

If you want to read more blogs on Ansible, please visit the following sites, which have been particularly selected for readers like you:

 

Please refer to our guided pathways on Code studio to learn more about DSACompetitive ProgrammingJavaScriptSystem Design, etc. Enroll in our courses, and use the accessible sample exams and questions as a guide. For placement preparations, look at the interview experiences and interview package.

Please do upvote our blogs if you find them helpful and informative!

Happy learning!
 

Thanking you for reading the blog.
Live masterclass