首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在ansible中未定义变量的情况下运行任务?

如何在ansible中未定义变量的情况下运行任务?
EN

Stack Overflow用户
提问于 2015-05-08 17:08:48
回答 3查看 249.4K关注 0票数 142

我正在寻找一种方法来执行任务时,可用变量不是寄存器/undefined,例如

代码语言:javascript
复制
-- name: some task
   command:  sed -n '5p' "{{app.dirs.includes}}/BUILD.info" | awk '{print  $2}'
   when: (! deployed_revision) AND ( !deployed_revision.stdout )
   register: deployed_revision
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-05-08 17:28:22

ansible docs中:如果没有设置所需的变量,则可以使用JJIA2的已定义测试跳过或失败。例如:

代码语言:javascript
复制
tasks:

- shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
  when: foo is defined

- fail: msg="Bailing out. this play requires 'bar'"
  when: bar is not defined

因此,在您的情况下,when: deployed_revision is not defined应该可以工作

票数 251
EN

Stack Overflow用户

发布于 2018-04-10 16:38:52

根据最新的Ansible version2.5,要检查是否定义了变量,并根据此检查是否要运行任何任务,请使用undefined关键字。

代码语言:javascript
复制
tasks:
    - shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
      when: foo is defined

    - fail: msg="Bailing out. this play requires 'bar'"
      when: bar is undefined

Ansible Documentation

票数 21
EN

Stack Overflow用户

发布于 2018-08-16 04:30:07

严格声明,您必须检查以下所有项:已定义、非空和非无。

对于“正常”变量,如果定义并设置或不设置,则会产生差异。请参阅下面示例中的foobar。两者都已定义,但仅设置了foo

另一方面,注册变量被设置为运行命令的结果,并且根据模块的不同而不同。它们大多是json结构。您可能必须检查您感兴趣的子元素。请参见以下示例中的xyzxyz.msg

代码语言:javascript
复制
cat > test.yml <<EOF
- hosts: 127.0.0.1

  vars:
    foo: ""          # foo is defined and foo == '' and foo != None
    bar:             # bar is defined and bar != '' and bar == None

  tasks:

  - debug:
      msg : ""
    register: xyz    # xyz is defined and xyz != '' and xyz != None
                     # xyz.msg is defined and xyz.msg == '' and xyz.msg != None

  - debug:
      msg: "foo is defined and foo == '' and foo != None"
    when: foo is defined and foo == '' and foo != None

  - debug:
      msg: "bar is defined and bar != '' and bar == None"
    when: bar is defined and bar != '' and bar == None

  - debug:
      msg: "xyz is defined and xyz != '' and xyz != None"
    when: xyz is defined and xyz != '' and xyz != None
  - debug:
      msg: "{{ xyz }}"

  - debug:
      msg: "xyz.msg is defined and xyz.msg == '' and xyz.msg != None"
    when: xyz.msg is defined and xyz.msg == '' and xyz.msg != None
  - debug:
      msg: "{{ xyz.msg }}"
EOF
ansible-playbook -v test.yml
票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30119973

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档