当给一个变量多个输入时,有条件地运行任务 [英] conditionally run tasks when given multiple input to a variable

查看:24
本文介绍了当给一个变量多个输入时,有条件地运行任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个 ansible 脚本,当变量只有 1 个输入时,它运行良好:

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

以下是我在只为 service_name 定义了一项服务时正在使用和工作的任务:---

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

当我在定义多个 service_name 后运行剧本时.它在步骤检查服务状态中显示失败服务状态,但在其余步骤中显示正常.当我检查服务状态时,没有任何变化.我怎样才能使它适用于多个 service_names ???

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 ???

所以我在这里脚本应该做什么(我坚持第 2 点和第 3 点,有人可以告诉我需要做什么才能使它工作):

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. 脚本将检查提到的所有服务的状态(它正确地执行此操作)

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

如果服务状态之一显示为停止.它将执行将运行命令以恢复该特定服务的任务.

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.

如果服务启动后仍然没有出现,那么脚本应该会失败(我还没有为这部分编写代码).

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

推荐答案

老实说,您的问题的答案在文档中:在循环中使用 register.

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}}"

这篇关于当给一个变量多个输入时,有条件地运行任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆