trying2dev
trying2dev

Reputation: 51

How to override a yum module state for multiple packages using environment variable in Ansible?

This is my code currently -

- name: software
  hosts: localhost
  tasks:
    - name: install packages
      yum: 
        name: 
          - ansible
          - docker
        state: latest
      become: yes

So when I run this I get the latest ansible and docker installed.

What I want is for the default value of state to remain latest, so if I just run the playbook the latest versions are downloaded, as it is now. However I want a way for me to override the state for one or both using environment variables(extra vars) when running my playbook from the command line.

So I can choose what version of ansible or docker to install.

Is there a way?

Upvotes: 0

Views: 814

Answers (1)

Zeitounator
Zeitounator

Reputation: 44760

Although I do not think this is the best way to manage software version and that the I consider the following a bit ugly, here is a in-a-nutshell example to get you on track for your experimentation (untested, you may have to adapt a bit):

---
- name: software
  hosts: localhost

  vars:
    ansible_raw_suffix: "-{{ ansible_yum_version | default('') }}"
    ansible_suffix: "{{ ansible_yum_version is defined | ternary(ansible_raw_suffix, '') }}"
    docker_raw_suffix: "-{{ docker_yum_version | default('') }}"
    docker_suffix: "{{ docker_yum_version is defined | ternary(docker_raw_suffix, '') }}"

  tasks:
    - name: install packages
      yum: 
        name: 
          - "ansible{{ ansible_suffix }}"
          - "docker{{ docker_suffix }}"
        state: "{{ yum_state | default('present') }}"
      become: yes

With the above, you can:

  • install to the latest version if first time install
ansible-playbook software.yml
  • install a specific version of one or both softwares:
ansible-playbook software.yml -e ansible_yum_version=2.9.2 -e docker_yum_version=20.10.6
  • upgrade to the lastest version
ansible-playbook software.yml -e yum_state=latest

I will let you go on with this to add more features (e.g. allow downgrades) if you feel you still want to walk that path.

Upvotes: 0

Related Questions