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

查看:41
本文介绍了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.

我添加到我的 ansible 角色

I add to my ansible role

- 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 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天全站免登陆