Mairold Kunimägi
Mairold Kunimägi

Reputation: 213

Ansible replace text in file

So ive been tasked with replaceing zabbix server. To do so i have to modify zabbix_agent file in all server and there are many. Tho in this job is the first time i see ansible so i need some help. And i am using ansible-playbook.

In zabbix_agentd.conf file there is the old zabbix conf:

HostMetadata=Linux
PidFile=/var/run/zabbix/zabbx_agentd.pid
LogFile=/var/log/zabbix/zabbix_agentd.log
LogFileSize=0
Server=zabbix.company.com
ServerActive=zabbix.company.com
HostnameItem=system.hostname
Include=/etc/zabbix_agentd.d/

Now i need to replace "Server" and "ServerActive" to "zabbix2.company.com"

I have tried various codes from this page to work for my needs but so far it has failed. No clue what im doing wrong

Upvotes: 3

Views: 3694

Answers (2)

Vladimir Botka
Vladimir Botka

Reputation: 68189

Try this one

    - lineinfile:
        path: /etc/zabbix_agentd.conf
        regexp: '^\s*{{ key }}\s*=(.*)$'
        line: '{{ key }}={{ value }}'
      notify: reload zabix
      loop:
        - {key: 'Server', value: 'zabbix2.company.com'}
        - {key: 'ServerActive', value: 'zabbix2.company.com'}


Notes

  • Path is required; probably /etc/zabbix_agentd.conf ?
  • It is not necessary to search the white-space \s* in regexp. However, it would match and fix potential spaces in the configuration.
  • Create and notify a handler reload zabix when anything changed. See Handlers: Running Operations On Change.
  • Take a look at Zabix modules.

Upvotes: 6

Mairold Kunimägi
Mairold Kunimägi

Reputation: 213

I have manged to solve this issue using this code.

---
tasks:
- name: 'replace line'
  lineinfile:
    dest: /etc/zabbix/zabbix_agentd.conf
    regexp: '^(.*)Server=zabbix.company.com(.*)$'
    line: 'Server=zabbix2.company.com'
    backrefs: yes

Upvotes: 2

Related Questions