Ansible—判断文件或文件夹是否存在

概述

Ansible内置的stat模块用于检索文件或文件系统的状态。

1、host.ini

[minio]
192.168.3.36             ansible_su_pass=root_password host_name=minio1.dokbok.com
192.168.3.37             ansible_su_pass=root_password host_name=minio2.dokbok.com
192.168.3.38             ansible_su_pass=root_password host_name=minio3.dokbok.com

2、deploy-minio.yaml

---
- hosts: minio
  gather_facts: no
  remote_user: cloud
  become: yes
  become_method: su
  become_user: root

  vars:
    vpn_local_ip: "{{ ansible_eth0['ipv4']['address'] }}"
    hostnames: "{{ lookup('file','hosts') }}"
  tasks:
  - name: check minio setup file exists
    stat:
      path: "/root/minio.deb"
    register: minio_file_exists
...
  • path:要检索的文件或对象的绝对路径
  • register:从一个Ansible的任务的输出定义一个变量。

下面我们使用debug模块,判断文件是否存在,下面是该实例的完整配置:

---
- hosts: minio
  gather_facts: no
  remote_user: cloud
  become: yes
  become_method: su
  become_user: root

  vars:
    vpn_local_ip: "{{ ansible_eth0['ipv4']['address'] }}"
    hostnames: "{{ lookup('file','hosts') }}"
  tasks:
  - name: check minio setup file exists
    stat:
      path: "/root/minio.deb"
    register: minio_file_exists
  - name: show minio_file_exists
    debug:
      msg: "minio file exists"
    when: minio_file_exists.stat.exists and minio_file_exists.stat.isreg

留下评论

您的邮箱地址不会被公开。 必填项已用 * 标注