Python functions in ansible

Ever wanted to use function from python in ansible, but did not want to create a filter pluging for the function. Starting with ansible-core 2.19 you can do it directly in ansible.

I’ve been working on some experimental ansible plugins in my capable.core219 collection that allows to use some* builtin python functions directly in ansible with help of python lamda functions:

- name: Try this lesson on localhost
  hosts: localhost
  gather_facts: false
  vars:
    summation: "{{ lookup('capable.core219.lambda', 'lambda n: sum(range(n + 1))') }}"
    padded: "{{ 'lambda value: format(value, \"05d\")' | capable.core219.lambda }}"
    ranger: "{{ lookup('capable.core219.lambda', 'lambda stop: range(stop)') }}"
  tasks:
    - name: Use sum and range in lambda
      ansible.builtin.assert:
        that:
          - summation(4) == 10
          - "padded(42) == '00042'"
          - ranger(4) | list == [0, 1, 2, 3]

As you can see summation, padder, ranger behave like functions that you can use dirently in ansible.

If you want to use whatever function you created to map over a list, you can do that with help of apply filter:

- hosts: localhost
  gather_facts: false
  vars:
    adder: "{{ lookup('capable.core219.lambda', 'lambda x: x + 1') }}"
    values:
      - 1
      - 2
      - 3
  tasks:
    - name: Apply filter via map
      ansible.builtin.assert:
        that:
          - "(values | map('capable.core219.apply', adder) | list) == [2, 3, 4]"

Documentation: Collections | Capable Ansible Collections
Collections: Ansible Galaxy

* there is a whitelist of what can be used due to security and other considerations

PS This is continuation to this discussion How to solve ansible challenge from ansible-core maintainer - #2 by nitzmahone