迭代未知数量的自定义 Ansible 事实

迭代未知数量的自定义 Ansible 事实

我编写了一些自定义事实,我将其作为任务中模块的值引用。当我有 1 个自定义事实时,运行任务没有问题,但问题是,当我有未知数量的事实并且我想为每个事实运行任务时,我该怎么办?我有以下事实:

"ansible_facts": {
    "ansible_local": {
        "facts": {
            "finance": {
                "files": {
                    "file1": {
                        "dest": "/tmp/dir1",
                        "path": "/etc/finance/file1"
                    },
                    "file2": {
                        "dest": "/tmp/dir2",
                        "path": "/etc/finance/file2"
                    }
                }
            }
        }
    }
},

这是我的任务的代码:

- name: Copy files
  copy:
    src: "/tmp/file1/{{ ansible_local.facts.finance.files.file1.path }}"
    dest: "/ghostcache/{{ ansible_local.facts.finance.files.file1.dest }}/"
    remote_src: yes

鉴于文件下的项目数量未知,我该如何迭代“文件”下的所有项目并获取两个值(目标和路径)并将它们作为值放入复制模块?我可能只有 1 个,即 file1 或者可能有 file1...fileN。

谢谢 !

答案1

这是您正在寻找的代码吗?

- hosts: localhost                                                                           
  become: yes                                                                                
  become_method: sudo                                                                        
  become_user: root                                                                          
  vars:                                                                                      
    facts:                                                                                     
      finance:                                                                           
        files:                                                                               
          - file1:                                                                           
              dest: "/tmp/dir1"                                                              
              path: "/etc/finance/file1"                                               
          - file2:                                                                           
              dest: "/tmp/dir2"                                                              
              path: "/etc/finance/file2"                                               
  tasks:                                                                                     
    - debug:                                                                                 
        msg: "src: {{ item.value.path}} dest: {{ item.value.dest }}"                         
      with_dict: "{{ facts.finance.files }}"                                               

ansible-playbook list-dict.yml 
ok: [localhost] => (item=None) => {
"msg": "src: /etc/finance/file1 dest: /tmp/dir1" }
ok: [localhost] => (item=None) => {
"msg": "src: /etc/finance/file2 dest: /tmp/dir2" }

相关内容