Ansible playbook文件选择任务
Ansible playbook file selection task
这可能违反最佳实践,但使用 Ansible 剧本,是否可以从一项任务中获取文件列表,然后向用户提示 select 将其中一个文件传递到变量中?
例如:
Choose file to select:
1. file1.txt
2. file2.txt
3. file3.txt
> 1
剧本理论上会暂停以等待用户输入,然后将生成的文件 selection 传递到一个变量中以在未来的任务中使用。
非常感谢。
使用pause。例如,给定文件
shell> tree files
files
├── file1.txt
├── file2.txt
└── file3.txt
0 directories, 3 files
下面的剧本
shell> cat playbook.yml
- hosts: localhost
tasks:
- find:
path: files
register: result
- set_fact:
my_files: "{{ result.files|map(attribute='path')|list|sort }}"
- pause:
prompt: |
Choose file to select:
{% for file in my_files %}
{{ loop.index }} {{ file }}
{% endfor %}
register: result
- debug:
msg: "selected file: {{ my_files[result.user_input|int - 1] }}"
给出(选择第二文件并输入'2
shell> ansible-playbook playbook.yml
PLAY [localhost] ****
TASK [find] ****
ok: [localhost]
TASK [set_fact] ****
ok: [localhost]
TASK [pause] ****
[pause]
Choose file to select:
1 files/file1.txt
2 files/file2.txt
3 files/file3.txt
:
ok: [localhost]
TASK [debug] ****
ok: [localhost] => {
"msg": "selected file: files/file2.txt"
}
PLAY RECAP ****
localhost: ok=4 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
这可能违反最佳实践,但使用 Ansible 剧本,是否可以从一项任务中获取文件列表,然后向用户提示 select 将其中一个文件传递到变量中?
例如:
Choose file to select:
1. file1.txt
2. file2.txt
3. file3.txt
> 1
剧本理论上会暂停以等待用户输入,然后将生成的文件 selection 传递到一个变量中以在未来的任务中使用。
非常感谢。
使用pause。例如,给定文件
shell> tree files
files
├── file1.txt
├── file2.txt
└── file3.txt
0 directories, 3 files
下面的剧本
shell> cat playbook.yml
- hosts: localhost
tasks:
- find:
path: files
register: result
- set_fact:
my_files: "{{ result.files|map(attribute='path')|list|sort }}"
- pause:
prompt: |
Choose file to select:
{% for file in my_files %}
{{ loop.index }} {{ file }}
{% endfor %}
register: result
- debug:
msg: "selected file: {{ my_files[result.user_input|int - 1] }}"
给出(选择第二文件并输入'2 shell> ansible-playbook playbook.yml
PLAY [localhost] ****
TASK [find] ****
ok: [localhost]
TASK [set_fact] ****
ok: [localhost]
TASK [pause] ****
[pause]
Choose file to select:
1 files/file1.txt
2 files/file2.txt
3 files/file3.txt
:
ok: [localhost]
TASK [debug] ****
ok: [localhost] => {
"msg": "selected file: files/file2.txt"
}
PLAY RECAP ****
localhost: ok=4 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0