Ansible modify /etc/sysconfig/network file

I’m trying to write an Ansible script that will replace the network line in /etc/sysconfig/network file if the FQDN is not specified and if the gateway is (say) 10.10.10.1.

So this is what I have so far:

I would use the lineinfile module. A rough draft (untested) without
correct indentation:

- name: "Ensure FQDN is present"
  lineinfile:
    dest=/etc/sysconfig/network
    line="HOSTNAME=FQDN"
    regexp="^HOSTNAME"
    insertafter=EOF
    state=present

This has to be adapted, of course. Replace FQDN with your real fqdn.

Basically this looks for a line beginning with "HOSTNAME" (the regexp
part) and replaces it with the line "HOSTNAME=FQDN". If there is no
line matching the regexp, it puts the line at the end of the file.

Johannes

In the setup module (get_facts), Ansible should be detecting an FQDN that you can access with ‘{{ ansible_fqdn }}’

I am too used to typing outside of browsers. Let’s try this again.

According to the module docs, there is different behaviour whether you are replacing an existing line (backrefs) or adding a non-existent line (insertafter or insertbefore). Insertafter/insertbefore will add a new line but not remove the old one.

If you want to replace an existing line, you can use backrefs. However, if the regexp line doesn’t match, it won’t add the replacement line:

Adding to Johannes example:

  • name: “Replace hostname with FQDN”
    lineinfile:
    dest=/etc/sysconfig/network
    line=“HOSTNAME={{ ansible_fqdn }}”

backrefs=yes

Thanks Joanna for the clarification. I should use that module more
often... :wink:

Johannes

It is not necessarily true that Ansible will detect the fqdn. If no FQDN is set it will set that variable to just the short name.

You might need to compare the FQDN to the short hostname and then if they match create a new one (presumably you know what domain name to add to the end)

Equally you could replace the hostname with a created one each time as it won't change anything if the result woild be the same. Unless you are potentially using multiple domain names I would just do that,