如何使用Ansible创建一个空文件? [英] How to create an empty file with Ansible?
问题描述
使用Ansible创建空文件的最简单方法是什么?我知道我可以将一个空文件保存到files
目录中,然后将其复制到远程主机,但是我发现这样做有些不满意.
What is the easiest way to create an empty file using Ansible? I know I can save an empty file into the files
directory and then copy it to the remote host, but I find that somewhat unsatisfactory.
另一种方法是在远程主机上触摸文件:
Another way is to touch a file on the remote host:
- name: create fake 'nologin' shell
file: path=/etc/nologin state=touch owner=root group=sys mode=0555
但是随后每次都触摸文件,在日志中显示为黄线,这也不令人满意...
But then the file gets touched every time, showing up as a yellow line in the log, which is also unsatisfactory...
这个简单的问题有更好的解决方案吗?
Is there any better solution to this simple problem?
推荐答案
文件模块的文档说
如果为
state=file
,则如果文件不存在,则不会创建该文件,如果需要此行为,请参见副本或模板模块.
If
state=file
, the file will NOT be created if it does not exist, see the copy or template module if you want that behavior.
因此,我们使用复制模块,仅当文件尚不存在时才使用force=no
创建一个新的空文件(如果文件存在,则保留其内容).
So we use the copy module, using force=no
to create a new empty file only when the file does not yet exist (if the file exists, its content is preserved).
- name: ensure file exists
copy:
content: ""
dest: /etc/nologin
force: no
group: sys
owner: root
mode: 0555
这是一种声明式的优雅解决方案.
This is a declarative and elegant solution.
这篇关于如何使用Ansible创建一个空文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!