Is there a way to have global macros?

By global macros I mean macros that are loaded somehow and are then available in every tasks in a playbook.

For instance, instead of having:

`

`

  • set_fact: var1=“{% from ‘macros.j2’ import macro1 %}{{ macro1(‘arg’)}}”

`

  • set_fact: var2=“{% from ‘macros.j2’ import macro2 %}{{ macro2(‘arg’)}}”

`

`

`

I would like to have sth like:

`

  • load_macros: ‘macros.j2’
    - set_fact: var1="{{ macro1('arg') }}"
    - set_fact: var2="{{ macro2('arg') }}"
    `

Could I create a plugin similar to the vars or filter plugins so that these macros become available either as true macros or in another form? My problem is that I dislike having to prepend the import statement before every macro.

There is not. This is something we have looked into, and since there is no way to do this in jinja2 itself, the implementation for achieving this in other ways was overtly complicated.

Instead of using macros, investigate creating custom jinja2 filters or custom lookup plugins.