Fixing Homebrew after upgrading to Mac OS X El Capitan


After upgrading to El Capitan Homebrew commands stopped working with this error:

TASK: [Clean up and update] *************************************************** 
failed: [] => {"changed": true, "cmd": "brew update && brew upgrade brew-cask && brew cleanup && brew cask cleanup", "delta": "0:00:00.466698", "end": "2015-10-16 10:49:57.
562138", "rc": 1, "start": "2015-10-16 10:49:57.095440", "warnings": []}
stderr: Error: The /usr/local directory is not writable.
Even if this directory was writable when you installed Homebrew, other
software may change permissions on this directory. Some versions of the
"InstantOn" component of Airfoil are known to do this.

You should probably change the ownership and permissions of /usr/local
back to your user account.
  sudo chown -R $(whoami):admin /usr/local

FATAL: all hosts have already failed -- aborting


To fix this, just follow the instructions in the error message and change the permissions on /usr/local. Since I'm using Ansible, I added a simple task to check if the directory is own by root, and if it then change ownership:

    - stat: path=/usr/local
      register: usrlocal
    - name: If root owns /usr/local, change it to current user.
      shell: sudo chown -R $(whoami):admin /usr/local
      when: usrlocal.stat.pw_name == "root"

Sidenote: I've chosen to do the shell command as a sudo rather than have ansible invoke the root user so I don't have to remember to run ansible with -K.