仅当文件不存在时才是Ansible模板

时间:2015-07-02 22:20:48

标签: ansible

如果相应的文件不存在,我会尝试仅设置模板。我目前有以下总是创建文件。

- name: Setup templates
  template: src={{ item }} dest={{ item | basename | regex_replace('\.j2','') }}
  with_fileglob: ../templates/*.j2

所以,如果有三个模板

  • t1.j2
  • t2.j2
  • t3.j3

目的地中存在两个文件

  • T1
  • T3

我只想运行并复制t2.j2模板..

我已经看到了使用state命令注册变量的方法,但是没有想出如何使用with_fileglob来做这个。

2 个答案:

答案 0 :(得分:2)

您可以使用stat模块来确定有关该文件的信息:

---

- name: File exist?
  stat: path=/tmp/not-exist
  ignore_errors: true
  register: myfile

- debug: var=myfile

- name: Setup templates
  template: src={{ item }} dest={{ item | basename | regex_replace('\.j2','') }}
  with_fileglob: ../templates/*.j2
  when: myfile.stat.exists == false

- debug: msg="Print if file exist"
  when: myfile.stat.exists == true

此设置将跳过上一个任务,但将执行模板。

答案 1 :(得分:1)

原来你可以通过一个力量参数。如果文件不存在,那只会复制模板。

- name: Setup templates
  template: src={{ item }} dest={{ item | basename | regex_replace('\.j2','') }} force=no
  with_fileglob: ../templates/*.j2
相关问题