我需要使用Anisble模块来检查文件是否存在,如果不存在,则创建它并向其中写入一些数据。
如果文件存在,那么检查我要写的内容是否存在于该文件中。
如果内容不存在,就把内容写进去。如果内容是存在的,那么就什么都不做。
我下面的演算本不能用。有什么建议吗?
- hosts: all
tasks:
- name: check for file
stat:
path: "{{item}}"
register: File_status
with_items:
- /etc/x.conf
- /etc/y.conf
- name: Create file
file:
path: "{{item}}"
state: touch
with_items:
- /etc/x.conf
- /etc/y.conf
when: not File_status.stat.exists
- name: add content
blockinfile:
path: /etc/x.conf
insertafter:EOF
block: |
mydata=something
你能帮我提供模块和条件,可以达到我想要的输出吗?
下面将。
changed
changed
即# BEGIN ANSIBLE MANAGED BLOCK
mydata=something
mydata2=somethingelse
# END ANSIBLE MANAGED BLOCK
changed
(见 marker
选择权 如果您在同一个文件中需要管理多个区块,并且不要忘记 {mark}
在那里,如果你改变它)。)ok
.请阅读 模块文件 更多信息
---
- name: blockinfile example
hosts: localhost
gather_facts:false
tasks:
- name: Update/create block if needed. Create file if not exists
blockinfile:
path: /tmp/testfile.conf
block: |
mydata=something
mydata2=somethingelse
create: true
这里是实现你的要求的可能方法。
- hosts: localhost
tasks:
- name: Create file
copy:
content: ""
dest: "{{item}}"
force: no
with_items:
- /etc/x.conf
- /etc/y.conf
- name: add content
blockinfile:
path: "{{ item.file_name }}"
insertafter: EOF
block: |
"{{ item.content }}"
loop:
- { file_name: '/etc/x.conf', content: 'mydata=something' }
- { file_name: '/etc/y.conf', content: 'mydata=hey something' }