0

Developers are going to provide a yaml file with hosts in particular order (every deployment can differ, depend on needs) and each field in yaml file will have instructions for example install yum packages. I'm going to take this information and run ansible against every host with specific flags given in yaml file. What is the best practice in iterating through yaml file? Should I execute ansible-playbook against every field or should I use lookup function in ansible?

1 Answers1

0

Ansible's usual pattern is for plays to loop over host patterns from inventory and run roles on them. Using variables that are possibly group specific.

First, decide where the source of truth is for hosts and other data. Static files are fine, but through inventory and lookup plugins, you can reference some system. For example, NetBox.

You prefer YAML, which is great because Ansible uses lots of YAML. Users could provide these directly. A static inventory from the example in the docs:

all:
  hosts:
    mail.example.com:
  children:
    webservers:
      hosts:
        foo.example.com:
        bar.example.com:
    dbservers:
      hosts:
        one.example.com:
        two.example.com:
        three.example.com:

Create roles to contain the tasks to do things. Make most things a variable so they can be easily changed or overridden.

---
- name: Web server software
  package:
    name: "{{ httpd_packages }}"

Plays are maps of host patterns to roles.

---
- name: Web server deploy
  hosts: webservers

  roles:
  - www

Certain directory layouts provide a logical ways to organize things, and allowing some things to be loaded automatically.

inventory/deployA.yml
inventory/deployB.yml
inventory/group_vars/vars.yml
roles/www/defaults/main.yml
roles/www/tasks/main.yml
web.yml

Such a play could be run against environments A and B with ansible-playbook -i inventory/ web.yml

Notice the separation what to be done from which hosts that applies to, enabling reuse of roles and inventory.

Maybe developers help write the roles and plays. Maybe not and devs are only need to use them by tagging hosts to be in a particular group. Or automate it entirely, and do the deploy on commit in version control, via a CI/CD pipeline. Depends on who runs operations in your organization.

Many more ways are possible, these static files containing short plays are only the most basic.

John Mahowald
  • 30,009
  • 1
  • 17
  • 32