9

I have an ansible 1.1 playbook where I do something like this:

- name: copy files
  sudo: True                                                                                                             
  shell: cp /from/* /to/

- name: change owner
  sudo: True
  file: path=$item owner=newuser group=newgroup
  with_fileglob: /to/*

The second task, "change owner" is always skipping. can anyone help me finding out why? is the file module skipping because the files exist? I'm stuck :)

deadsven
  • 193
  • 1
  • 1
  • 5

2 Answers2

16

From documentation:

Remember lookup plugins are run on the "controlling" machine:

with_fileglob is a lookup plugin, so it looks for files on the local server, the one you are running ansible-playbook from.

Here is what you can do:

- name: list files 
  action: command ls -1 /to/* 
  register: dumpfiles 

- name: change ownership 
  action: file path=$item owner=newuser group=newgroup
  with_items: ${dumpfiles.stdout_lines}
slm
  • 7,615
  • 16
  • 56
  • 76
Tom Aac
  • 1,097
  • 9
  • 11
  • that makes so much sense now that you say it. BTW, I solved this by using [shell: chown -R newuser:newgroup /to] – deadsven May 29 '13 at 14:12
  • 3
    Using shell in this case is not the preferable way since you are losing idempotency. You should instead use file module and with_items – Tom Aac May 30 '13 at 06:59
  • yes, i'd like to use the file module, but with_items does not support globs does it? listing every file in a with_items list is not really what I want – deadsven May 30 '13 at 11:12
  • See my answer, there is what you need – Tom Aac May 31 '13 at 14:17
  • How is *shell: chown* **not** idempotent? You can run it as many times as you like, and the state of the machine is exactly the same as if you'd just run it once. That's [idempotency](http://en.wikipedia.org/wiki/Idempotence), no? – Bosh Jun 12 '14 at 21:35
  • 2
    Every time you run chown, you change file's timestamp. In particular ctime. That might be issue for some backup software for example. – Tom Aac Jun 13 '14 at 21:38
  • The link is now broken. I suspect this would be an alternative: http://docs.ansible.com/ansible/playbooks_lookups.html. – slm Sep 25 '15 at 20:52
5

Ansible 1.1 added the recurse parameter to the file module, so all you need to do for your change ownership task is this:

- name: change ownership 
  action: file state=directory recurse=yes path=/to/ owner=newuser group=newgroup

This will make it more apparent when actually things change; using the shell or command modules will always return a changed status, even if nothing was actually changed.

Andrew Schulman
  • 8,811
  • 21
  • 32
  • 47
HitScan
  • 151
  • 1
  • 3