linux 提示变量以列表格式输入值(with_item/loop)

rryofs0p  于 2023-03-17  发布在  Linux
关注(0)|答案(1)|浏览(115)
- name: testplay  
  hosts: localhost  
  gather_facts: false  
  vars_prompt:  
    - name: register_name  
      prompt: "Enter your register name in a listformat to pick one by one"  
      private: no  
  
    - name: node_list  
      prompt: "Enter your register names in list like  
 same,charles,william,george"
      private: no
      with_items: "{{ register_name }}"

  tasks:
    - debug:
        msg: "display all {{ register_names }} here"
  
    - name: write register names to a file one below the other  
      shell: echo '{{ item }}' >> file.txt  
      with_items: "{{ register_name }}"

我想在提示模块的列表中输入值,以便逐个选择,不确定此处的循环如何工作,请建议(我尝试了with_item/loop,但没有工作)

# ansible-playbook test.yml  
Enter register_no in a listformat to pick one by one: same,charles,william,george
0h4hbjxa

0h4hbjxa1#

vars_prompt接受文本。没有办法从头开始输入列表。但使用split很容易实现(添加trim以确保安全)。简而言之,下面是prompt_demo.yml剧本:

---
- hosts: localhost
  gather_facts: false

  vars_prompt:
    - name: registered_names_prompt
      prompt: Please enter names. Separate multiple elements with coma
      private: no

  vars:
    registered_names: "{{ registered_names_prompt.split(',') | map('trim') }}"

  tasks:
    - name: Debug our var in a loop
      ansible.builtin.debug:
        var: item
      loop: "{{ registered_names }}"

给出:

$ ansible-playbook prompt_demo.yml 
Please enter names. Separate multiple elements with coma: toto,pipo ,bingo, bla , bli, blo

PLAY [localhost] ********************************************************************************************************************************

TASK [Debug our var in a loop] ******************************************************************************************************************
ok: [localhost] => (item=toto) => {
    "ansible_loop_var": "item",
    "item": "toto"
}
ok: [localhost] => (item=pipo) => {
    "ansible_loop_var": "item",
    "item": "pipo"
}
ok: [localhost] => (item=bingo) => {
    "ansible_loop_var": "item",
    "item": "bingo"
}
ok: [localhost] => (item=bla) => {
    "ansible_loop_var": "item",
    "item": "bla"
}
ok: [localhost] => (item=bli) => {
    "ansible_loop_var": "item",
    "item": "bli"
}
ok: [localhost] => (item=blo) => {
    "ansible_loop_var": "item",
    "item": "blo"
}

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

相关问题