使用Ansible创建空文件的最简单方法是什么?我知道我可以将一个空文件保存到files
目录中,然后将其复制到远程主机,但我觉得有点不满意。
另一种方法是触摸远程主机上的文件:
- name: create fake 'nologin' shell
file: path=/etc/nologin state=touch owner=root group=sys mode=0555
但是每次文件都会被触摸,在日志中显示为黄线,这也不能令人满意......
这个简单的问题有更好的解决方案吗?
答案 0 :(得分:143)
文件模块的文档说
如果
state=file
,如果文件不存在,则不会创建该文件,如果您想要该行为,请参阅副本或模板模块。
因此我们使用复制模块,仅当文件尚不存在时才使用force=no
创建新的空文件(如果文件存在,则保留其内容)。
- name: ensure file exists
copy:
content: ""
dest: /etc/nologin
force: no
group: sys
owner: root
mode: 0555
这是一个声明性和优雅的解决方案。
答案 1 :(得分:33)
这样的事情(首先使用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
您也可以使用changed_when
功能。
答案 2 :(得分:25)
另一个选项,使用命令模块:
- name: Create file
command: touch /path/to/file
args:
creates: /path/to/file
'creates'参数确保在文件存在时不执行此操作。
答案 3 :(得分:11)
根据接受的答案,如果您希望在每次运行时检查文件的权限,并且如果文件存在则相应地更改文件,或者只是创建文件(如果文件不存在),您可以使用以下内容:
- 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"}}
答案 4 :(得分:9)
file: path=/etc/nologin state=touch
完全相当于触摸(1.4+中的新功能) - 如果您不想更改文件时间戳,请使用stat。
答案 5 :(得分:3)
事实证明,我没有足够的声誉将此作为评论,这将是一个更合适的地方:
重新。 AllBlackt的回答是,如果你更喜欢Ansible的多线格式,你需要调整state
的引用(我花了几分钟来解决这个问题,所以希望这能加快其他人的速度),
- 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" }}'
答案 6 :(得分:0)
为了使用ad-hoc命令在远程计算机中创建文件
ansible client -m file -a"dest=/tmp/file state=touch"
如果我错了请纠正我
答案 7 :(得分:0)
如果文件不存在则更改。创建空文件。
- name: create fake 'nologin' shell
file:
path: /etc/nologin
state: touch
register: p
changed_when: p.diff.before.state == "absent"
答案 8 :(得分:0)
文件模块提供了无需修改文件时间即可触摸文件的方法。
- 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
参考: https://docs.ansible.com/ansible/latest/modules/file_module.html
答案 9 :(得分:0)
两个答案的组合,略有不同。创建文件或更新权限后,将检测到代码已更改。
- name: Touch again the same file, but dont change times this makes the task idempotent
file:
path: /etc/foo.conf
state: touch
mode: 0644
modification_time: preserve
access_time: preserve
changed_when: >
p.diff.before.state == "absent" or
p.diff.before.mode|default("0644") != "0644"
,以及还会更正所有者和组的版本,并在其更正这些内容时将其检测为已更改:
- name: Touch again the same file, but dont change times this makes the task idempotent
file:
path: /etc/foo.conf
state: touch
state: touch
mode: 0644
owner: root
group: root
modification_time: preserve
access_time: preserve
register: p
changed_when: >
p.diff.before.state == "absent" or
p.diff.before.mode|default("0644") != "0644" or
p.diff.before.owner|default(0) != 0 or
p.diff.before.group|default(0) != 0