Stepan's blog

Tips for writing infrastructure tests

When you writing your tests it is better to remember that fastest test feedback will save your time. Based on this it is great to instruct your playbooks with smoke tests that will validate state of deployed component. And what could provide faster feedback that ansible’s failed_when and until.

So here are example how to validate state of docker container :

    - name: Validate that envoy container running
      shell: |
        sleep 10
        docker inspect --format="{{.State.Status' }}" envoy
      changed_when: False
      retries: 5
      delay: 5
      register: inspect_status
      until: inspect_status.stdout.find("running") != -1


Running this kind of tests for each component is crucial for delivering consistent infrastructure. In other words you need to automate smoke tests execution within ansible playbooks for each component.

And here are some more examples of various validations…

Fail when line apears in stdout:

- fail: msg="There is conflicts "
     when: 'oracle_conflict_patches.stdout is search("Prereq.+failed")'

And even multiple conditions:

register: ecmf_configmigrate
  failed_when: >
    ( not ecmf_configmigrate.stdout | regex_search("^BUILD SUCCESSFUL", multiline=True) ) and
    ("No such file or directory" not in ecmf_configmigrate.stdout )
  changed_when: >
    (  ecmf_configmigrate.stdout | regex_search("^BUILD SUCCESSFUL", multiline=True) )

Assert also helps:

  - name: Assert that token configured correctly
    assert:
      that:
        - vault_token | length > 1
        - vault_token is regex("^s\.\w+$")

This project is maintained by stepan111