Set variable before hosts in playbook?

145 views
Skip to first unread message

Anthony Cheng

unread,
Apr 6, 2017, 12:57:24 PM4/6/17
to Ansible Project
Is it possible to set variable before hosts in playbook?

Something like this doesn't work:

var:
 VARHOSTNAME
: test

- hosts: "{{ VARHOSTNAME }}"
  gather_facts
: true
  become
: yes

I know I can set variable in vars file or pass in environment values at command line but wanted to know if i can just define variable directly at the playbook level.



Kai Stian Olstad

unread,
Apr 6, 2017, 1:22:43 PM4/6/17
to ansible...@googlegroups.com
You can have vars as part of the play

- hosts: "{{ VARHOSTNAME }}"
gather_facts: true
become: yes
vars:
VARHOSTNAME: test

--
Kai Stian Olstad

Anthony Cheng

unread,
Apr 6, 2017, 1:32:05 PM4/6/17
to Ansible Project, ansible-pr...@olstad.com
Are you sure that it actually works?  It didn't when I tested it (looks like order matters).

Kai Stian Olstad

unread,
Apr 6, 2017, 1:38:48 PM4/6/17
to ansible...@googlegroups.com
On 06. april 2017 19:32, Anthony Cheng wrote:
> Are you sure that it actually works? It didn't when I tested it (looks
> like order matters).

Yes I'm sure, if not I would not have written it.

https://docs.ansible.com/ansible/playbooks_variables.html#variables-defined-in-a-playbook


> On Thursday, April 6, 2017 at 1:22:43 PM UTC-4, Kai Stian Olstad wrote:
>>
>> On 06. april 2017 18:57, Anthony Cheng wrote:
>>> Is it possible to set variable before hosts in playbook?
>>>
>>> Something like this doesn't work:
>>>
>>> var:
>>> VARHOSTNAME: test
>>>
>>> - hosts: "{{ VARHOSTNAME }}"
>>> gather_facts: true
>>> become: yes
>>>
>>> I know I can set variable in vars file or pass in environment values at
>>> command line but wanted to know if i can just define variable directly
>> at
>>> the playbook level.
>>
>> You can have vars as part of the play
>>
>> - hosts: "{{ VARHOSTNAME }}"
>> gather_facts: true
>> become: yes
>> vars:
>> VARHOSTNAME: test
>>

Take notice that I wrote vars: not var: as you did.


--
Kai Stian Olstad

Anthony Cheng

unread,
Apr 6, 2017, 3:14:04 PM4/6/17
to Ansible Project, ansible-pr...@olstad.com
Thanks!

Somehow I missed that vars (and IDE missed it as well..)
Reply all
Reply to author
Forward
0 new messages