title: Ansible file copy with src depending on whether a path exists
body: <p>Let's say I have a task to distribute a standard <code>/etc/aliases</code> file.</p>
  
  <pre><code>- name: Distribute /etc/aliases
    copy:
        src:   generic/etc/aliases
        dest:  /etc/aliases
        owner: root
        group: root
        mode:  0644
  </code></pre>
  
  <p>But I would like to have a directory structure that looks like this:</p>
  
  <pre><code>site.yml
  roles/
      common/
          files/
              fqdn/
                  foo.example.com/
                      etc/
                          aliases
              generic/
                  etc/
                      aliases
          tasks/
              main.yml
              etc_aliases.yml
  </code></pre>
  
  <p>Then, if (and only if) the file <code>fqdn/{{ inventory_hostname }}/etc/aliases</code> exists, copy that, otherwise copy the file <code>generic/etc/aliases</code> instead. So, the choice of which file to copy is based solely on whether the file exists or not; by creating the <code>fqdn/foo.example.com/etc/aliases</code> file, host foo.example.com gets that one instead of the generic one.</p>
  
  <p>Is that a sensible thing to want to do in Ansible and if so how would I accomplish it? If not, what is the correct pattern for this sort of thing?</p>
  
  <p>I realise that I can do it by setting a variable for the source path and overriding it on a per-host basis. For me the downside with this approach is that the host variable gets set in a place far away from the role definition, and also that it requires a variable setting <em>and</em> a file being placed, whereas the way I'd like to do it requires just a file being placed inside the role directory tree.</p>
  
  <p>I also found I could do it by using the stat module, to check if the source file path with the host name in does exist first, but I didn't find a way there to do it without having two copy tasks, one with a <code>when: blah.stat.exists defined</code> and the other with a <code>when: blah.stat.exists not defined</code> for the copy of the generic file. It also then lists three tasks in the output: one for the stat and then one for each of the possible copies, which seems a bit verbose.</p>
  
  <p>Is there a way to do what I want or is there a better way to accomplish a similar outcome?</p>