Variable "role" in play is undefined

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?

^^^^^^^^
Maybe you need a different variable here, something like:
hostvars[target]['role']

Johannes

Also i don’t recommend using vars that have same name as keywords.

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?

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.

It definitely seemed like I was bumping into something like that. Thank you for the info.