Linux – Get current hostname and push it into conf file with ansible

ansiblelinuxyaml

I'm working into an ansible playbook to get the current hostname of a server and then set it into a configuration file. I cannot figure it out how can I push the shell output using the lineinfile module.

  - name: Get hostname
    shell: echo $HOSTNAME
    register: result

  - name: Set hostname on conf file
    lineinfile: dest=/etc/teste/linux/zabbix_agentd.conf regexp="^Hostname=.*" insertafter="^# Hostname=" line=Hostname=????

Best Answer

In general, to look what's inside a variable you can use the debug module.

- debug:
    var: result

This should show you an object and its properties which include stdout. That is the complete result of the previous command. So to use the output of the first task you would use result.stdout.

To use any variable you would use Jinja2 expressions: {{ whatever }}. So your task could look like this:

- name: Set hostname on conf file
  lineinfile:
    dest: /etc/teste/linux/zabbix_agentd.conf
    regexp: ^Hostname=.*
    insertafter: ^# Hostname=
    line: Hostname={{ result.stdout }}

So much for theory, but here comes the real answer. Don't do it like that. Of course Ansible already knows the hostname.

The hostname as defined in your inventory would be {{ inventory_hostname }}. The hostname as reported by the server is {{ ansible_hostname }}. Additionally there is {{ ansible_fqdn }}. So just use any of these instead of running an additional task:

- name: Set hostname on conf file
  lineinfile:
    dest: /etc/teste/linux/zabbix_agentd.conf
    regexp: ^Hostname=.*
    insertafter: ^# Hostname=
    line: Hostname={{ ansible_hostname }}
Related Topic