Ansible: variable interpolation in task name

Solution 1:

Variables are not resolved inside the name. Only inside the actual tasks/conditions etc. the placeholders will be resolved. I guess this is by design. Imagine you have a with_items loop and use the {{ item }}in the name. The tasks name will only be printed once, but the {{ item }} would change in every iteration.

I see the examples, even the one in the doc you linked to, use variables in the name. But that doesn't mean the result would be like you expected it. The docs are community managed. It might be someone just put that line there w/o testing it - or maybe it used to work like that in a previous version of Ansible and the docs have not been updated then. (I'm only using Ansible since about one year). But even though it doesn't work like we wish it would, I'm still using variables in my name's, just to indicate that the task is based on dynamic parameters. Might be the examples have been written with the same intention.

An interesting observation I recently made (Ansible 1.9.4) is, default values are written out in the task name.

- name: create a virtual host file for {{ vhost | default("foo") }}

When executed, Ansible would show the task title as:

TASK: [create a virtual host file for foo]

This way you can avoid ugly task names in the output.

Solution 2:

Explanation

Whether the variable gets interpolated depends on where it has been declared.

Imagine You have two hosts: A and B.

  • If variable foo has only per-host values, when Ansible runs the play, it cannot decide which value to use.
  • On the other hand, if it has a global value (global in a sense of host invariance), there is no confusion which value to use.

Source: https://github.com/ansible/ansible/issues/3103#issuecomment-18835432

Hands on playbook

  • ansible_user is an inventory variable
  • greeting is an invariant variable
- name: Test variable substitution in names
  hosts: localhost
  connection: local
  vars:
    greeting: Hello
  tasks:
    - name: Sorry {{ ansible_user }}
      debug:
        msg: this won't work
    - name: You say '{{ greeting }}'
      debug:
        var: ansible_user