首页 > 解决方案 > 如何使用其他列表项编写循环?

问题描述

我不熟悉 Ansible 并且正在努力编写脚本。

在第一个任务中,如果目标作业能够终止,则执行查询。在任务 2 中,执行另一个查询以终止满足条件的作业。但是,task1 和 task 2 是按顺序执行的,所以我没有解决方案来使用存储的值job_id_listquery_result组合使用的值。

# task1
- name: Check the status of specific jobs
  become: true
  become_user: postgres
  shell: psql -t -database -c "select count(*) from table_a a inner join table_b b on b.job_id = a.job_id where b.job_id={{ item }} and b.submitted_date > CURRENT_TIMESTAMP - interval '10 minutes';"
  with_items: {{ job_id_list }}
  register: query_result

# task2
- name: kill job when the result of task1 is 0
  shell: psql -t database -c "update table_b set status='TERMINATED' where job_id={{ XXX }};" # here I struggle...
  with_items: {{ query_result }}
  become: true
  become_user: postgres
  when: query_result.stdout|int = 0

标签: ansible

解决方案


你有job_id_listwhich 是你在 Task#1 中迭代的项目列表。查询您返回的数据库,该数据库count(*)返回该 job_id 的编号。在 Task#2 中,您想要遍历查询结果,它是一个数字或数字列表(作业计数),而您在这里没有 job_id。您必须遍历相同的列表job_id_list,但只有当query_result为 0 才能获得job_id可用的列表。我希望这有帮助!

编辑:当我再次重新阅读查询时,我认为您的逻辑可能是错误的。您可以获取 id 返回,然后在 Task#2 中迭代要更新的 id 列表,而不是获取计数。


推荐阅读