6

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"}
techraf
  • 64,883
  • 27
  • 193
  • 198

1 Answers1

23

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

Remove the line.

techraf
  • 64,883
  • 27
  • 193
  • 198
  • in my case `gather_facts: true` but still doesn't collect it, it is caused when I use `--tags` if i'm not - it works – Ricky Levi May 11 '23 at 07:53