Ansible:如果不存在则插入行

Pav*_*tam 24 ansible ansible-playbook

我正在尝试使用ansible在属性文件中插入一行.我想添加一些属性,如果它不存在,但如果文件中已经存在这样的属性,则不要替换它.

我加入了我的ansible角色

- name: add couchbase host to properties
  lineinfile: dest=/database.properties regexp="^couchbase.host"  line="couchbase.host=127.0.0.1"
Run Code Online (Sandbox Code Playgroud)

但是,如果属性值已存在于文件中,则会将属性值替换回127.0.0.1.

我做错了什么?

udo*_*dan 28

lineinfile模块执行它应该执行的操作:它确保line文件中存在已定义的行,并且该行由您的标识regexp.因此,无论您的设置具有什么价值,它都会被您的新设备覆盖line.

如果您不想覆盖该行,则首先需要测试内容,然后将该条件应用于lineinfile模块.没有用于测试文件内容的模块,因此您可能需要grep使用shell命令运行并检查.stdoutfor内容.像这样(未经测试):

- name: Test for line
  shell: grep "^couchbase.host" /database.properties
  register: test_grep
Run Code Online (Sandbox Code Playgroud)

然后将条件应用于您的lineinfile任务:

- name: add couchbase host to properties
  lineinfile:
    dest: /database.properties
    line: couchbase.host=127.0.0.1
  when: test_grep.stdout != ""
Run Code Online (Sandbox Code Playgroud)

regexp既然你已经确信该行不存在,所以它永远不会匹配,则可以去掉.

但也许你正在做的事情要回到前面.文件中的那一行来自哪里?当您使用Ansible管理系统时,应该没有其他机制干扰相同的配置文件.也许你可以通过default为你的角色添加一个值来解决这个问题?

  • @openCivilisation那是因为grep在没有匹配项的情况下返回退出代码`1`。Ansible假设非零退出代码是脚本/命令的失败,因此中止。我所做的是:`shell:'grep“ my_pattern” some_file -c || 如果为true,则检查;然后为“何时:test_grep.stdout ==“ 0””。 (2认同)

Nic*_*ard 11

这可以通过简单地使用lineinfile和来实现check_mode

- name: Check if couchbase.host is already defined
  lineinfile:
    state: absent
    path: "/database.properties"
    regexp: "^couchbase.host="
  check_mode: true
  changed_when: false # This just makes things look prettier in the logs
  register: check

- name: Define couchbase.host if undefined
  lineinfile:
    state: present
    path: "/database.properties"
    line: "couchbase.host=127.0.0.1"
  when: check.found == 0

Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案,因为 Ansible 不鼓励使用 shell,除非没有适用的模块。 (2认同)

小智 6

这是我能够让这个工作的唯一方法.

- name: checking for host
  shell: cat /database.properties | grep couchbase.host | wc -l
  register: test_grep

- debug: msg="{{test_grep.stdout}}"

- name: adding license server
  lineinfile: dest=/database.properties line="couchbase.host=127.0.0.1"
  when: test_grep.stdout == "0"
Run Code Online (Sandbox Code Playgroud)

  • `shell:grep -c couchbase.host /database.properties`,更少的二进制文件。 (3认同)