【问题标题】:Ansible to execute a task only when multiple files exist仅当存在多个文件时才执行任务
【发布时间】:2020-11-26 08:29:14
【问题描述】:

我只想在多个文件存在时执行任务。如果只存在单个文件,我需要忽略此任务。我怎样才能做到这一点。 我无法通过以下剧本实现

---
- name: Standardize
  hosts: test
  gather_facts: false
  vars:
    file_vars:
      - {id: 1, name: /etc/h_cm}
      - {id: 2, name: /etc/H_CM}

  tasks:
    - block:
      - name: Check if both exists
        stat:
          path: "{{ item.name }}"
        with_items: "{{ file_vars }}"
        register: cm_result

      - name: Move both files
        shell: mv "{{ item.item }}" /tmp/merged
        with_items: "{{ cm_result.results }}"
        when: item.stat.exists

【问题讨论】:

    标签: linux file ansible ansible-facts


    【解决方案1】:

    检查两者是否存在任务后,您可以添加一个这样的设置事实任务:

      - name: set facts
        set_fact:
          files_exist: "{{ (files_exist | default([])) + [item.stat.exists] }}"
        with_items: "{{ cm_result.results }}"
    

    然后您将移动文件任务更改为:

      - name: Move both files
        debug:
          msg: "{{ item.stat.exists }}"
        with_items: "{{ cm_result.results }}"
        when: false not in files_exist
    

    【讨论】:

      【解决方案2】:
      You have to specify shell: mv "{{ item.item.name }}" /tmp/merged insted of shell: mv "{{ item.item }}" /tmp/merged
      
      
      Check the below works?:
      
      - name: Standardize
        hosts: test
        gather_facts: false
        become: yes ## If needed
        vars:
          file_vars:
            - {id: 1, name: /etc/h_cm}
            - {id: 2, name: /etc/H_CM}
      
        tasks:
          - block:
            - name: Check if both file exists
              stat:
                path: "{{ item.name }}"
              with_items: "{{ file_vars }}"
              register: cm_result
      
            - debug:
                var: item.stat.exists
              loop: "{{ cm_result.results }}"
      
            - name: Crate a dummy list
              set_fact:
                file_state: []
      
            - name: Add true to list if file exists
              set_fact: 
                file_state: "{{ file_state }} + ['{{ item.stat.exists }}']"
              loop: "{{ cm_result.results }}"
              when: item.stat.exists == true
      
            - name: Move both files
              shell: mv "{{ item.item.name }}" /tmp/merged
              loop: "{{ cm_result.results }}"
              when: file_state|length > 1
      

      【讨论】:

      • 我的意思是说 /etc/h_cm 和 /etc/H_CM 应该存在,如果它们都存在,那么我需要执行移动两个文件任务
      • 我想合并两个文件而不是 mv。你能帮忙吗?例如: cat /etc/h_cm /etc/H_CM |排序-u | uniq -u > /etc/h_cm
      • 它没有用。它只是在合并文件中有 /etc/H_CM 的内容,但没有 /etc/h_cm 的内容
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-01-12
      • 2015-09-09
      • 2017-12-22
      • 1970-01-01
      • 2021-02-12
      • 2014-05-12
      • 2014-04-23
      相关资源
      最近更新 更多