未定义变量时跳过 Ansible 任务 [英] Skip Ansible task when variable not defined

查看:30
本文介绍了未定义变量时跳过 Ansible 任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在剧本中有以下任务:

I have the following task in a playbook:

- name: task xyz  
  copy:  
    src="{{ item }}"  
    dest="/tmp/{{ item }}"  
  with_items: "{{ y.z }}"  
  when: y.z is defined  

y.z 未定义,因此我希望跳过该任务.相反,我收到:

y.z is not defined, so I'm expecting the task to be skipped. Instead, I receive:

FAILED! => {"failed": true, "msg": "'dict object' has no attribute 'z'"

我发现:如何在变量未定义时运行任务可以吗?但似乎我就是这样做的.我在这里做错了什么?

I have found: How to run a task when variable is undefined in ansible? but it seems I implemented just that. What am I doing wrong here?

推荐答案

这里的问题是 with_itemswhen 之前被评估.实际上,在实际场景中,您将 item 放在 when 条件中.请参阅:循环和条件.

The problem here is that with_items is evaluated before when. Actually in real scenarios you put item in the when conditional. See: Loops and Conditionals.

此任务适合您:

- name: task xyz
  copy:  
    src: "{{ item }}"  
    dest: "/tmp/{{ item }}"  
  with_items: "{{ (y|default([])).z | default([]) }}"

这篇关于未定义变量时跳过 Ansible 任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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