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

时间:2016-11-24 14:12:34

标签: ansible

我是ansible的新手。

是否有一种简单的方法可以用option domain-name-servers中的/etc/dhcp/interface-br0.conf替换以更多IP开头的行?

  option domain-name-servers 10.116.184.1,10.116.144.1;

我想添加,10.116.136.1

4 个答案:

答案 0 :(得分:10)

您可以使用lineinfile Ansible module来实现这一目标。

  - 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

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

line选项会将您之前找到的内容替换为您选择的新内容。

答案 1 :(得分:2)

您可以使用替换模块。请参阅 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

运行

ansible-playbook httpd-replace-hostname.yml

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

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 

答案 2 :(得分:1)

我创建了一个角色dhcp,其中包含以下main.yaml

---
- name: add all dns servers
  lineinfile:
    dest: /etc/dhcp/interface-br0.conf
    regexp: '^\s*option domain-name-servers.*$'
    line: '  option domain-name-servers 10.116.184.1,10.116.144.1,10.116.136.1;'
    backrefs: yes
  become: true

答案 3 :(得分:0)

我们可以使用 lineinfile模块替换行

使用临时命令

ansible <host> -m lineinfile -a "path=/etc/dhcp/interface-br0.conf regexp=''^(.*)option domain-name-servers(.*)$'' line='1option domain-name-servers 10.116.184.1,10.116.144.1,10.116.136.1;' backrefs: yes"

使用可播放的剧本

- name: replacing a line in file
  lineinfile: 
    path: /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

有关更多信息,我们可以检查其他选项:在 lineinfile 模块

https://docs.ansible.com/ansible/latest/modules/lineinfile_module.html