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

问题描述 投票:0回答:1

使用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 }}"

我收到set_fact的错误,如下所示:

"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' }}"

但那也无济于事。

您能建议我的代码有什么问题吗?

ansible runtime-error ansible-2.x ansible-inventory ansible-facts
1个回答
0
投票

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

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]
© www.soinside.com 2019 - 2024. All rights reserved.