I'm working on several Ansible playbooks to spin up a new server instance. There are approximately 15 different playbooks I need to run in a specific order to successfully spin up a server.

My initial thought was to write a shell script that executes ansible-playbook playbook_name.yml and duplicate it one entry for each playbook I need to run.

Is there a smarter/better way to do this using a master playbook and if so what would it look like (examples are appreciated).

I could write one monolithic playbook that does it all but there are some plays that run as root first then as a sudo user later.

  • 2
    use include in your main playbook docs.ansible.com/ansible/playbooks_roles.html – c4f4t0r Jan 21 '16 at 20:13
  • 1
    To handle the case of running as root then as a sudo user, you can use the block feature - put the become: part at end of each block. You might need to create a new play to switch connection user from root to sudo user though. – RichVel Oct 3 '16 at 6:48

Build many sub-playbooks and aggregate them via include statements.

- include: playbook-one.yml
- include: playbook-two.yml

If your playbooks must run in order and if all of them are mandatory, build a main playbook and include files with tasks. A playbook should always be a closed process.

  • 3
    could you elaborate on the last part of your answer? what do you mean by "A playbook should always be a closed process." ? – Mike Vella Dec 1 '16 at 13:31
  • 1
    Is there a way to specify all playbooks using regular expression? For Example: - include : books/*.yml – blueskin Jan 20 '17 at 21:04
  • 10
    Looks like include is deprecated. docs.ansible.com/ansible/latest/playbooks_reuse.html I think import_playbook: foo is the right way to go, but I'm not super experienced. – Andrew Sep 12 '17 at 18:48
  • @MikeVella "A playbook should always be a closed process" essentially means that each playbook should be unto itself and should be independently complete. Nothing in playbook-a should be reliant or necessary from playbook-b. Keep it all as together as possible. – jnovack Aug 10 '20 at 20:32

For newer versions of Ansible, you can build many sub-playbooks and aggregate them via import_playbook statements:

- import_playbook: A-systemd-networkd.yml
- import_playbook: B-fail2ban-ssh.yml
- import_playbook: C-enable-watchdog.yml
  • By any chance, do you know how to continue with B if A fails? A way other than setting ignore_errors: yes for every task in A ? – Tag Wint Dec 28 '20 at 20:31

From: https://docs.ansible.com/ansible/latest/collections/ansible/builtin/import_playbook_module.html

- hosts: localhost
    - debug:
        msg: play1

- name: Include a play after another play
  import_playbook: otherplays.yaml

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.