查找并复制 Ansible 中位置不固定的文件

Find and Copy a file where the location is not fixed in Ansible

我正在尝试从 machineconfig 目录中查找具有模式 *-chrony-configuration.yaml 的文件并将其复制到 manifests 目录。

machineconfig 的位置因用户而异

- name: Find machineconfig files generated from helpernode
  find:
    paths: "machineconfig/"
    patterns: "*-chrony-configuration.yaml"
  register: machine_file

- name: Copy machineconfig files generated from helpernode
  copy:
    src: "{{ item.path }}"
    dest: "{{ workdir }}/manifests"
    remote_src: yes
  with_items:
    - "{{ machine_file.files }}"

以上代码错误给出

"msg": "machineconfig/ was skipped as it does not seem to be a valid directory or it cannot be accessed\n"

ansible 有没有找到文件路径并使用它来生成副本的方法?

如果你的路径是 /root/machineconfig/home/machineconfig,你可以做什么, 是向 paths 参数提供一个列表,正如文档所建议的那样。

给定任务:

- find:
    paths: 
      - /root/machineconfig
      - /home/machineconfig
    patterns: "*-chrony-configuration.yaml"
  register: machine_file

这将列出您要查找的文件,并对不存在的文件夹发出简单警告。


使用剧本:

- hosts: localhost
  gather_facts: yes
  gather_subset: 
    - min

  tasks:
    - find:
        paths: 
          - /root/machineconfig
          - /home/machineconfig
        patterns: "*-chrony-configuration.yaml"
      register: machine_file

    - debug:
        var: machine_file.files | map(attribute='path')

这产生:

TASK [find] ****************************************************************
[WARNING]: Skipped '/root/machineconfig' path due to this access issue:
'/root/machineconfig' is not a directory
ok: [localhost]

TASK [debug] ***************************************************************
ok: [localhost] => 
  machine_file.files | map(attribute='path'):
  - /home/machineconfig/foobar-chrony-configuration.yaml

如果 playbook 的 remote_user 是为其创建 machineconfig 文件夹的用户,那么您可以使用 ansible_env.HOME 事实来获取该用户的主目录用户。

所以,这将使您的复制任务看起来像:

- name: Find machineconfig files generated from helpernode
  find:
    paths: "{{ ansible_env.HOME }}/machineconfig/"
    patterns: "*-chrony-configuration.yaml"
  register: machine_file
  become: no

请注意:您需要为此收集一些最少的事实,才能工作:

- hosts: foobar
  gather_facts: yes
  gather_subset: 
    - min