Как запустить задачу, когда переменная undefined недоступна?
Я ищу способ выполнить задачу, когда изменяемая переменная не является регистром / undefined e.g
-- 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
Ответы
Ответ 1
Из ansible docs:
Если требуемая переменная не была установлена, вы можете пропустить или не сработать с помощью теста Jinja2s. Например:
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
должен работать
Ответ 2
Согласно последней версии Ansible 2.5, чтобы проверить, определена ли переменная, и в зависимости от этого, если вы хотите запустить какую-либо задачу, используйте undefined
ключевое слово.
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 Документация
Ответ 3
Строго указано, что вы должны проверить все следующее: определено, не пусто И не Нет.
Для "нормальных" переменных это имеет значение, если они определены и установлены или не установлены. Смотрите foo
и bar
в примере ниже. Оба определены, но установлен только foo
.
С другой стороны, зарегистрированные переменные устанавливаются в результате выполнения команды и варьируются от модуля к модулю. В основном это структуры JSON. Вы, вероятно, должны проверить подэлемент вас интересует См. xyz
и xyz.msg
в примере ниже:
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
Ответ 4
Для этого вы можете использовать непонятную последовательность фильтров, выражений регулярных выражений и проверок на равенство.
#!/usr/bin/env ansible-playbook
- name: Lets munge some data
hosts: localhost
gather_facts: false
become: false
vars:
array:
- 445533
- 112234-538
- 11
- 1111
- 1111-1111
- 11-11
tasks:
- name: Replace hypens when starting with 4 numbers
debug:
msg: "{{ ((item | string)[0:4] | regex_search('[0-9]{4}') | string != 'None')
| ternary((item | regex_replace('-', '_')), item) }}"
loop: "{{ array }}"
PLAY [Lets munge some data] *****************************************************************************************************************************************************************************************************
TASK [Replace hypens when starting with 4 numbers] ******************************************************************************************************************************************************************************
ok: [localhost] => (item=445533) => {
"msg": "445533"
}
ok: [localhost] => (item=112234-538) => {
"msg": "112234_538"
}
ok: [localhost] => (item=11) => {
"msg": "11"
}
ok: [localhost] => (item=1111) => {
"msg": "1111"
}
ok: [localhost] => (item=1111-1111) => {
"msg": "1111_1111"
}
ok: [localhost] => (item=11-11) => {
"msg": "11-11"
}
PLAY RECAP **********************************************************************************************************************************************************************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0