在Ansible中将字典添加到循环内的数组

时间:2018-09-26 17:50:48

标签: ansible

如何在'''with_items'''循环中将字典附加到数组?

SELECT COALESCE (a.DATE_IN, b.DATE_IN)                  AS DATE_IN,
       SUBSTR(COALESCE (a.TIME_IN, b.TIME_IN), 1, 8)    AS TIME_IN,
       CASE WHEN ( b.DATE_TIME_OUT > a.DATE_TIME_IN ) THEN COALESCE (a.DATE_OUT, 
            b.DATE_OUT) ELSE '' END                     AS DATE_OUT,
       CASE WHEN ( b.DATE_TIME_OUT > a.DATE_TIME_IN ) THEN 
            SUBSTR(COALESCE (a.TIME_OUT, b.TIME_OUT), 1, 8) ELSE '' END
                                                        AS TIME_OUT,
       COALESCE (a.SURNAME, b.SURNAME)                  AS SURNAME,
       COALESCE (a.WIEGANDID, b.WIEGANDID)              AS WIEGANDID,
       CASE WHEN ( b.DATE_TIME_OUT > a.DATE_TIME_IN ) THEN
            TIMESTAMPDIFF(SECOND, a.DATE_TIME_IN, b.DATE_TIME_OUT) / 3600 ELSE '' END
                                                        AS HOURS_WORKED
FROM (
    SELECT  _DATE_  AS  DATE_IN,
            _TIME_  AS  TIME_IN, 
            NULL    AS  DATE_OUT,
            NULL    AS  TIME_OUT,
            SURNAME,
            WIEGANDID,
            CONCAT( _DATE_, ' ', _TIME_ ) AS DATE_TIME_IN
       FROM test 
      WHERE ZKINOUT = 0 )   AS   a,
    (
    SELECT  NULL    AS  DATE_IN,
            NULL    AS  TIME_IN, 
            _DATE_  AS  DATE_OUT,
            _TIME_  AS  TIME_OUT,
            SURNAME,
            WIEGANDID,
            CONCAT( _DATE_, ' ', _TIME_ ) AS DATE_TIME_OUT
       FROM test
      WHERE ZKINOUT = 1 )   AS   b
WHERE a.WIEGANDID = b.WIEGANDID  
HAVING HOURS_WORKED < 15 AND HOURS_WORKED <> ''
ORDER BY 1, 2, 3, 4

以上内容不起作用,但这很好地表示了我想要完成的工作。如果我提前定义dict,则此附加效果很好,但它会附加相同的dict。

1 个答案:

答案 0 :(得分:2)

错误:

  • 您在第一次迭代中缺少default过滤器

  • 您不必为每次迭代定义my_dict-改用helper变量

  • 您的模板严重损坏,它创建了一个带有+的字符串,而不是连接列表

固定代码:

- with_items: "{{ members_obj.results }}"
  set_fact:
    effort_members: "{{ effort_members|default([]) + [ my_dict ] }}"
  vars:
    my_dict:
      name:  "{{ (item.content|from_json).name.0.value }}"
      id:    "{{ (item.content|from_json).nid.0.value }}"
      email: "{{ (item.content|from_json).mail.0.value }}"