我试图在匹配后使用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
据我所知,逆转是由于循环,但如何在不颠倒输入顺序的情况下克服这种情况?我知道有一个blockinfile将文本块按原样放置但是添加了“不可理解的块”标记,这是我不想要的。
感谢。
答案 0 :(得分:2)
在对此进行了更多的介绍之后,我发现我可以做到这一点:
- 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
------
我认为我们的要求是可以接受的。
感谢。
答案 1 :(得分: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
答案 2 :(得分:0)
要回答@ user2700022的问题:在Windows主机上,我设法通过ansible Windows集合的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