How do I narrow down scope when running an ansible

2019-07-12 20:28发布

问题:

I have a playbook that takes a lot of time to execute, partly due to having a lot of nodes on which it has to run on (I am wasting time with ansible checking the status of all the nodes), and I need to make some changes somewhere in the middle of it.

What would be the best way in which I could narrow down the scope of the playbook? I've considered isolating the required change and/or just running the modified part on a single node?

回答1:

This is what tags are for.

You can tag any tasks with any combination of tags and then specify that combination of tags to run (or, alternatively, to skip with --skip-tags) which will then only run those specified tasks.

So an example playbook may look like this:

- hosts: all
  tasks:
    - name: copy foo
      copy:
        src:  path/to/foo
        dest: path/to/foo
      tags:
        - copy_foo
        - copy
        - foo

    - name: copy bar
      copy:
        src:  path/to/bar
        dest: path/to/bar
      tags:
        - copy_bar
        - copy
        - bar

    - name: restart foo
      service:
        name:  foo
        state: restarted
      tags:
        - restart_foo
        - restart
        - foo

    - name: restart bar
      service:
        name:  bar
        state: restarted
      tags:
        - restart_bar
        - restart
        - bar

I can then run just the "restart foo" task with ansible-playbook -i path/to/hosts playbook.yml --tags "restart_foo". Alternatively I could run all the bar related tags and also restart foo (but not copying foo) with any combination of the following:

  • ansible-playbook -i path/to/hosts playbook.yml --tags "bar,restart_foo"
  • ansible-playbook -i path/to/hosts playbook.yml --tags "restart,copy_bar"
  • ansible-playbook -i path/to/hosts playbook.yml --skip-tags "copy_foo"

If you want to instead (or as a combination) limit the nodes that a play is ran against then you can do that with --limit option. So if you want to limit the play to just web servers then you could run it with ansible-playbook -i path/to/hosts playbook.yml --limit webservers or even limit it to a single specific host with ansible-playbook -i path/to/hosts playbook.yml --limit web.example.org



回答2:

Sadly this is not really documented, even if is very useful

ansible-playbook -i "hostname," site.yml

You can list multiple hosts if you want. As you can see you need to put a comma after the name to make it realise it is a list.