在Ansible中从字典创建逗号分隔的字符串

在Ansible中从字典创建逗号分隔的字符串

本文介绍了在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"

并创建string:

"cleanup.policy =删除,retention.ms = 146800000,分区= 6,复制因子= 2"

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

这是我到目前为止所拥有的.

This is what I have so far.

- 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?

推荐答案

这是您要查找的代码吗?

Is this the code that you're looking for?

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中从字典创建逗号分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 23:25