存在する場合にのみファイルの名前を変更する Ansible

存在する場合にのみファイルの名前を変更する Ansible

/jp/Test が存在する場合のみ、/jp/Test を /jp/test に名前変更する必要があります。そうでない場合は、このタスクを実行する必要はありません。両方が存在する場合は、両方を /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

以下は実用的な解決策です。 によって作成されたファイルの所有者/権限を設定するとblockinfileblockinfile挿入先のファイルに挿入されたテキストの周囲に挿入アンカーが追加されることに注意してください。これらは両方とも設定できます(ドキュメント

- 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 }}"(注:loopwith_) ループの各反復における の値は{{ item }}、完全なリストではなく、リスト内の単一の項目です。現在のループ インデックスの統計値にアクセスするには を使用し、別の反復の統計値にアクセスするには(はアクセスするインデックスです)item.statを使用します。jpresult.results.N.statN

関連情報