ansible

Dynamically add Plays in Ansible


I have a control Playbook that fetches group data from an API during runtime. Based on these groups, I want to dynamically add Plays to the run (with differing Hosts and Vars).

From my understanding, this is what the "include" module was for. However, the doc says that it is deprecated. So now I wonder: What is a future-proof way to dynamically add Plays on runtime?

"include_tasks" won't do the trick since the included Tasks will belong to the same Play and thus will use the same Hosts.


Solution

  • It is not possible to include a playbook. There is only the import available. See ansible.builtin.import_playbook.

    It's not possible to import anything dynamically. An import object (task, role, playbook) must be imported before the excution starts. See Re-using Ansible artifacts.

    Ansible Runner can be used to run playbooks dynamically.


    Q: "The Playbooks do exist before runtime."

    A: A playbook must exist before runtime.

    Q: "The controlling playbook has to decide which one to include at runtime."

    A: Still the same, It is not possible to include a playbook. There is only the import available. The 'controlling' (top level) playbook does not controll anything but an optionall when condition. For example,

    - name: top level play
      hosts: all
    
    - name: import foo.yml
      ansible.builtin.import_playbook: foo.yml
      when: foo_enable | d(false) | bool
    
      ...
    

    Quoting Synopsis:

    • Includes a file with a list of plays to be executed.
    • Files with a list of plays can only be included at the top level.
    • You cannot use this action inside a play.

    The wording of the official documentation is misleading. There is no include.

    Q: "This is possible with the include module."

    A: No. It is not possible with the include module. A play must be imported at the top level. You cannot use this action inside a play.


    Summary:

    • There is import_playbook only. No include.
    • A play must be imported at the top level.
    • The import_playbook isn't a task. It is a simple import with optional condition.