Ansible: preferring a pull from a URL with fallback to a local file

Pulling the most recent script/file/asset from a remote host may be preferable, but you would like to provide a fallback to a local file just in case the remote pull fails.

This is relatively easy to do with Ansible by allowing the remote pull to ‘ignore_errors’ and then doing a local file copy if an error was sensed.  Here is a snippet from playbook-try-url-first.yaml.

  - name: try file from github first
    get_url:
      url: https://raw.githubusercontent.com/fabianlee/blogcode/master/README.md
      dest: "/tmp/README.md"
      mode: 0666
    ignore_errors: true
    register: gitpull_result
  - debug: msg="{{gitpull_result}}"

  - name: uses local file when github not available
    copy:
      src: "{{playbook_dir}}/local-README.md"
      dest: "/tmp/README.md"
    when: gitpull_result.failed

The ‘get_url’ attempts to pull a file from github (with a lenient ignore_errors), and puts the result in ‘gitpull_results’.  If this failed then a local file copy is allowed to execute.

If this copy task were part of a role, the ‘src’ attribute would not need to specify any path prefix as long as the local file was located in the standard ‘files’ directory.

REFERENCES

ansible docs, get_url

fabianlee github, playbook example