从 Ansible 中的字典创建逗号分隔的字符串 [英] Creating a comma separated string from a dictionary in Ansible

查看:30
本文介绍了从 Ansible 中的字典创建逗号分隔的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个 Ansible 角色,以便能够alter 给定的 Kafka 主题.我正在使用键/值对字典.

I want to write an Ansible role to be able to alter a given Kafka topic. I am using a dictionary of key/value pairs.

command 模块然后用于执行采用逗号分隔值字符串的 Kafka 脚本.例如,使用 app_kafka_topic 列表:

The command module is then used to execute a Kafka script that take a string of comma separated values. For instance, use app_kafka_topic list:

---
app_kafka_topic:
    cleanup.policy      :
    - "delete"
    retention.ms        :
    - "146800000"
    partitions          :
    - "6"
    replication-factor  :
    - "2"

并创建字符串:

"cleanup.policy=delete,retention.ms=146800000,partitions=6,replication-factor=2"

"cleanup.policy=delete,retention.ms=146800000,partitions=6,replication-factor=2"

这是我目前所拥有的.

- name: Reading the Default Topic Properties
  set_fact:
    app_kafka_topic_properties_dicts: |
        {% set res = [] -%}
        {% for key in app_kafka_topic.keys() -%}
           {% for value in app_kafka_topic[key] -%}
            {% set ignored = res.extend([{'topic_property': key, 'value':value}]) -%}
           {%- endfor %}
        {%- endfor %}
        {{ res }}

- name: Create Topic with Default Properties
  command: "{{ kafka_bin_dir }}/{{ kafka_config_script }}
            --zookeeper {{ prefix }}-kafka-{{ Kafka_node }}.{{ DNSDomain}}:{{ zookeeper_port }}
            --entity-type topics
            --alter
            --entity-name {{ kafka_topic }}
            --add-config
            {{ properties }}"
  with_items: "{{ app_kafka_topic_properties_dicts }}"
  register: createdTopic
  vars:
    properties: |-
      {% for key in app_kafka_topic.keys() %}
      {% for value in app_kafka_topic[key] %}
       "{{ key }}={{ value }}"
      {%- endfor %}
      {%- endfor %}

但是,properties 变量不会将值连接到字符串的末尾.有没有办法将值附加到字符串并用逗号分隔它们?

However, the properties variable is not concatenating the values to the end of a string. Is there a way to append the values to a string and separate them by a comma?

推荐答案

这是您要找的代码吗?

play.yml

- hosts: localhost
  gather_facts: no
  vars:
    string: ""
    app_kafka_topic:
      cleanup.policy      :
      - "delete"
      retention_ms        :
      - "146800000"
      partitions          :
      - "6"
      replication_factor  :
      - "2"
  tasks:
    - set_fact:
        string: "{{ string }}{{ (index > 0)|ternary(',','') }}{{ item.key }}={{ item.value[0] }}"
      loop: "{{  app_kafka_topic|dict2items }}"
      loop_control:
        index_var: index
    - debug:
        var: string

$ ansible-playbook play.yml |grep 字符串

$ ansible-playbook play.yml | grep string

"string": "retention_ms=146800000,cleanup.policy=delete,replication_factor=2,partitions=6"

这篇关于从 Ansible 中的字典创建逗号分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆