1

I'm new in Ansible and I try to do some practice playbook. I write a playbook to deploy a Docker container as follows. I write a task in the block section if an error happened, run a task in the rescue section based on Failed message content. For example, I want to run a specific task to delete an existing container if the Failed message is something like this:

failed: [192.168.1.140] (item=stderr_lines) => {"changed": true, "cmd": ["docker", "run", "-itd", "--name", "h1", "-p", "80:80", "httpd"], "delta": "0:00:00.016385", "end": "2021-01-04 03:00:55.403364", "failed_when_result": true, "item": "stderr_lines", "msg": "non-zero return code", "rc": 125, "start": "2021-01-04 03:00:55.386979", "stderr": "/usr/bin/docker-current: Error response from daemon: Conflict. The container name "/h1" is already in use by container bc5cc803a5f4321358992d06097ce271f3a63b8eba19900cfc0d23e321a4e243. You have to remove (or rename) that container to be able to reuse that name..\nSee '/usr/bin/docker-current run --help'.", "stderr_lines": ["/usr/bin/docker-current: Error response from daemon: Conflict. The container name "/h1" is already in use by container bc5cc803a5f4321358992d06097ce271f3a63b8eba19900cfc0d23e321a4e243. You have to remove (or rename) that container to be able to reuse that name..", "See '/usr/bin/docker-current run --help'."], "stdout": "", "stdout_lines": []}"


My playbook is as follows but it didn't work correctly. Sometimes an error in reading dictionary or "Unexpected templating type error occurred on". Can somebody guide me on what should I write?

- name: run a container
  vars:
   - run_container: docker run -itd --name h1 -p 80:80 httpd
   - rm_container: docker stop h1 && docker rm h1

  hosts: 192.168.x.x
  tasks:
  - name: check docker container
    block:
    - name: run a container httpd
      command: "{{run_container}}"
      register: rss
      with_items:
        - "stderr_lines"
      failed_when: "'Error' in rss.stderr"

    rescue:
     - name: iterate over list
       debug:
         msg: "{{item.value}}"
       loop: "{{rss | dict2items}}"

     - name: remove the exited container
       command: "{{rm_container}}"
       register: rs
       with_items:
        - "{{rss | dict2items}}"
       when: item.value is search("The container name .* is already in use")
3

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.