Ansible para renomear um arquivo somente se existir

Ansible para renomear um arquivo somente se existir

Preciso renomear /jp/Test para /jp/test apenas se /jp/Test existir, caso contrário, não preciso executar esta tarefa. se ambos existirem, preciso mesclar ambos em/jp/test

Eu recebo o erro abaixo

{"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

Livro de cantadas:

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

Responder1

Abaixo está uma solução funcional. Observe que você pode querer definir o proprietário/permissões no arquivo criado por blockinfilee isso blockinfileadicionará âncoras de inserção ao redor do texto inserido no arquivo de destino. Ambos podem ser configurados (vejaos documentos)

- 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

O erro que você tem aí é devido à variável de loop não ser uma lista, mas um objeto de dicionário. Quando você invoca loop: "{{ jpresult.results }}"(observe, vejaloopcontrawith_) o valor de {{ item }}para cada iteração do loop é um único item na lista, em vez da lista completa. Para acessar o valor stat do índice do loop atual você pode usar item.stat, ou para acessar o stat de uma iteração diferente que você pode usar jpresult.results.N.stat(onde Nestá o índice que você deseja acessar).

informação relacionada