Ansible playbook 文件选择任务

问题描述 投票:0回答:1

这可能违反最佳实践,但使用 Ansible 剧本,是否可以从一项任务获取文件列表,然后提示用户选择其中一个文件以传递到变量中?

例如:

Choose file to select:
1. file1.txt
2. file2.txt
3. file3.txt
> 1

理论上,剧本会暂停以等待用户输入,然后将结果文件选择传递到变量中以在将来的任务中使用。

提前非常感谢。

ansible prompt
1个回答
2
投票

使用暂停。例如,给定文件

shell> tree files
files
├── file1.txt
├── file2.txt
└── file3.txt

0 directories, 3 files

更新

剧本

shell> cat playbook.yml 
- hosts: localhost

  vars:

    dir: files
    my_files: "{{ q('fileglob', dir ~ '/*')|map('basename') }}"
    selected_file: "{{ dir }}/{{ my_files[result.user_input|int - 1] }}"

  tasks:

    - pause:
        prompt: |-
          Choose file to select:
          {% for file in my_files %}
          {{ loop.index }} {{ dir }}/{{ file }}
          {% endfor %}
      register: result

    - debug:
        var: selected_file

给出(当选择第二个文件并输入“2

shell> ansible-playbook playbook.yml 

PLAY [localhost] ****

TASK [pause] ****
[pause]
Choose file to select:
1 files/file3.txt
2 files/file2.txt
3 files/file1.txt
:
2^Mok: [localhost]

TASK [debug] ****
ok: [localhost] => 
  selected_file: files/file2.txt

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

起源

下面的剧本

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
© www.soinside.com 2019 - 2024. All rights reserved.