Linux

迭代未知數量的自定義 Ansible Facts

  • June 26, 2018

我編寫了一些自定義事實,我將它們作為任務中模組的值引用。當我有 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 。

謝謝 !

這是您要查找的程式碼嗎?

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

引用自:https://serverfault.com/questions/918063