skip to Main Content

I’m trying to make a conditional “when” in my ansible playbook.
If docker not installed, install docker.
So i have a playbook, with a role with some tasks in it.
And i would like to do something like

when: docker != not exist

or

when: docker == false

When i get setup, from one with docker installed i get this:

"ansible_docker0": {
            "active": true,
            "device": "docker0",
            "features": {
When no docker : 
SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    },
    "changed": false

3

Answers


  1. Chosen as BEST ANSWER

    It just seems that, the task still running, and installing docker. ? Should it not be skipped if it is installed ?

    I'm also looking for the other way around. If the docker (or something else ) is installed, then skip the rest of the tasks.


  2. Q: “If docker not installed, install docker.”

    A: Use package – Generic OS package manager. The task below will install the package if it has not been installed yet. It’s conditional by default.

    - name: install package
      package:
        name: "{{ package }}"
        state: present
    

    Q: “How to check if docker is installed – ansible – centos”

    A: For details see How to get the installed yum packages with Ansible?.

    Login or Signup to reply.
  3. You can check if something is installed from trying a simple command, register the output, use the output.failed in the when: section of your install tasks to only run when your check failed.

    Using docker as an example.
    Version command in a task:

    - name: Check If Docker Is Installed
      command: docker --version
      register: docker_valid
      ignore_errors: yes
    

    If you don’t include ignore_errors: yes and you don’t have it installed, then your playbook running the task will exit, and we want to continue.

    You can use the debug module to print the registered variables to the output

    - name: Debug Docker Output
      debug:
        var: docker_valid
    

    Next task only runs if the docker_vaild.failed returns true, because of the when clause. Add this when: in each task you want to run when docker is not installed. If docker is installed then these tasks will be skipped.

    - name: Install Docker pre-requisites
      yum:
        name: yum-utils
        state: latest
      when: docker_valid.failed
    ...
    

    Using that format you can install docker or anything else you need.

    To reverse the conditional then you add not on the when: clause.

    - name: Run Task If Docker is Already Installed 
      debug:
        msg: "will run if docker is installed"
      when: not docker_valid.failed
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search