代码之家  ›  专栏  ›  技术社区  ›  Ashar

使用Ansible为set_fact赋值时发生意外的模板类型错误

  •  0
  • Ashar  · 技术社区  · 6 年前

    使用Ansible为set_fact赋值时发生意外的模板类型错误

    以下是我的剧本:

       - name: Load entire repository inventory
         include_vars:
           file="{{ playbook_dir }}/repository/inform/gac.yaml"
           name=user1
    
       - debug:
           msg: "ALERT !! File {{ user1[inventory_hostname][item.stat.path] }} has changed {{ inventory_hostname }}"
         when: item.stat.checksum != user1[inventory_hostname][item.stat.path].hash
         with_items: "{{ files_det.results }}"
    
    
       - name: Gather all files
         tags: always
         set_fact:
           msg_body: "{{ msg_body | default('') + user1[inventory_hostname][item.stat.path] + 'has changed' + inventory_hostname +'. Rollback' + '\n' }}"
         when: item.stat.checksum != user1[inventory_hostname][item.stat.path].hash
         with_items: "{{ files_det.results }}"
    

    我收到的错误设置如下:

    "msg": "ALERT !! File {u'hash': u'1746f03d5741b27158b0d3a48fca8b5fa85c0c2'} has changed 10.9.9.66"
    
    
    TASK [Gather all files] ***************************************************************************************************************
    task path: /app/fg_test.yml:2
    META: noop
    fatal: [10.9.9.66]: FAILED! => {
        "msg": "Unexpected templating type error occurred on ({{ msg_body | default('') + user1[inventory_hostname][item.stat.path] + 'has changed' + [inventory_hostname] +'. Rollback' + '\n' }}): cannot concatenate 'str' and 'dict' objects"
    }
    META: noop
    

       msg_body: "{{ msg_body | default('') + user1[inventory_hostname][item.stat.path] + 'has changed' + [inventory_hostname] +'. Rollback' + '\n' }}"
    

    但这也无济于事。

    你能告诉我我的代码有什么问题吗?

    0 回复  |  直到 6 年前
        1
  •  1
  •   Vladimir Botka    6 年前

    问: “我的代码有什么问题?”

    A: 问题是“ Cannot concatenate 'str' and 'dict' objects ".

    user1[inventory_hostname][item.stat.path] 词典 {u'hash': u'1746f03d5741b27158b0d3a48fca8b5fa85c0c2'}

       - debug:
           msg: "ALERT !! File {{ user1[inventory_hostname][item.stat.path] }} has changed {{ inventory_hostname }}"
    
    "msg": "ALERT !! File {u'hash': u'1746f03d5741b27158b0d3a48fca8b5fa85c0c2'} has changed 10.9.9.66"
    

    下一步你 将字符串与此词典连接

    msg_body: "{{ msg_body | default('') + user1[inventory_hostname][item.stat.path] + 'has changed'
    

    修好它。用字符串替换字典。例如使用

    user1[inventory_hostname][item.stat.path.hash]
    
    推荐文章