我必须检查/etc/中是否存在一个文件。如果文件存在,那么我必须跳过该任务。 这是我正在使用的代码:

- name: checking the file exists
  command: touch file.txt
  when: $(! -s /etc/file.txt)

当前回答

你可以使用Ansible的统计模块来注册文件,当模块来应用条件。

- name: Register file
      stat:
        path: "/tmp/test_file"
      register: file_path

- name: Create file if it doesn't exists
      file: 
        path: "/tmp/test_file"
        state: touch
      when: file_path.stat.exists == False

其他回答

发现调用stat很慢,并且收集了很多文件存在检查不需要的信息。 在花了一些时间寻找解决方案后,我发现了以下解决方案,它的工作速度更快:

- raw: test -e /path/to/something && echo -n true || echo -n false
  register: file_exists

- debug: msg="Path exists"
  when: file_exists.stdout == "true"

关于相对路径的注释,以补充其他答案。

当把基础设施作为代码使用时,我通常使用接受相对路径的角色和任务,特别是对于在这些角色中定义的文件。

像playbook_dir和role_path这样的特殊变量对于创建测试存在性所需的绝对路径非常有用。

我发现这样做很烦人,而且容易出错。存在类型检查。例如,它们需要额外的注意才能使检查模式(——check)工作。

这里的许多答案表明

获取和注册 当寄存器表达式为真时应用

然而,有时这是一种代码气味,所以总是寻找更好的方法来使用Ansible,特别是使用正确的模块有许多优点。如。

- name: install ntpdate
  package:
    name: ntpdate

or

- file:
    path: /etc/file.txt
    owner: root
    group: root
    mode: 0644

但是当不能使用一个模块时,也要研究一下是否可以注册和检查前一个任务的结果。如。

# jmeter_version: 4.0 
- name: Download Jmeter archive
  get_url:
    url: "http://archive.apache.org/dist/jmeter/binaries/apache-jmeter-{{ jmeter_version }}.tgz"
    dest: "/opt/jmeter/apache-jmeter-{{ jmeter_version }}.tgz"
    checksum: sha512:eee7d68bd1f7e7b269fabaf8f09821697165518b112a979a25c5f128c4de8ca6ad12d3b20cd9380a2b53ca52762b4c4979e564a8c2ff37196692fbd217f1e343
  register: download_result

- name: Extract apache-jmeter
  unarchive:
    src: "/opt/jmeter/apache-jmeter-{{ jmeter_version }}.tgz"
    dest: "/opt/jmeter/"
    remote_src: yes
    creates: "/opt/jmeter/apache-jmeter-{{ jmeter_version }}"
  when: download_result.state == 'file'

注意when:和created: so——check不会出错

我之所以提到这一点,是因为这些不太理想的做法通常是成对出现的,即没有apt/yum包,所以我们必须1)下载和2)解压缩

希望这能有所帮助

你可以使用Ansible的统计模块来注册文件,当模块来应用条件。

- name: Register file
      stat:
        path: "/tmp/test_file"
      register: file_path

- name: Create file if it doesn't exists
      file: 
        path: "/tmp/test_file"
        state: touch
      when: file_path.stat.exists == False
vars:
  mypath: "/etc/file.txt"

tasks:
  - name: checking the file exists
    command: touch file.txt
    when: mypath is not exists