如何根据ansible中的条件仅使用3个变量中的一个?

问题描述 投票:0回答:1

我要根据条件注册三个变量,它将运行一个任务并注册一个变量,我如何为各个任务使用测试变量?

---
- name: Test1
  command" "echo HAHA"
  register: testing
  when: HAHA is defined

- name: Test2
  command" "echo BLABLA"
  register: testing
  when: BLABLA is defined

- name: Test3
  command" "echo DODO"
  register: testing
  when: DODO is defined
  
- name: Verify Tests
  command: "execute {{ testing.stdout }}"
  when: TEST is defined

我收到了类似未定义变量的错误,如下所示:

{"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'stdout'\n\nThe error appears to be in '/home/ubuntu/tests/': line 3, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: Verify Tests \n  ^ here\n"

您能推荐一个吗?

linux ansible ansible-facts ansible-template
1个回答
0
投票

使用

debug
任务来验证您的变量是否包含您认为它们包含的内容总是一个好主意。

当您在任务中使用

register
时,它总是设置命名变量,无论任务是否运行。这是因为注册值包含有关任务执行状态的信息。例如,如果未设置变量
DODO
,则在最终任务中,变量
testing
将包含:

ok: [localhost] => {
    "testing": {
        "changed": false,
        "false_condition": "DODO is defined",
        "skip_reason": "Conditional result was False",
        "skipped": true
    }
}

如您所见,这里没有

stdout
属性。对于您想要的行为,您可以像这样重写您的剧本:

- hosts: localhost
  gather_facts: false
  tasks:
  - name: Test1
    command: "echo HAHA"
    register: testing1
    when: HAHA is defined

  - name: Test2
    command: "echo BLABLA"
    register: testing2
    when: BLABLA is defined

  - name: Test3
    command: "echo DODO"
    register: testing3
    when: DODO is defined

  - set_fact:
      testing: >-
        {{
          [testing1, testing2, testing3] | selectattr("stdout", "defined")
        }}
    
  - name: Verify Tests
    when: testing
    debug:
      msg: "execute {{ testing[0].stdout }}"

在没有定义变量的情况下运行此命令会导致:

TASK [Verify Tests] *************************************************************************************************************************
skipping: [localhost]

但是如果我们定义目标变量:

$ ansible-playbook playbook.yaml -e DODO=1
.
.
.
TASK [Verify Tests] *************************************************************************************************************************
ok: [localhost] => {
    "msg": "execute DODO"
}

或者:

$ ansible-playbook playbook.yaml -e HAHA=1
.
.
.
TASK [Verify Tests] *************************************************************************************************************************
ok: [localhost] => {
    "msg": "execute HAHA"
}

如果设置了多个变量,您将从第一个执行的任务中获取值:

$ ansible-playbook playbook.yaml -e HAHA=1 -e DODO=1
.
.
.
TASK [Verify Tests] *************************************************************************************************************************
ok: [localhost] => {
    "msg": "execute HAHA"
}
© www.soinside.com 2019 - 2024. All rights reserved.