title: Appending to lists/adding keys to a variable in ansible
body: <p>I'm following as per <a href="https://serverfault.com/questions/685673/appending-to-lists-or-adding-keys-to-dictionaries-in-ansible">thread</a> to append variables to a list in Ansible; i'm using logic <code>my_group: {{my_group + [item.hostname]}}</code></p>
  
  <pre><code>- name: "Initialize variables"
    set_fact:
        my_group: []
  
  - set_fact:
        my_group:
          "{% if item.hostGroup == "webgroup" %}
             {{my_group + [item.hostname]}}
          {% endif %}"
    with_items: "{{serverList}}"
  </code></pre>
  
  <p>my <code>serverList</code> payload looks like</p>
  
  <pre><code>{
      "hostGroup": "dbgroup", 
      "hostname": "db_server_usa_01" 
  }, 
  {
      "hostGroup": "webgroup", 
      "hostname": "web_server_usa_01" 
  }
  </code></pre>
  
  <p>Getting an error like below</p>
  
  <pre><code>"Unexpected templating type error occurred on 
  ({% if item.hostGroup == 'webgroup' %} {{my_group + [item.hostname]}} 
  {% endif %}): coercing to Unicode: need string or buffer, list found"}
  </code></pre>
  
  <p>It works perfectly if there is NO <code>if</code> loop.  Any idea how to make this work with <code>if</code> loop?</p>