kubernetes - 在列表项前面添加字符串并在 Ansible 中将其转换为 JSON

标签 kubernetes ansible formatting jinja2

我有一个端口列表

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/

相关文章:

kubernetes - EKS 工作节点可以设置在不同的区域吗

kubernetes - 带有 EKS 的 Terraform Kubernetes 提供程序在 configmap 上失败

python - 如何在python3中使用数组join()方法添加数字?

Python 格式将 numpy.float32 转换为 Python float

c# - .NET 中的货币格式

kubernetes - 在 helm 中覆盖 .Release.Name 的位置

docker - 在Google Cloud Platform中更新Docker镜像

loops - 安塞 bool 2.x : ec2_remote_facts

jenkins - 执行 ansible 脚本时出现 MODULE FAILURE 错误

ansible - 循环遍历两个数组的乘积