首页 > 解决方案 > 想在ansible playbook中使用lineinfile在文件中插入文本

问题描述

我需要在文件中的参数结束之前添加一个文本。我需要在之前插入我的文本</abc>。我正在使用 lineinfile ,它输入之前的文本<abc>而不是</abc>.

我当前的文本文件:

<domain-log-broadcast-filter>MultiDataSourceLogFilter</domain-log-broadcast-filter>
      <abc>Info is already here. i just need to append the text at end of this parameter. new values to be inserted here</abc>

我的剧本:

  - lineinfile:
         path: /tmp/tochange.xml
         insertbefore:  '\<\/abc\>'
         line: "Tisisthelinetobeinsertedbyme"
         state: present

我的输出是:

<domain-log-broadcast-filter>MultiDataSourceLogFilter</domain-log-broadcast-filter>
Thisisthelinetobeinsertedbyme
      <abc>Info is already here. i just need to append the text at end of this parameter. new values to be inserted here</abc>

现在我有两个要求:

  1. 我想在之前插入我的文本</abc>
  2. 我的文件中有 4 个</abc>参数。我想忽略第一个</abc>,该行将插入其他 3 个</abc>参数之前。

请给我一个最好的方法来做到这一点,我所需要的只是完成这项工作,使用剧本中的任何模块任何脚本。提前致谢。

标签: shellansibledevopsansible-template

解决方案


问:“......任何模块,剧本中的任何脚本。”

A: Ansible 文件模块无法做到这一点。您将需要模块命令shell来运行sedawk等文件编辑工具。

模块lineinfile无法满足要求。该模块修改文件中的单行。无法更改匹配regexp的 4 行中的 3 行。恐怕replace和blockinfile模块都不会帮助你。模块模板修改整个文件。下一个选项可能是模块补丁

引用lineinfile

“...对于其他情况,请参阅副本或模板模块。”


推荐阅读