How to check if a file exists in Ansible?

后端 未结 11 1823
旧巷少年郎
旧巷少年郎 2020-12-23 02:35

I have to check whether a file exists in /etc/. If the file exists then I have to skip the task. Here is the code I am using:

- name: checking th         


        
相关标签:
11条回答
  • 2020-12-23 03:18

    This can be achieved with the stat module to skip the task when file exists.

    - hosts: servers
      tasks:
      - name: Ansible check file exists.
        stat:
          path: /etc/issue
        register: p
      - debug:
          msg: "File exists..."
        when: p.stat.exists
      - debug:
          msg: "File not found"
        when: p.stat.exists == False
    
    0 讨论(0)
  • 2020-12-23 03:19
    vars:
      mypath: "/etc/file.txt"
    
    tasks:
      - name: checking the file exists
        command: touch file.txt
        when: mypath is not exists
    
    0 讨论(0)
  • 2020-12-23 03:19

    If you just want to make sure a certain file exists (f.ex. because it shoud be created in a different way than via ansible) and fail if it doesn't, then you can do this:

    - name: sanity check that /some/path/file exists
      command: stat /some/path/file
      check_mode: no # always run
      changed_when: false # doesn't change anything
    
    0 讨论(0)
  • 2020-12-23 03:20

    You can use Ansible stat module to register the file, and when module to apply the condition.

    - 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
    
    0 讨论(0)
  • 2020-12-23 03:23

    A note on relative paths to complement the other answers.

    When doing infrastructure as code I'm usually using roles and tasks that accept relative paths, specially for files defined in those roles.

    Special variables like playbook_dir and role_path are very useful to create the absolute paths needed to test for existence.

    0 讨论(0)
提交回复
热议问题