Variable "role" in play is undefined

41 views
Skip to first unread message

Jeff Hardy

unread,
Apr 22, 2016, 10:00:15 AM4/22/16
to Ansible Project
I have a static inventory setup with the hope of applying different roles to different hosts, but am finding that this playbook is not achieving what I would like:

- hosts: "{{target}}"
  pre_tasks:
    - debug: var=role
  roles:
    - "{{role}}"
  tasks:
    - debug: var=role
  post_tasks:
    - debug: var=role


Ultimately with an inventory of:

192.168.1.13 role=test


Executing this playbook:

ansible-playbook -i inventory testrole.yml -e "target=192.168.1.13"
ERROR! 'role' is undefined


This persists no matter where I attempt to define that role variable, in inventory, group_vars, host_vars, etc.  If I comment out the roles stanza, all the debug tasks report the variable being interpolated correctly no matter how I do it.  The only way I have found the role to be variable so far is to define it with --extra-args at the command line.

I this a bug, or am I running into a hard boundary of ansible?

Johannes Kastl

unread,
Apr 22, 2016, 2:44:13 PM4/22/16
to ansible...@googlegroups.com
On 22.04.16 16:00 Jeff Hardy wrote:
> I have a static inventory setup with the hope of applying different roles
> to different hosts, but am finding that this playbook is not achieving what
> I would like:
>
> - hosts: "{{target}}"
> pre_tasks:
> - debug: var=role
> roles:
> - "{{role}}"
^^^^^^^^
Maybe you need a different variable here, something like:
hostvars[target]['role']

Johannes

signature.asc

Brian Coca

unread,
Apr 22, 2016, 2:56:20 PM4/22/16
to ansible...@googlegroups.com
Also i don't recommend using vars that have same name as keywords.


----------
Brian Coca

Jeff Hardy

unread,
Apr 22, 2016, 4:59:49 PM4/22/16
to Ansible Project
I tried your suggestion, and also Brian's following suggestion of a different variable, and it reports:

ERROR! 'hostvars' is undefined

And I can debug out all the hostvars in all the task calls with no issue as long as I am not trying to call the role.

pre_tasks:
  - debug: var=dorole
  - debug: var=hostvars[inventory_hostname]['dorole']

Maybe an order of processing issue?

Brian Coca

unread,
Apr 22, 2016, 5:01:59 PM4/22/16
to ansible...@googlegroups.com
Sorry, should have realized on first post:

you CANNOT define which role is loaded based on host variables, as the roles NEED to be the same for all hosts and get loaded BEFORE host variables are available.


----------
Brian Coca

Jeff Hardy

unread,
Apr 22, 2016, 5:46:15 PM4/22/16
to Ansible Project
It definitely seemed like I was bumping into something like that.  Thank you for the info.
Reply all
Reply to author
Forward
0 new messages