title: Assigning the hosts attribute dynamically in Ansible from Python
body: <p>I am integrating Ansible with Python and MySQL DB. A part of my use case is that  given a group name to Ansible, send that group name to python which does a db read and returns a list of IPs corresponding to that group name.
  For a test I want to ping the returned IPs.</p>
  
  <p>Here is my playbook for achieving the same:</p>
  
  <pre><code>name: run a cmd
  hosts: localhost
  connection: local
  tasks:
    name: runs a python script with a parameter
        shell: python /pythonScripts/AnsibleDBRead.py &lt;someGroupName&gt;
        register: py_ret
      - set_fact:
         ip_list: "{{py_ret.stdout}}"
     - debug: var=hostvars['localhost']['ip_list']  # option to set messages here as well but not both together
  
  
  name: png the hosts returned 
  hosts: hostvars['localhost']['ip_list'] #this does not work
  #hosts: [ "127.0.0.1", "54.147.177.9"] #this works same value but hardcoded
  tasks: 
      - debug: var=hostvars['localhost']['ip_list']  # able to print the value
  </code></pre>
  
  <p>I am trying to set the values stored in <code>ip_list</code> as the <code>hosts:</code> for second play but without any success. The error I get is no hosts matched. Here is the output whe n run with hardcoded part commented. Ignore the formatting of the script. </p>
  
  <pre><code>PLAY [run a cmd] ***************************************************************
  
  TASK [setup] *******************************************************************
  ok: [localhost]
  
  TASK [runs a python script with a parameter] ***********************************
  changed: [localhost]
  
  TASK [set_fact] ****************************************************************
  ok: [localhost]
  
  TASK [debug] *******************************************************************
  ok: [localhost] =&gt; {
      "hostvars['localhost']['ip_list']": [
          "127.0.0.1", 
          "54.147.177.9"
      ]
  }
  
  PLAY [png the hosts returned] **************************************************
  skipping: no hosts matched
  
  PLAY RECAP *********************************************************************
  localhost                  : ok=4    changed=1    unreachable=0    failed=0   
  </code></pre>
  
  <p>from what I have read I should be able to access the variable declared in one play in another play using <code>hostvars</code>. Any help is appreciated.</p>