我具有以下目录结构:
parent_dir/
├── subdir_1
├── subdir_2
└── subdir_3
子目录没有固定的名称,可以有任意数量的名称。
如何使ansible为每个子目录运行任务?
(任何任务都可以,最终每个目录都将是一个要安装的python软件包,但这对于此问题的上下文并不重要)
答案 0 :(得分:1)
这是我设法提供的解决方案,也许lookups有一种更简洁的方法可以在单个任务中实现。
复制粘贴以下代码将创建一个目录结构,其中包含执行所需操作的最小ansible剧本。 (已在Ubuntu / dash上测试)
mkdir action_per_dir
cd action_per_dir
mkdir -p parent_dir/subdir_1 parent_dir/subdir_2 parent_dir/subdir_3
cat > action_per_dir.yml << "EOF"
---
# Gets all the directories and stores all the return values of `find`
# into the results_of_find
# The return value will consist of:
# https://docs.ansible.com/ansible/latest/modules/find_module.html#return-values
- hosts: localhost
tasks:
- name: Get all dirs
find:
paths: parent_dir
file_type: directory
register: result_of_find
# We're interested only in the `files` part of results of find.
# In pseudo code what's happening here is:
# for each item in result_of_find.files:
# print item.path
#
# The output will be very verbose but for debugging purposes it can be filtered
# ansible-playbook action_per_dir.yml | grep msg
- name: Print all the dirs
debug:
msg: "{{ item.path }}"
with_items: "{{ result_of_find.files }}"
EOF
之后,只需要运行它即可:
ansible-playbook action_per_dir.yml | grep msg