使用Ansible创建空文件的最简单方法是什么?我知道我可以将一个空文件保存到files
目录中,然后将其复制到远程主机,但我觉得有点不尽如人意.
另一种方法是触摸远程主机上的文件:
- name: create fake 'nologin' shell
file: path=/etc/nologin state=touch owner=root group=sys mode=0555
Run Code Online (Sandbox Code Playgroud)
但是每次文件都会被触摸,在日志中显示为黄线,这也是令人不满意的......
这个简单的问题有更好的解决方案吗?
Ren*_*ijl 164
文件模块的文档说
如果
state=file
,如果文件不存在,则不会创建该文件,如果您想要该行为,请参阅副本或模板模块.
因此我们使用复制模块,force=no
仅在文件尚不存在时才创建新的空文件(如果文件存在,则保留其内容).
- name: ensure file exists
copy:
content: ""
dest: /etc/nologin
force: no
group: sys
owner: root
mode: 0555
Run Code Online (Sandbox Code Playgroud)
这是一个声明性和优雅的解决方案.
cee*_*yoz 34
这样的事情(stat
首先使用模块收集有关它的数据,然后使用条件过滤)应该工作:
- stat: path=/etc/nologin
register: p
- name: create fake 'nologin' shell
file: path=/etc/nologin state=touch owner=root group=sys mode=0555
when: p.stat.exists is defined and not p.stat.exists
Run Code Online (Sandbox Code Playgroud)
您也可以利用该changed_when
功能.
Ley*_*nos 26
另一个选项,使用命令模块:
- name: Create file
command: touch /path/to/file
args:
creates: /path/to/file
Run Code Online (Sandbox Code Playgroud)
'creates'参数确保在文件存在时不执行此操作.
Rav*_*rni 14
文件模块提供了在不修改时间的情况下触摸文件的方法。
- name: Touch again the same file, but dont change times this makes the task idempotent
file:
path: /etc/foo.conf
state: touch
mode: u+rw,g-wx,o-rwx
modification_time: preserve
access_time: preserve
Run Code Online (Sandbox Code Playgroud)
参考:https : //docs.ansible.com/ansible/latest/modules/file_module.html
All*_*ckt 13
基于接受的答案,如果您希望在每次运行时检查文件的权限,并且如果文件存在则相应地更改文件,或者只是创建文件(如果文件不存在),您可以使用以下内容:
- stat: path=/etc/nologin
register: p
- name: create fake 'nologin' shell
file: path=/etc/nologin
owner=root
group=sys
mode=0555
state={{ "file" if p.stat.exists else "touch"}}
Run Code Online (Sandbox Code Playgroud)
小智 10
file: path=/etc/nologin state=touch
完全相当于触摸(1.4+中的新功能) - 如果您不想更改文件时间戳,请使用stat.