Checking output of a shell command in ansible

10,739

Consider doing the comparison in your shell command:

  - name: Check if the number of HITACHI devices is equal to 1
    shell: test "$(lsscsi | awk '/HITACHI/ { count++ } END { print count }')" -eq 1

You don't need to use register at all here, since the default failedWhen is when the exit status of a command is nonzero.


If you did want to use register, however:

  - name: Check if the number of HITACHI devices is equal to 1
    shell: lsscsi | awk '/HITACHI/ { count++ } END { print count }'
    register: countHitachiDevices
    failed_when: int(countHitachiDevices.stdout) != 1 

Note the use of failed_when instead of when: A when clause determines if a command is going to be run at all, whereas a failed_when clause determines whether that command is determined to have failed.

Share:
10,739
Omri
Author by

Omri

DevOps Ninja

Updated on June 28, 2022

Comments

  • Omri
    Omri almost 2 years

    I'm trying to write an Ansible script that runs a shell pipeline, and determines whether to terminate the playbook's execution based on that pipeline's output.

    Here is the problematic code:

      - name: Check if the number of HITACHI devices is equal to 1
        shell: lsscsi | grep HITACHI | awk '{print $6}' | wc -l
        register: numOfDevices
        when: numOfDevices|int  == 1
    

    Here is the error:

    {  
       "failed":true,
       "msg":"The conditional check 'numOfDevices|int  == 1' failed.  
    The error was: error while evaluating conditional (numOfDevices|int  == 1): 'numOfDevices' is undefined\n\nThe error appears to have been in '/etc/ansible/config/test.yml': line 14, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n  - name: Check if the number of HITACHI devices is equal to 1\n    ^ here\n"
    }
    

    Can someone tells me what could be the issue?