【问题标题】:How to insert a line not immediately after a match using Ansible?如何使用 Ansible 在匹配后不立即插入一行?
【发布时间】:2019-01-16 07:04:13
【问题描述】:

我试图在 2 行匹配后插入一行。

- name : Update compute node under  ipsec group
  lineinfile:
    backup: yes
    state: present
    path: /root/multinode
    insertafter: '\[ipsec:children\]'
    line: "hostname"

文件:

[ipsec:children]
control

结果:

[ipsec:children]
hostname
control

期望的结果:

[ipsec:children]
control
hostname

基本上我想在匹配后插入 1 行,而不是在下一行。

请告诉我该怎么做。

【问题讨论】:

标签: ansible


【解决方案1】:

一个选项是使用blockinfile(参见下面的示例)或template。模块 lineinfile 最适用于非结构化数据。

当您只想更改文件中的单行时,这主要是有用的。 ...如果要在文件中插入/更新/删除一行行,请检查 blockinfile。对于其他情况,请参阅复制或模板模块。

- hosts: localhost
  gather_facts: no
  vars:
    ipsec_children_conf:
      - "control"
      - "hostname"
  tasks:
    - blockinfile:
        path : /root/multinode
        create: yes
        block: |
          [ipsec:children]
          {% for conf_item in ipsec_children_conf %}
          {{ conf_item }}
          {% endfor %}


> cat /root/multinode 
# BEGIN ANSIBLE MANAGED BLOCK
[ipsec:children]
control
hostname
# END ANSIBLE MANAGED BLOCK

【讨论】:

    猜你喜欢
    • 2015-08-05
    • 1970-01-01
    • 2013-03-11
    • 2016-09-29
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    相关资源
    最近更新 更多