![ansible 从寄存器变量打印文件夹路径](https://linux22.com/image/783930/ansible%20%E4%BB%8E%E5%AF%84%E5%AD%98%E5%99%A8%E5%8F%98%E9%87%8F%E6%89%93%E5%8D%B0%E6%96%87%E4%BB%B6%E5%A4%B9%E8%B7%AF%E5%BE%84.png)
我正在尝试打印具有多个值的寄存器变量的路径,但是我只能打印特定值。我怎样才能打印多个值?
---
- name: find directories
find:
paths: "{{ item }}"
recurse: yes
file_type: directory
use_regex: yes
patterns:
- '.*log.*'
- '.*sbin.*'
with_items:
- /var
- /usr
register: folders_info
- name: print folders found
debug:
msg: "{{ item }}"
with_items: "{{ folders_info.results[0].files[0].path }}"
输出:
TASK [filebeat_confirm : find directories] ***********************************************************************************************************************************************
ok: [10.0.1.243] => (item=/var)
ok: [10.0.1.243] => (item=/usr)
TASK [filebeat_confirm : print folders found] ********************************************************************************************************************************************
ok: [10.0.1.243] => (item=/var/log) => {
"msg": "/var/log"
}
答案1
问:“仅打印寄存器变量的路径。”
答:下面的声明可以满足您的要求
my_dirs: "{{ folders_info.results|json_query('[].files[].path') }}"
例子
给定测试树
shell> tree /tmp/test
/tmp/test
├── usr
│ └── bin
│ └── dosepsbin
└── var
├── db
├── lib
│ └── dkms
│ ├── test1
│ │ └── log
│ ├── test2
│ │ └── log
│ └── test3
│ └── log
├── local
└── log
15 directories, 0 files
剧本
shell> cat pb.yml
- hosts: localhost
become: true
vars:
my_dirs: "{{ folders_info.results|json_query('[].files[].path') }}"
tasks:
- name: find directories
find:
paths: "{{ item }}"
recurse: true
file_type: directory
use_regex: true
patterns:
- '.*log.*'
- '.*sbin.*'
loop:
- /tmp/test/var
- /tmp/test/usr
register: folders_info
- debug:
var: my_dirs
给出
shell> ansible-playbook pb.yml
PLAY [localhost] ******************************************************************************************************************************************************************************
TASK [find directories] ***********************************************************************************************************************************************************************
ok: [localhost] => (item=/tmp/test/var)
ok: [localhost] => (item=/tmp/test/usr)
TASK [debug] **********************************************************************************************************************************************************************************
ok: [localhost] =>
my_dirs:
- /tmp/test/var/log
- /tmp/test/var/lib/dkms/test1/log
- /tmp/test/var/lib/dkms/test2/log
- /tmp/test/var/lib/dkms/test3/log
- /tmp/test/usr/bin/dosepsbin
PLAY RECAP ************************************************************************************************************************************************************************************
localhost: ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0