Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking output of a shell command in ansible

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?

like image 607
Omri Avatar asked Oct 22 '25 06:10

Omri


1 Answers

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.

like image 107
Charles Duffy Avatar answered Oct 23 '25 19:10

Charles Duffy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!