如何解决将dict转换为期望的列表ansible podman模块
我有以下意见:
ports:
http:
host: 81
container: 80
https:
host: 444
container: 443
我想以我的角色使用它,部分原因是它非常适合完成此任务的示例(按预期工作)。
- name: ensure container's exposed ports firewall state
tags: firewall
firewalld:
port: "{{ item.value.host }}/tcp"
permanent: yes
immediate: yes
state: enabled
loop: "{{ lookup('dict',ports,wantlist=True) }}"
when: ports is defined
但是在以下任务上,循环将无法正常进行(我试图启动同时启用了两个端口的容器):
- name: Run container
containers.podman.podman_container:
name: "{{ container_name }}"
image: "{{ container_image }}"
state: "{{ state }}"
recreate: "{{ recreate }}"
ports:
- "{{ item.value.host }}:{{ item.value.container }}"
loop: "{{ lookup('dict',wantlist=True) }}"
如果我使用 loop 语句进行循环,它将启动两个容器(一个带有http,另一个带有https),并且带有 with_items ,它将仅适用于最后一个值(在本例中为https)。
模块期望这样的值。 (带有可在测试中使用的硬编码值。)
containers.podman.podman_container:
name: myapplication
...
ports:
- "8080:9000"
- "127.0.0.1:8081:9001/udp"
如何将现有字典转换为模块期望的形式?
解决方法
循环将在您拥有物品时多次调用该模块。在调用模块之前,例如,使用循环创建端口列表,例如
- name: Calculate list of ports to launch container
vars:
current_port: "{{ item.value.host }}:{{ item.value.container }}"
set_fact:
port_list: "{{ port_list | default([]) + [current_port] }}"
loop: "{{ lookup('dict',ports,wantlist=True) }}"
- name: Run container
containers.podman.podman_container:
name: "{{ container_name }}"
image: "{{ container_image }}"
state: "{{ state }}"
recreate: "{{ recreate }}"
ports: "{{ port_list }}"
,
环境变量
env_vars:
hostname:
key: HOSTNAME
value: '"host1"'
user:
key: USER
value: '"user1"'
我用w ::
转换了- name: Calculate list of env_vars to launch container
set_fact:
env_vars_dict: "{{ env_vars_dict|default({}) | combine( {item.value.key | upper: item.value.value} ) }}"
loop: "{{ lookup('dict',env_vars,wantlist=True) }}"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。