Some services need to have separate processes for initial installation and upgrading. A simple example is upgrading a database server, where you may need to take it out of the cluster when upgrading. In Ansible, you may split that into separate playbooks, but if you need to handle that in one (for example, your master site.yml), the easiest way is to try to ensure it is installed by setting the state to 'present'. If that causes a chance, that means that the package was not installed previously, so we can proceed with the initial installation. If no, we can see if there is an upgrade by setting to 'latest'. If that changes, we know it's an upgrade and can handle in its own play
# If this causes a change, we know that mysql-server was not previously installed
- name: 'MySQL > install mysql server if absent'
yum:
name: 'mysql-server'
state: 'present'
register: install_present
# If no change was caused by the previous step, we can see if there is an upgrade by setting state to latest
- name: 'MySQL > if MySQL is already present, check if there is a new version and install it'
yum:
name: 'mysql-server'
state: 'latest'
when: install_present.changed == False
register: install_latest
# If package was installed for the first time, proceed with the installation steps
- include: install.yml
when: install_present.changed == True
# If package was upgraded, proceed with the upgrade steps
- include: upgrade.yml
when: install_latest == True