如何在Ansible中添加多行

如何在Ansible中添加多行,ansible,Ansible,我试图在匹配后向配置文件添加多行,并使用lineinfile,但我发现结果行是相反的。这是我的剧本: - name: Line test lineinfile: path: /home/vagrant/abcd insertafter: '### AFTER THIS LINE' line: "{{ item }}" state: present with_items: - '# This is line 1'

我试图在匹配后向配置文件添加多行,并使用lineinfile,但我发现结果行是相反的。这是我的剧本:

  - 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
我知道反转是由于循环造成的,但是如果不反转输入顺序,如何克服这一点呢?我知道有blockinfle,它将文本块按原样放置,但它添加了我不想要的“ANSIBLE MANAGED block”标记


谢谢。

在玩了一点之后,我发现我可以做到:

 - 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
 ------
我认为这符合我们的要求


谢谢。

我同意techraf的评论(以及您的回答),Blockinfle更适合此用途。但我想看看如何使用Lineinfle:

- 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

要回答@user2700022的问题:在Windows主机上,我已成功地使用ansible Windows集合的模块和块字符
|

-name:将mod_wsgi config添加到apache config
win_Lineinfle:
路径:C:\Users\Administrator\AppData\Roaming\Apache24\conf\httpd.conf
行:|
加载文件“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/”
新行:windows

不要这样做,你不需要这样做(每个人在某个时候都认为他们需要)。有人知道如何为Windows主机实现这一点吗?