Override hosts variable of Ansible playbook from the command line

luqo33 picture luqo33 · Oct 19, 2015 · Viewed 115.3k times · Source

This is a fragment of a playbook that I'm using (server.yml):

- name: Determine Remote User
  hosts: web
  gather_facts: false
  roles:
    - { role: remote-user, tags: [remote-user, always] }

My hosts file has different groups of servers, e.g.

[web]
x.x.x.x

[droplets]
x.x.x.x

Now I want to execute ansible-playbook -i hosts/<env> server.yml and override hosts: web from server.yml to run this playbook for [droplets].

Can I just override as a one time off thing, without editing server.yml directly?

Thanks.

Answer

wallydrag picture wallydrag · Oct 20, 2015

I don't think Ansible provides this feature, which it should. Here's something that you can do:

hosts: "{{ variable_host | default('web') }}"

and you can pass variable_host from either command-line or from a vars file, e.g.:

ansible-playbook server.yml --extra-vars "variable_host=newtarget(s)"