conditionally run tasks when given multiple input

2019-07-23 22:11发布

问题:

I have written a ansible script which runs fine when there is only 1 input to a variable:

---
- hosts: ListA
  vars:
    app-dir: /tmp
    service_name: exampleAAA
    roles:
    - prechecks

Below is the task i am using and working when only one service defined for service_name: ---

- name: check service status
  command: "{{app_dir}}/app-name {{item}} status"
  with_items: '{{service_name}}'
  ignore_errors: yes
  register: service_status

- name: starting service if it's in failed state
  set_fact: serviceTostart={{item}}
  with_items: '{{service_name}}'
  when: service_status | failed

- shell: "{{app_dir}}/app-name {{serviceTostart}} start"
  when: service_status | failed

As per my usecase i need this to work for below:

vars:
  service_name:
  - exampleAAA
  - exampleBBB
  - exampleCCC

When i run the playbook after defining multiple service_name. it shows failed status of service in step check service status but it says ok in rest of the steps. When i check the status of services there is no change. How can i make it work for multiple service_names ???

So here i what the script should do(I am stuck with points 2 & 3, can someone please let me know what need to be done to make it work):

  1. The script will check the status of all the services mentioned (it is doing this correctly)

  2. If one of the service status shows as stop. It will go the tasks which will run the command to bring back that particular service.

  3. If after one start the service still does not come up then script should fail ( I am yet to write code for this part).

回答1:

Honestly the answer to your question is in the documentation: Using register with a loop.

- name: check service status
  command: "{{app_dir}}/app-name {{item}} status"
  with_items: "{{service_name}}"
  ignore_errors: yes
  register: service_status

- shell: "{{app_dir}}/app-name {{item.item}} start"
  when: item | failed
  with_items: "{{service_status.results}}"


标签: ansible