ansible find:从寄存器中获取目录的路径

ansible find:从寄存器中获取目录的路径

在此先感谢大家的帮助。我似乎不知道自己做错了什么,所以我才寻求帮助。我希望使用 ansible 搜索文件夹,找到该文件夹​​并将其内容复制到另一个目录。这是我目前所拥有的。我想我被困在了 with_items 部分。

- name: Folder find and file copy
  hosts: "{{ target }}"
  gather_facts: no

  vars:
    search_path: ~/oldfolder/backups
    id: patient_1234
    dest: "~/newfolder/{{ id }}"

  tasks:

    - name: Find directory using patterns
      ansible.builtin.find:
        paths: "{{ search_path }}/"
        file_type: directory
        patterns: "{{ id[:-4] }}*"
        recurse: yes
      register: find_matches

    - name: Print return information from the previous task
      ansible.builtin.debug:
        var: find_matches.files[0].path
      when: find_matches is defined

    - name: Copy from backup to destination
      ansible.builtin.copy:
        src: "{{ item.path }}"
        dest: "{{ dest }}"
        remote_src: yes
      with_items: "{{ find_matches.files }}"

答案1

- name: Folder find and file copy
  hosts: "{{ target }}"
  gather_facts: no

  vars:
    search_path: ~/oldfolder/backups
    id: patient_1234
    dest: "~/newfolder/{{ id }}"

  tasks:

    - name: Find directory using patterns
      ansible.builtin.find:
        paths: "{{ search_path }}/"
        file_type: directory
        patterns: "{{ id[:-4] }}*"
        recurse: yes
      register: find_matches

    - name: Print return information from the previous task
      ansible.builtin.debug:
        var: find_matches.files[0].path
      when: find_matches is defined

    - name: Copy from backup to destination
      ansible.builtin.copy:
        src: "{{ item.path }}/."
        dest: "{{ dest }}"
        remote_src: yes
      with_items: "{{ find_matches.files }}"

另外一个选择

   - name: Copy from backup to destination
     ansible.builtin.shell: 'cp -r {{ item.path }}/. {{ dest }}'
     with_items: "{{ find_matches.files }}"

答案2

更改最后一个复制块

  • 名称:从备份复制到目的地 ansible.builtin.copy:src:“{{ item.path }}/。” dest:“{{ dest }}” remote_src:是 with_items:“{{ find_matches.files }}”

确保 src 中没有 /.

  • 名称:从备份复制到目的地 ansible.builtin.copy:src:“{{ item.path }}” dest:“{{ dest }}” remote_src:是 with_items:“{{ find_matches.files }}”

相关内容