仅当文件存在时才重命名文件

仅当文件存在时才重命名文件

仅当 /jp/Test 存在时,我才需要将 /jp/Test 重命名为 /jp/test,否则我不需要执行此任务。如果 Both 都存在,我需要将两者合并到 /jp/test 中

我收到以下错误

{"msg": "The conditional check 'item.1.stat.exists == false and item.2.stat.exists == true' failed. The error was: error while evaluating conditional (item.1.stat.exists == false and item.2.stat.exists == true): dict object has no element 1\n\nThe error appears to be in

剧本:

hosts: test
gather_facts: false
vars:
  hostsfiles:
    - /jp/test
    - /jp/Test
    


  tasks:
    - name: Check if file exists
      stat:
        path: "{{ item}}"
      with_items: "{{ hostsfiles }}"
      register: jpresult

    - name: test
      shell: mv "{{item.2.stat.path}}" /jp/test
      with_items:
        - "{{ jpresult.results }}"
      when: item.1.stat.exists == false and item.2.stat.exists == true

答案1

以下是一个可行的解决方案。请注意,您可能需要设置由 创建的文件的所有者/权限blockinfile,这blockinfile将在目标文件中插入的文本周围添加插入锚点。这两者都可以配置(请参阅文档

- name: Some very cool play
  hosts: test
  gather_facts: false
  vars:
    destination_path: /jp/test
    legacy_path: /jp/Test
  tasks:
    - name: Check if legacy file exists
      stat:
        path: "{{ legacy_path }}"
      register: legacy_status

    - name: Move contents of legacy file to destination file
      when: legacy_status.stat.exists is true
      block:
        # Note that there is currently no module to read the contents of a
        # file on the remote, so using "cat" via command is the best alternative
        - name: Read contents of legacy file
          command:
            cmd: cat {{ legacy_path }}
          register: legacy_contents
          changed_when: false

        - name: Add contents of legacy file to destination file
          blockinfile:
            path: "{{ destination_path }}"
            state: present
            block: "{{ legacy_contents.stdout }}"
            # This ensures the file is created if it does not exist, 
            # saving an extra task to rename the file if necessary
            create: true  

    - name: Remove legacy file
      file:
        path: "{{ legacy_path }}"
        state: absent

出现此错误是因为循环变量不是列表,而是字典对象。调用时loop: "{{ jpresult.results }}"(注意,请参阅loop对比with_{{ item }})循环每次迭代的值都是列表中的单个项目,而不是完整列表。要访问当前循环索引的统计值,您可以使用item.stat,或者要访问不同迭代的统计值,您可以使用jpresult.results.N.stat(其中N是您要访问的索引)。

相关内容