{{ ansible_hostname }} not working while calling directly with Ansible 2.3

user7995721 picture user7995721 · Jun 30, 2017 · Viewed 7.9k times · Source

Has anyone faced the following issue with "{{ ansible_hostname }}" while calling in a playbook task directly?

Please suggest if there is other way around to do it or if I'm doing anything wrong here, I have tried it with both lineinfile & replace module:

---
- name: Playbook to Install CollectD
  hosts: servercast01
  gather_facts: False
  remote_user: root
  become: true
  tasks:
  - name: Replacing hostname entry
    lineinfile:
      dest: "/tmp/collectd/etc/collectd.conf"
      regexp: '#Hostname  "myvm01"'
      line: 'Hostname  "{{ ansible_hostname }}"'

2) With replace module:

---
- name: Playbook to Install CollectD
  hosts: servercast01
  gather_facts: False
  remote_user: root
  become: true
  tasks:
  - name: Replacing hostname entry
    replace:
      dest: /tmp/collectd/etc/collectd.conf
      regexp: '#Hostname  "myvm01"'
      replace: 'Hostname  "{{ ansible_hostname }}"'
      backup: yes

Below is the error while executing the playbook..

fatal: [servercast01]: FAILED! => {"failed": true, "msg": "the field 'args' has an invalid value, which appears to include a variable that is undefined. The error was: 'ansible_hostname' is undefined\n\nThe error appears to have been in '/etc/ansible/lineinfile3.yml': line 10, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n  tasks:\n  - name: Replacing hostname entry\n    ^ here\n"}

Answer

techraf picture techraf · Jun 30, 2017

ansible_hostname is a fact and you have explicitly disabled gathering facts (gather_facts: False), so it's not defined.

Remove the line.