learn-ansible

Learning Ansible

View the Project on GitHub robertdebock/learn-ansible

Targeting

With Ansible you can “taget” (or select) hosts using a couple of patterns.

For example, here is a playbook snippet that will run on all hosts:

- name: Do something on all hosts
  hosts: all

  tasks:
    - name: Say something
      debug:
        msg: "Hello world!"

As you can see, the hosts parameter is targeting all hosts.

There are a couple of patterns that are interesting:

Limiting

You can also restict the hosts that are targeted by using the --limit parameter. This is a reduction from the targeted pattern defined in hosts in the playbook.

Note: The --limit parameter can be shortened to -l.

For example, this inventory:

[webservers]
node-1
node-2
node-3
node-4

[databaseservers]
node-5
node-6
node-7
node-8

[development]
node-1
node-5

[test]
node-2
node-6

[accepance]
node-3
node-7

[production]
node-4
node-8

With this playbook:

- name: Do something on the webservers hosts
  hosts: webservers

  tasks:
    - name: Say something
      debug:
        msg: "Hello world!"

And this limit:

ansible-playbook playbook.yml --limit development

Would run on node-1 only.

Note: Limiting on the command line, like above, has a disadvantage of not being stored in code.

Assignment

  1. Create an inventory with the following groups:

Note: You need to tell Ansible (in ansible.cfg, under the [defaults] section, to use your inventory file as the inventory. The parameter is inventory.)

  1. Add the following hosts:
  1. Run the playbook with a limit on development.

Note: The nodes are not reachable, so the task will fail. That’s okay.

Verify

You should see the playbook run on node-3 only.