【问题标题】:Ansible: merge dictionaries appending valuesAnsible:合并字典附加值
【发布时间】:2022-07-05 23:38:25
【问题描述】:

如何获得一个字典,其中输入的值用逗号分隔?输入参数的数量和顺序可以不同。我尝试过的只是给出以下错误

- set_fact:
    input:
      - port: 1234
        protocol: TCP
        messages: 888-999
        file: s3://somepath/file.xsl
      - protocol: TLS
        port: 5678
        path: s3://somepath/mycertificate.crt
        messages: 345, 467, 888
        file: s3://somepath/file2.xsl

- set_fact:
    final_dict:
      finalFile: item | map(attribute='file')| join(',')
      finalFilter: item | map(attribute='messages')| join(',')
      finalPath: item | map(attribute='path')| join(',')
      finalProtocol: item | map(attribute='protocol')| join(',')
      finalPort: item | map(attribute='port')| join(',')
  loop: "{{ input }}"

"msg": "任务包含一个带有未定义变量的选项。错误是:'str object' has no attribute 'file'

【问题讨论】:

    标签: data-structures ansible


    【解决方案1】:

    这里确实存在三个问题:

    1. 如果你打算使用map,那么你需要在一个列表上做,所以,你应该有像这样的表达式
      var: input | map(attribute='file')
      
      并且不要对loopitem 采取行动。
    2. 您在final_dict 中缺少{{ ... }} 表达式分隔符,例如:
      finalFile: "{{ input | map(attribute='file') | join(',') }}"
      
      并不是
      finalFile: input | map(attribute='file') | join(',')
      
    3. 因为您的字典列表input 中确实有一些未定义的键,所以您想使用mapdefault 值:
      finalPath: "{{ input | map(attribute='path', default='') | join(',') }}"
      

    鉴于这三个评论,这两个任务:

    - set_fact:
        final_dict:
          finalFile: "{{ input | map(attribute='file') | join(',') }}"
          finalFilter: "{{ input | map(attribute='messages') | join(',') }}"
          finalPath: "{{ input | map(attribute='path', default='') | join(',') }}"
          finalProtocol: "{{ input | map(attribute='protocol') | join(',') }}"
          finalPort: "{{ input | map(attribute='port') | join(',') }}"
      vars:
        input:
          - port: 1234
            protocol: TCP
            messages: 888-999
            file: s3://somepath/file.xsl
          - protocol: TLS
            port: 5678
            path: s3://somepath/mycertificate.crt
            messages: 345, 467, 888
            file: s3://somepath/file2.xsl
    
    - debug:
        var: final_dict
    

    会产生:

    ok: [localhost] => 
      final_dict:
        finalFile: s3://somepath/file.xsl,s3://somepath/file2.xsl
        finalFilter: 888-999,345, 467, 888
        finalPath: ',s3://somepath/mycertificate.crt'
        finalPort: 1234,5678
        finalProtocol: TCP,TLS
    

    【讨论】:

      猜你喜欢
      • 2020-12-28
      • 2014-10-14
      • 1970-01-01
      • 2013-03-18
      • 1970-01-01
      • 2020-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多