John Lonewolf
John Lonewolf

Reputation: 81

Executing specific tasks against specific hosts in an Ansible playbook

I need to deploy my apps to two VMs using an Ansible playbook. Each VM serves a different purpose and my app consists of several different components, so each component has its own set of tasks in the playbook.

My inventory file looks like this:

[vig]
192.168.10.11

[websvr]
192.168.10.22

Ansible playbooks only have one for declaring hosts, which is right at the top and all the tasks execute against the specified hosts. But what I hope to achieve is:

  1. Tasks 1 to 10 execute against the vig group
  2. Tasks 11 to 20 execute against the websvr group

All in the same playbook, as in: ansible-playbook -i <inventory file> deploy.yml.

Is that possible? Do I have to use Ansible roles to achieve this?

Upvotes: 1

Views: 6516

Answers (1)

chash
chash

Reputation: 4423

Playbooks can have multiple plays (see https://docs.ansible.com/ansible/latest/user_guide/playbooks_intro.html).

Playbooks can contain multiple plays. You may have a playbook that targets first the web servers, and then the database servers. For example:

---
- hosts: webservers
  remote_user: root

  tasks:
  - name: ensure apache is at the latest version
    yum:
      name: httpd
      state: latest
  - name: write the apache config file
    template:
      src: /srv/httpd.j2
      dest: /etc/httpd.conf

- hosts: databases
  remote_user: root

  tasks:
  - name: ensure postgresql is at the latest version
    yum:
      name: postgresql
      state: latest
  - name: ensure that postgresql is started
    service:
      name: postgresql
      state: started

Upvotes: 7

Related Questions