Ansible:插入行(如果不存在) [英] Ansible: Insert line if not exists

查看:268
本文介绍了Ansible:插入行(如果不存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying insert a line in a property file using ansible. I want to add some property if it does not exist, but not replace it if such property already exists in the file.

我加入了角色

- name: add couchbase host to properties
  lineinfile: dest=/database.properties regexp="^couchbase.host"  line="couchbase.host=127.0.0.1"

但是,如果文件中已经存在该属性值,它将替换回127.0.0.1.

But this replaces the property value back to 127.0.0.1 if it exists already in the file.

我做错了什么?

推荐答案

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

The lineinfile module does what it's supposed to: It ensures the line as defined in line is present in the file and the line is identified by your regexp. So no matter what value your setting already has, it will be overridden by your new line.

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

If you don't want to override the line you first need to test the content and then apply that condition to the lineinfile module. There is no module for testing the content of a file so you probably need to run grep with a shell command and check the .stdout for content. Something like this (untested):

- name: Test for line
  shell: grep -c "^couchbase.host" /database.properties || true
  register: test_grep

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

And then apply the condition to your lineinfile task:

- name: add couchbase host to properties
  lineinfile:
    dest: /database.properties
    line: couchbase.host=127.0.0.1
  when: test_grep.stdout == "0"

regexp然后可以删除,因为您已经确保该行不存在,所以它永远不会匹配.

The regexp then can be removed since you already made sure the line doesn't exist so it never would match.

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

But maybe you're doing things back to front. Where does that line in the file come from? When you manage your system with Ansible there should be no other mechanisms in place which interfere with the same config files. Maybe you can work around this by adding a default value to your role?

这篇关于Ansible:插入行(如果不存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆