title: How to create global variable that each host in a play can read and write in ansible?
body: <pre><code>---
  hosts: all
  vars:
    global_variable: 0 
  tasks:
    - name: increment variable
      set_var:
         global_variable: "{{ global_variable + 1   }}"
     -debug: global_variable
  </code></pre>
  
  <p>This won't work as you'll get a fresh instance of global_variable for each host. the output of debug will always be the same, instead of incrementing. 
  I tried using localhost's hostvars to share a read/write variable , but you can't assign to it with set_fact: ( how else would you assign a value to it?) 
  eg</p>
  
  <pre><code>- name: update global variable
      delegate_to: localhost
      connection: local
      set_fact:
        hostvars['localhost']['global_variable']: "{{ hostvars['localhost']['global_variable'] + 1 }}"
  </code></pre>
  
  <p>Results in the error:</p>
  
  <pre><code> FAILED! =&gt; {"changed": false, "msg": "The variable name 'hostvars['localhost']['global_variable']' is not valid. Variables must start with a letter or underscore character, and contain only letters, numbers and underscores."}
  </code></pre>
  
  <p>Ideas on how to get this to work? </p>