Tanner Semerad
Tanner Semerad

Reputation: 12672

How to check if list of strings are present in command output in Ansible?

I want to run an Ansible action on the condition that a shell command doesn't return the expected output. ogr2ogr --formats pretty-prints a list of compatible file formats. I want to grep the formats output, and if my expected file formats aren't in the output, I want to run a command to install these components. Does anyone know how to do this?

- name: check if proper ogr formats set up
  command: ogr2ogr --formats | grep $item
  with_items:
    - PostgreSQL
    - FileGDB
    - Spatialite
  register: ogr_check

# If grep from ogr_check didn't find a certain format from with_items, run this
- name: install proper ogr formats
  action: DO STUFF
  when: Not sure what to do here

Upvotes: 27

Views: 53860

Answers (2)

Tomas Pytel
Tomas Pytel

Reputation: 188

My solution :

- name: "Get Ruby version"
command: "/home/deploy_user/.rbenv/shims/ruby -v"
changed_when: true
register: ruby_installed_version
ignore_errors: true

- name: "Installing Ruby 2.2.4"
command: '/home/deploy_user/.rbenv/libexec/rbenv install -v {{ruby_version}}'
become: yes
become_user: deployer
when: " ( ruby_installed_version | failed ) or ('{{ruby_version}}' not in ruby_installed_version.stdout) "

Upvotes: 11

Dan
Dan

Reputation: 1745

First, please make sure you are using Ansible 1.3 or later. Ansible is still changing pretty quickly from what I can see, and a lot of awesome features and bug fixes are crucial.

As for checking, you can try something like this, taking advantage of grep's exit code:

- name: check if proper ogr formats set up
  shell: ogr2ogr --formats | grep $item
  with_items:
    - PostgreSQL
    - FileGDB
    - Spatialite
  register: ogr_check
  # grep will exit with 1 when no results found. 
  # This causes the task not to halt play.
  ignore_errors: true

- name: install proper ogr formats
  action: DO STUFF
  when: ogr_check|failed

There are some other useful register variables, namely item.stdout_lines. If you'd like to see what's registered to the variable in detail, try the following task:

- debug: msg={{ogr_check}}

and then run the task in double verbose mode via ansible-playbook my-playbook.yml -vv. It will spit out a lot of useful dictionary values.

Upvotes: 36

Related Questions