Optimizing Permission Rewriting in Ansible

I was recently working on speeding up an Ansible playbook and found this task that was running slowly.

- name: Web Root File Permissions
  command: find /var/www/somedir -type f -exec chmod ug=rw,o=r {} \;
  args:
    chdir: /var/www/somedir

This task runs the find command for all files in a specific directory and recursively executes the chmod command on them. The issue is with a directory thousands of files we end up executing thousands of chmod commands. This is a lengthy process. Thankfully I found a better way at https://bash-prompt.net/guides/bash-find-exec-speedup/

- name: Web Root File Permissions
  command: find /var/www/somedir -type f -exec chmod ug=rw,o=r {} +
  args:
    chdir: /var/www/somedir

Using the “+” instead of the “\;” exec parameter concatenates all the found files to a single chmod command. This is much faster.

One response to “Optimizing Permission Rewriting in Ansible”

  1. @matt Neat! I wonder if it has a length limitation? Like, will it be fine with 10,000 objects but fall over when it hits 100,001 objects …

Leave a Reply

Your email address will not be published. Required fields are marked *