Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible best practice to copy directories

Tags:

In my playbook I have

- name: Grab h5bp/server-configs-nginx
  git:  repo=https://github.com/h5bp/server-configs-nginx.git
        dest=/tmp/server-configs-nginx
        version="3db5d61f81d7229d12b89e0355629249a49ee4ac"
        force=yes

- name: Copy over h5bp configuration
  command: cp -r /tmp/server-configs-nginx/{{ item }} /etc/nginx/{{ item }}
  with_items:
    - "mime.types"
    - "h5bp/"

Which raises the warning in ansible-lint:

[ANSIBLE0006] cp used in place of copy module
/Users/austinpray/Dropbox/DEV/opensauce/bedrock-ansible/roles/nginx/tasks/main.yml:0
Task/Handler: Copy over h5bp configuration

So this raises the question: is there a better way to do this with ansible modules rather than a command?

like image 431
Austin Pray Avatar asked Aug 29 '14 22:08

Austin Pray


People also ask

Does Ansible copy use SCP?

If you want to copy a file from an Ansible Control Master to remote hosts, the COPY (scp) module would be just fine.

Does Ansible copy overwrite?

By default, the ansible copy module does a force copy to the destination and overwrites the existing file when present.


2 Answers

You can use the synchronize module with mode='pull'

- name: Copy over h5bp configuration
 synchronize: mode=pull src=/tmp/server-configs-nginx/{{ item }} dest=/etc/nginx/{{ item }} 
 with_items:
   - "mime.types"
   - "h5bp/"

Note: To copy remote-to-remote, use the same command and add delegate_to (as remote source) and current inventory_host (as remote dest)

like image 54
ant31 Avatar answered Sep 20 '22 12:09

ant31


Currently, command is your best option. There's no remote-to-remote option. Here's a thread about it: How to move/rename a file using an Ansible task on a remote system

You have a couple other options:

  • you could use the file module to make a symlink (by setting src, path, and state=link.
  • you could check out the repo on the Ansible server and then use copy. This is a more common model for deploying code.
  • you can keep using command but wrap it with a stat conditional so it only overwrites once. This is especially helpful if you use notify to restart nginx.

Finally, it looks like you might be doing a "deploy by git". That isn't always the best choice, especially if you don't "own" that repo. But it could be fine- just a bit of code smell.

like image 20
tedder42 Avatar answered Sep 23 '22 12:09

tedder42