如何在Ansible中添加多行

3

我正在尝试在匹配后向配置文件添加多行,并使用lineinfile,但我发现结果行被反转了。这是我的playbook:

  - name: Line test
    lineinfile:
      path: /home/vagrant/abcd
      insertafter: '### AFTER THIS LINE'
      line: "{{ item }}"
      state: present
    with_items:
      - '# This is line 1'
      - '# This is line 2'
      - '# This is line 3' 

这里是结果:

### AFTER THIS LINE
# This is line 3
# This is line 2
# This is line 1

我的期望结果是:

### AFTER THIS LINE
# This is line 1
# This is line 2
# This is line 3

我了解到反转是由于循环引起的,但是如何在不反转输入顺序的情况下克服这个问题呢?我知道有一个blockinfile命令可以将文本块原样放置,但那会添加“ANSIBLE MANAGED BLOCK”标记,而我不想要这个标记。
谢谢。

不要这样做,你不需要这样做(每个人都曾经认为他们需要这样做)。 - techraf
3个回答

6

在进一步尝试后,我发现我可以这样做:

 - name: Line test2
   blockinfile:
     path: /home/vagrant/abcd
     marker: "------"
     insertafter: '### AFTER THIS LINE PART 2'
     state: present
     block: |
       # This is line 1
       # This is line 2
       # This is line 3

这将产生以下结果:

 ### AFTER THIS LINE PART 2
 ------
 # This is line 1
 # This is line 2
 # This is line 3
 ------

我认为这符合我们的要求。

谢谢。


0
回答 @user2700022 的问题:在 Windows 主机上,我已经使用 ansible windows collection 的 win_lineinfile 模块和块字符 | 成功实现了。
    - name: add mod_wsgi config to apache config
      win_lineinfile:
        path: C:\Users\Administrator\AppData\Roaming\Apache24\conf\httpd.conf
        line: |
          LoadFile "c:/python37/python37.dll"
          LoadModule wsgi_module "c:/software/env/lib/site-packages/mod_wsgi/server/mod_wsgi.cp37-win_amd64.pyd"
          WSGIPythonHome "c:/software/env/"
        newline: windows

0

我同意techraf的评论(以及你的回答),blockinfile更适合这个目的。但是我想看看如何使用lineinfile完成:

- hosts: 127.0.0.1
  gather_facts: no
  tasks:
  - name: Add temp marker
    lineinfile:
      path: /home/vagrant/abcd
      insertafter: '### AFTER THIS LINE'
      line: "###TEMP MARKER###"
      state: present
  - name: Add content
    lineinfile:
      path: /home/vagrant/abcd
      insertbefore: '###TEMP MARKER###'
      line: "{{ item }}"
    with_items:
      - '# This is line 1'
      - '# This is line 2'
      - '# This is line 3'
  - name: Remove temp marker
    lineinfile:
      path: /home/vagrant/abcd
      line: "###TEMP MARKER###"
      state: absent

有人知道如何在Windows主机上实现这个吗? - user2700022

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接