Use Ansible task name as variable

ansible

I have some task in a playbook. I need send a message for each task.

- name: Upload kubernetes config
  template:
    src=kubernetes-config.j2
    dest=/etc/kubernetes/config backup=yes
    group=root
    owner=root
    mode="u=rw,g=r,o=r"
  notify: Send notification message via Slack

I use slack notify module.

- name: Send notification message via Slack
  local_action:
    module: slack
    domain: hsap.slack.com
    token: yourtoken
    msg: "{{ansible_nodename}} - {{ansible_distribution}}"

I have in mind use one handler ("Send notification message via Slack"). I don't know how to pass the task name as variable to the handler.

¿How I can pass the task name as variable?

Best Answer

You probably do not want to use handlers for this. Handlers are for things like service management where you don't want them to run until the end of your play. They aren't intended to take parameters.

In your case I assume you want to send a notification via slack as soon as the task runs, to do this you could add your slack notification task below your "upload to kerbenetes config" task or you could use a task include with a parameter.

Example:

main.yml:

- name: Upload kubernetes config
  template:
    src=kubernetes-config.j2
    dest=/etc/kubernetes/config backup=yes
    group=root
    owner=root
    mode="u=rw,g=r,o=r"
- include: send_slack.yml msg="kurbenetes updated!"

send_slack.yml:

- name: Send notification message via Slack
  local_action:
    module: slack
    domain: hsap.slack.com
    token: yourtoken
    msg: "{{ansible_nodename}} - {{ansible_distribution}} - {{ msg }}"