Functions In Ansible

Functions In Ansible

Functions in Ansible

Hello Everyone

Welcome to CloudAffaire and this is Debjeet.

In the last blog post, we have discussed statements in Ansible.

https://cloudaffaire.com/statements-in-ansible/

In this blog post, we will discuss statements in Ansible.

What is a function?

A function is a unit of code that is often defined by its role within a greater code structure. Specifically, a function contains a unit of code that works on various inputs, many of which are variables, and produces concrete results involving changes to variable values or actual operations based on the inputs.

In Ansible functions are called filters and are used for transforming data inside a template expression. Ansible supports all filters provided by Jinja2 and also ships its own filters. For the rest of the blog post, we will refer function as filters.

Note: Templating happens on the Ansible controller, not on the task’s target host, so filters also execute on the controller as they manipulate local data.

Next, we are going to explain each filter types with a demo.

Filters for string:

  • capitalize(s): Capitalize a value. The first character will be uppercase, all others lowercase
  • format(value, *args, **kwargs): Apply python string formatting on an object
  • indent(s, width=4, first=False, blank=False, indentfirst=None): Return indented lines, The first line and blank lines are not indented
  • join(value, d=”, attribute=None): Return a string which is the concatenation of the strings in the sequence.
  • list(value): Convert the value into a list. If it was a string the returned list will be a list of characters.
  • lower(s): Convert a value to lowercase.
  • replace(s, old, new, count=None): Return a copy of the value with all occurrences of a substring replaced with a new one.
  • reverse(value): Reverse the object or return an iterator that iterates over it the other way round.
  • string(object): Make a string unicode if it isn’t already.
  • trim(value): Strip leading and trailing whitespace.
  • truncate(s, length=255, killwords=False, end=’…’, leeway=None): Return a truncated copy of the string.
  • upper(s): Convert a value to uppercase.
  • wordcount(s): Count the words in that string.
  • wordwrap(s, width=79, break_long_words=True, wrapstring=None): Return a copy of the wrapped string after 79 characters.
  • comment(style): allows to decorate the text with a chosen comment style.

Filters for number:

  • abs(x, /): Return the absolute value of the argument.
  • float(value, default=0.0): Convert the value into a floating point number.
  • int(value, default=0, base=10): Convert the value into an integer.
  • round(value, precision=0, method=’common’): Round the number to a given precision.
  • range([start, ]stop[, step]): Return a list containing an arithmetic progression of integers.
  • log(base): Get the logarithm (default is e):
  • pow(power): Get to the power
  • root(n): Get square root of n

Filters for list:

  • min(value, case_sensitive=False, attribute=None): Return the smallest item from the sequence.
  • max(value, case_sensitive=False, attribute=None): Return the largest item from the sequence.
  • first(seq): Return the first item of a sequence.
  • last(seq): Return the last item of a sequence.
  • length(obj, /): Return the number of items in a container.
  • random(seq): Return a random item from the sequence.
  • shuffle(): randomize an existing list, giving a different order every invocation
  • reject(*args, **kwargs): Filters a sequence of objects by applying a test to each object, and rejecting the objects with the test succeeding.
  • reverse(value): Reverse the object or return an iterator that iterates over it the other way round.
  • select(*args, **kwargs): Filters a sequence of objects by applying a test to each object, and only selecting the objects with the test succeeding.
  • sort(value, reverse=False, case_sensitive=False, attribute=None): Sort an iterable.
  • sum(iterable, attribute=None, start=0): Returns the sum of a sequence of numbers plus the value of parameter ‘start’ (which defaults to 0).
  • unique(value, case_sensitive=False, attribute=None): Returns a list of unique items from the the given iterable.
  • union: To get a union of two lists
  • intersect: To get the intersection of 2 lists (unique list of all items in both)
  • difference: To get the difference of 2 lists (items in 1 that don’t exist in 2)
  • symmetric_difference: to get the symmetric difference of 2 lists (items exclusive to each list)

Filters for variables:

  • mandatory: make variable assignment mandatory
  • default: assign a default value to a variable if not set

Filters for IP address:

  • ipaddr: To test if a string is a valid IP address
  • ipv4: To test if a string is a valid IPv4 address
  • ipv6: To test if a string is a valid IPv6 address

Filters for hashing:

  • hash: To get the hash of a string
  • checksum: To get a string checksum
  • password_hash: To get a password hash with a specific salt

Filters for file path:

  • basename: To get the last name of a file path, like ‘foo.txt’ out of ‘/etc/asdf/foo.txt’
  • win_basename: To get the last name of a windows style file path
  • win_splitdrive: To separate the windows drive letter from the rest of a file path
  • dirname: To get the directory from a path
  • win_dirname: To get the directory from a windows path
  • expanduser: To expand a path containing a tilde (~) character
  • realpath: To get the real path of a link
  • relpath: To get the relative path of a link
  • splitext: To get the root and extension of a path or filename

Filters for time:

  • to_datetime(string, format=”%Y-%m-%d %H:%M:%S”): To get date object from string
  • strftime(string_format, second=None): To format a date using a string

Filters for regular expressions:

  • regex_replace(value=”, pattern=”, replacement=”, ignorecase=False): To replace text in a string with regex,
  • regex_findall(value, regex, multiline=False, ignorecase=False): To search for all occurrences of regex matches
  • regex_search(value, regex, *args, **kwargs): To search a string with a regex
  • regex_escape(string, re_type=’python’): To escape special characters within a standard python regex

Filters For Formatting Json Yaml:

  • to_json(a, *args, **kw): convert to json
  • to_nice_json(a, indent=4, sort_keys=True, *args, **kw): convert to human redable json
  • to_yaml(a, *args, **kw): convert to yaml
  • to_nice_yaml(a, indent=4, *args, **kw): convert to human redable yaml

Hope you have enjoyed this article. We have tried to cover as many filters as possible. But still, if few are left, you can reference below documents

https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html

https://jinja.palletsprojects.com/en/2.10.x/templates/#builtin-filters

In the next blog post, we will discuss tests in Ansible.

To get more details on Ansible, please refer below Ansible documentation.

https://docs.ansible.com/

Leave a Reply

Close Menu