Using Assert to Create a Test Suite


Within software development circles, there’s an idea called “Test Driven Development” and since the basic idea behind Ansible is to treat “infrastructure as code” – why wouldn’t you want to do some testing to verify the changes you intended to make are in fact made?

This is where the Assert statement in Ansible comes in, it allows you to test for expected values and then you’ll get a failure if the expected value isn’t returned.

Here’s an example:

Test Case Description

Verify that docker containers have associated AppArmor profiles.

Test Case

- name: 5.1 | Ensure AppArmor Profile is Enabled
  block:
    - name: Get list of docker containers
      shell: docker ps --quiet --all
      register: docker_containers
      changed_when: false
    
    - name: Get container information and pars AppArmor info
      shell: docker inspect --format '{{ '{{' }} .Id {{ '}}' }}{{ ':' }} AppArmorProfile={{ '{{' }} .AppArmorProfile {{ '}}' }}' {{ item }}
      loop: "{{ docker_ontainers.stdout_lines }}"
      register: container_info
      changed_when: false

    - name: Assert that all Docker containers have an AppArmor profile
      assert:
        that:
          - item is match('^.*AppArmorProfile=.*$')
        fail_msg: "Docker container {{ item.split()[0] }} does not have an AppArmor profile"
      loop: "{{ container_info.results | map(attribute='stdout') | list }}"
      changed_when: false


Leave a Reply

Your email address will not be published. Required fields are marked *