MasterCheffinator
MasterCheffinator

Reputation: 343

How to validate that a file has a specific substring with Ansible?

I would like to have an assert or fail task in my Ansible play that validates that the right code build was deployed. The deployment comes with a version.properties file which has the build info I care about.

The 'correct' code version comes from a vars file and is called desired_build_id.

How can I validate that my version.properties mentions this build ID? Some sort of substring search?

I've tried the following:

--- 
- name: Validate deployment success
  hosts: app-nodes
  tasks:
    - name: Read version.properties file
      shell: cat /path/to/version.properties
      register: version_prop_content

    - fail: Wrong build ID found in version.properties
      when: desired_build_id not in version_prop_content.stdout 

However, that gives a error: error while evaluating conditional: esired_build_id not in version_prop_content.stdout

What's the right syntax for this? Or, is there a better way?

Upvotes: 4

Views: 6487

Answers (2)

Kashyap
Kashyap

Reputation: 17556

A much simpler python expression would also do:

- name: Read version.properties file
  shell: cat /path/to/version.properties
  register: version_prop_content

- debug: msg="desired build installed"
  when: "'{{desired_build_id}}' in '{{version_prop_content.stdout}}'"

Or as I always recommend, avoid using ansible as far as possible:

- name: verify version
  shell: grep '{{desired_build_id}}' /path/to/version.properties

Upvotes: 4

MasterCheffinator
MasterCheffinator

Reputation: 343

Figured it out!

The way to do the substring comparison is with version_prop_content.stdout.find(desired_build_id) > 0 which is true if the substring is present

The find command returns index of the substring and -1 if it is not present.

I also changed it to an assert tasks to make it look a bit prettier (fail is such an ugly word ;) ).

- name: Check that desired version was deployed
  assert:
    that: 
      - version_prop_content.stdout.find(desired_build_id) > 0

Upvotes: 2

Related Questions