使用带有循环的 set_fact 的 ansible 输出可能 [英] Use ansible output for set_fact with loop maybe
问题描述
我使用 ansible 在 proxmox 中创建和运行 lxc 容器.运行容器任务:
I use ansible for create and run lxc containers in proxmox. Run container task:
- name: "DHCP IP"
proxmox:
...
hostname: "{{ item }}"
...
pubkey: "{{ pubkey }}"
with_items:
- "{{ (servers_name_suggested | union(servers_name_list)) | unique }}"
register: output_dhcp
when: not static_ip
- set_fact:
vmid: "{{ output_dhcp.results[0].msg | regex_search('[0-9][0-9][0-9]') }}"
- name: "Start container {{ vmid }}"
proxmox:
vmid: "{{ vmid }}"
api_user: root@pam
api_password: "{{ api_password }}"
api_host: "{{ api_host }}"
state: started
when: start_lxc
如果启动一个容器,任务DHCP IP"中的一项,它就可以工作.如果我设置两个或更多项目,我的任务只开始了第一个容器.因为我正在设置
It's work if launched one container, one item in task "DHCP IP". If I set two or more item, my task started only first container. Because I am setting
output_dhcp.results[0].msg
我如何获取所有容器的信息,例如,如果我将创建树容器:
How I can take information about all containers, as example, if I will create tree containers:
output_dhcp.results[1].msg
output_dhcp.results[2].msg
并收到
- name: "Start container {{ vmid }}"
proxmox:
vmid: "{{ vmid }}"
运行我所有的新容器.
推荐答案
output_dhcp.results
是一个列表,如果你只提取带有 [0]
您将只有第一项.
The output_dhcp.results
is a list, if you extract only the first item with a [0]
you will only have the first item.
您需要将列表转换为另一个可以在启动容器"中迭代的列表;任务:
You need to transform the list into another list you can iterate over in the "Start container" task:
- set_fact:
vmids: "{{ output_dhcp.results | map(attribute='msg') | map('regex_search', '[0-9][0-9][0-9]') | list }}"
- name: "Start container {{ item }}"
proxmox:
vmid: "{{ item }}"
api_user: root@pam
api_password: "{{ api_password }}"
api_host: "{{ api_host }}"
state: started
with_items: "{{ vmids }}"
when: start_lxc
解释转换部分:
output_dhcp.results |地图(属性='msg')
=>获取output_dhcp.results
列表(http://jinja.pocoo.org/docs/dev/templates/#map)- <代码>|map('regex_search', '[0-9][0-9][0-9]') =>对列表的每个项目应用
regex_search
- <代码>|列表 =>将生成器转换为列表
output_dhcp.results | map(attribute='msg')
=> get themsg
attribute of each item of theoutput_dhcp.results
list (http://jinja.pocoo.org/docs/dev/templates/#map)| map('regex_search', '[0-9][0-9][0-9]')
=> apply theregex_search
on each item of the list| list
=> transform the generator into a list
这篇关于使用带有循环的 set_fact 的 ansible 输出可能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!