존재하는 경우에만 파일 이름을 바꿀 수 있습니다.

존재하는 경우에만 파일 이름을 바꿀 수 있습니다.

/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

아래는 작동하는 솔루션입니다. 에서 생성한 파일에 대한 소유자/권한을 설정하려고 할 수 있으며 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 }}"(참고, 참조loopwith_{{ item }}) 루프의 각 반복에 대한 값은 전체 목록이 아닌 목록의 단일 항목입니다. 현재 루프 인덱스의 통계 값에 액세스하려면 를 사용 item.stat하거나 다른 반복의 통계에 액세스하려면 사용할 수 있습니다 jpresult.results.N.stat( N액세스하려는 인덱스는 어디에 있습니까).

관련 정보