Installing Composer with Ansible
I recently had to install Composer on multiple machines, Ansible was the right tool for the job. Ansible is a well-known provisioning tool where all configuration is written in simple Yaml files, and the target machines don’t need any client installed.
In this post I will walk through the Ansible role I created to install Composer.
Here’s the structure of the role.
Without surprise, I called this role composer.
roles/
└── composer
└── tasks
└── main.yml
As you can see, this role is extremely simple.
It contains a single task list in ./roles/composer/tasks/main.yml:
---
- name: Download Composer
ansible.builtin.get_url:
url: https://github.com/composer/composer/releases/download/2.9.2/composer.phar
dest: /usr/local/bin/composer
mode: '+x'
become: yes
- name: Update Composer
ansible.builtin.command: /usr/local/bin/composer self-update --no-interaction
become: yes
- name: Add Composer to PATH
ansible.builtin.lineinfile:
path: '/.bashrc'
regexp: '^export PATH=.*composer/vendor/bin'
line: 'export PATH="/.config/composer/vendor/bin:$PATH"'
The first task downloads the Phar version of Composer. If Composer is already installed, Ansible won’t re-download it.
Notice that version of Composer is hardcoded, this is not a big concern because in the second task we update Composer anyway.
Finally, the last task adds the Composer’s global bin directory into the
PATH.
This is important because it lets you run binaries installed through the
composer global require command.
Before using this role as-is, make sure it matches your environment:
- Check if you really need to execute tasks with elevated privileges (
become: yes). - Also check if the Composer’s global bin directory is correct. You can use
this command to retrieve this value:
composer global config bin-dir --absolute.