Using which
or command
in a command
task would be ok here IMO since homebrew is installed directly from a binary through a script and does not leave any traces in a package manager.
Meanwhile, since ansible has support for Homebrew, we can use the community.general.homebrew
module to test if it is available.
Notes:
- since I don't have Homebrew I tested my script only in that situation. Meanwhile you should get the expected result testing on a machine where it is available.
- this method depends on the configured path to find Homebrew. Here I'm using a local connection to my local machine. When using a remote target, ansible will connect via ssh and use sh by default with a non-login shell (not loading any shell init files like
login
, .bashrc
, ...). If your binary is installed outside the available path for the task, you'll get a false negative response.
Here is the idea, adapt to your needs.
The playbooks:
---
- name: Test homebrew presence
hosts: localhost
gather_facts: false
tasks:
- name: Check if homebrew is available
block:
- name: try using homebrew in check_mode (no changes)
homebrew:
update_homebrew: true
check_mode: true
- name: Homebrew available
debug:
msg: Homebrew is installed
rescue:
- name: No homebrew
debug:
msg: Homebrew is not installed
Gives (without homebrew):
PLAY [Test homebrew presence] ***********************************************
TASK [try using homebrew in check_mode (no changes)] ************************
fatal: [localhost]: FAILED! => {"changed": false, "msg": "Failed to find required executable \"brew\" in paths: /usr/local/bin:/home/user/.local/bin:/home/user/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin"}
TASK [No homebrew] **********************************************************
ok: [localhost] => {
"msg": "Homebrew is not installed"
}
PLAY RECAP ******************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=1 ignored=0