Providing fact data

Similar to data returned as part of a module exit, a module can directly create facts for a host by returning data in a key named ansible_facts. Providing facts directly from a module eliminates the need to register the return of a task with a subsequent set_fact task. To demonstrate this usage, let's modify our module to return the source and dest data as facts. Because these facts will become top-level host variables, we'll want to use more descriptive fact names than source and dest – replace the current module.exit_json line in our module with the code listed:

    facts = {'rc_source': module.params['source'], 
             'rc_dest': module.params['dest']} 
 
    module.exit_json(changed=True, ansible_facts=facts) 

We'll also add a task to our playbook to use one of the facts in a debug statement:

  - name: show a fact 
    debug: 
      var: rc_dest 

Now, running the playbook will show the new return data plus the use of the variable:

If our module does not return facts (and our previous version of remote_copy.py didn't), we will have to register the output and use set_fact to create the fact for us, as shown in the following code:

  - name: do a remote copy 
    remote_copy: 
      source: /tmp/rcfoo 
      dest: /tmp/rcbar 
    register: mycopy 
 
  - name: set facts from mycopy 
    set_fact: 
      rc_dest: "{{ mycopy.dest }}" 

Although it is useful to be able to do this, when designing our own modules, it is better to have the module define the facts required. If this is not done, then the previous register and the set_fact code would need to be repeated for every use of our module in a playbook!