用ansible替换配置文件中的一行

rub*_*o77 13 ansible

我是ansible的新手.

有没有一种简单的方法,以取代开头的一行option domain-name-servers/etc/dhcp/interface-br0.conf有更多的IP地址?

  option domain-name-servers 10.116.184.1,10.116.144.1;
Run Code Online (Sandbox Code Playgroud)

我想补充一下 ,10.116.136.1

Seg*_*ult 19

您可以使用lineinfile Ansible模块来实现这一点.

  - name: replace line
    lineinfile: 
      dest: /etc/dhcp/interface-br0.conf 
      regexp: '^(.*)option domain-name-servers(.*)$' 
      line: 'option domain-name-servers 10.116.184.1,10.116.144.1,10.116.136.1;'
      backrefs: yes
Run Code Online (Sandbox Code Playgroud)

regexp选项告诉模块要替换的内容是什么.

line选项将以前找到的内容替换为您选择的新内容.

  • 在这个例子中 backrefs 做了什么? (3认同)

小智 7

您可以使用替换模块。请参阅 http://docs.ansible.com/ansible/latest/modules/replace_module.html

#example
vim httpd-replace-hostname.yml

---
- hosts: <Your ansible host>
  tasks:
  - name: hostname was used instead of path.
    replace:
      path: /etc/hosts
      regexp: '(\s+)old\.name\.com(\s+.*)?$'
      replace: '\new.name.com\2'
      backup: yes
Run Code Online (Sandbox Code Playgroud)

ansible-playbook httpd-replace-hostname.yml
Run Code Online (Sandbox Code Playgroud)

您可以成功查看结果,如下所示。

PLAY [Your hosts] ***************************************************************************************************************************************************************

TASK [Gathering Facts] **********************************************************************************************************************************************************
ok: [hostname.name.com]

TASK [hostname was used instead of path.] ***************************************************************************************************************************************
ok: [hostname.name.com]

TASK [Replace after the expression till the end of the file] ********************************************************************************************************************
changed: [hostname.name.com]

PLAY RECAP **********************************************************************************************************************************************************************
hostname.name.com : ok=3    changed=1    unreachable=0    failed=0 
Run Code Online (Sandbox Code Playgroud)