Do a copy but restart if condition is true

Viewed 53

I want to copy a directory conf on remote server. I want to make a copy whatever happens, but I want to trigger the reload of Docker only if the container exists.

In other words:

  • if the container does not exist, make only a copy of directory Configuration
  • if the container exists, make a copy of the directory Configuration and reload the container with a handler
- name: Get infos container
  docker_container_info:
    name: "docker_name"
  register: result

- name: Print the status of docker
  debug:
    msg: "docker {{ 'running' if result.container['State']['Status'] == 'running' else 'is not running' }}"

- name: Copy conf
  copy:
    src: "templates/etc/conf"
    dest: "/etc/conf"
  notify:
    - reload docker
  when: not result.container['State']['Status'] != 'running'

I try to set the when condition after notify, but it always reload the container.

Moreover how to skip the Get infos container task, when docker does not exist ? because when docker does not exist, I get

'result' is undefined\n\nThe error appears

and cannot make evaluation

1 Answers

you put your condition on handlers:

- name: Copy conf
  copy:
    src: "templates/etc/conf"
    dest: "/etc/conf"
  notify:
    - reload docker


  handlers:
    - name: reload docker
      debug:
        msg: "docker reloaded"
      when: result.container.State.Status is defined and result.container.State.Status == 'running'
Related