Set variable before hosts in playbook?

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

Are you sure that it actually works? It didn’t when I tested it (looks like order matters).

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

Thanks!

Somehow I missed that vars (and IDE missed it as well…)