我有一个端口列表
ports:
- 123
- 456
- 789
我喜欢将其转换为 containerPort
以在 Kubernetes 部署中使用:
"container_ports": [
{
"containerPort": 123
},
{
"containerPort": 456
},
{
"containerPort": 789
}
]
上面的示例是在我将 ports
定义为
ports:
- containerPort: 123
- containerPort: 456
- containerPort: 789
但是,我想节省用户的输入时间并自动添加 containerPort
。我可以使用
- name: Creating custom ports
set_fact:
container_ports: "{{ ports | map('regex_replace', '(^)', '- containerPort: \\1') | list }}"
when: ports is defined
这只会创建
ok: [localhost] => {
"container_ports": [
"- containerPort: 123",
"- containerPort: 456",
"- containerPort: 789"
]
}
虽然很接近,但不太正确。
最佳答案
你可以这样做:
---
- hosts: localhost
connection: local
gather_facts: no
vars:
ports:
- 123
- 456
tasks:
- name: Creating custom ports
set_fact:
container_ports: '{{ ports | map("regex_replace", "^(.*)$", "containerPort: \1") | map("from_yaml") | list }}'
- debug:
var: container_ports
...
诀窍是将每个项目转换为 YAML 哈希,然后使用 from_yaml
将其转换为 Python 字典。
调试输出:
ok: [localhost] => {
"container_ports": [
{
"containerPort": 123
},
{
"containerPort": 456
}
]
}
关于kubernetes - 在列表项前面添加字符串并在 Ansible 中将其转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62155232/