gpt4 book ai didi

ansible - 如何通过 Ansible 创建嵌套目录结构

转载 作者:行者123 更新时间:2023-12-05 01:50:45 24 4
gpt4 key购买 nike

最后,我找到了一个关于如何创建与 Bash 命令等效的嵌套目录结构的解决方案

mkdir -p jenkins/cache/{war,tmp,workspace}

我的剧本

---
- name: Create directories
hosts: localhost
vars:
dirs: [
jenkins, # for one elemnt it can be string
[ cache ],
[ war, tmp, workspace ]
]
base_directory: ~/tmp

tasks:
- debug:
msg="{{base_directory}}/{{item.0}}/{{item.1}}/{{item.2}}"
with_nested: "{{ dirs | list }}"

它产生:

PLAY [Create directories] **********************************************************************************************************************************

TASK [debug] ***********************************************************************************************************************************************
ok: [localhost] => (item=['jenkins', 'cache', 'war']) => {
"msg": "~/tmp/jenkins/cache/war"
}
ok: [localhost] => (item=['jenkins', 'cache', 'tmp']) => {
"msg": "~/tmp/jenkins/cache/tmp"
}
ok: [localhost] => (item=['jenkins', 'cache', 'workspace']) => {
"msg": "~/tmp/jenkins/cache/workspace"
}

PLAY RECAP *************************************************************************************************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

但是如果我想使用更多(或更少)的嵌套级别,就会出现问题。我需要更多(或更少)item.X
如何在 Ansible 中动态执行?

我知道有社区模块filetree ,这可能会有帮助,但我不想或不需要使用它。

最佳答案

您绝对可以使用 with_nested 并使用 / join 二级列表。

所以,像这样的任务会做:

- debug:
msg: >-
{{ base_directory }}/
{{- item | join('/') }}
with_nested: "{{ dirs }}"

给定任务:

- debug:
msg: >-
{{ base_directory }}/
{{- item | join('/') }}
with_nested: "{{ dirs }}"
vars:
dirs:
- jenkins
- - cache
- - war
- tmp
- workspace
base_directory: ~/tmp

这会产生:

ok: [localhost] => (item=['jenkins', 'cache', 'war']) => 
msg: ~/tmp/jenkins/cache/war
ok: [localhost] => (item=['jenkins', 'cache', 'tmp']) =>
msg: ~/tmp/jenkins/cache/tmp
ok: [localhost] => (item=['jenkins', 'cache', 'workspace']) =>
msg: ~/tmp/jenkins/cache/workspace

关于ansible - 如何通过 Ansible 创建嵌套目录结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72895360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com