How to run a task when variable is undefined in ansible? Ask Question

How to run a task when variable is undefined in ansible? Ask Question

I am looking for a way to perform a task when Ansible variable is not registers or 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

From the ansible documentation:

必要な変数が設定されていない場合は、Jinja2 の定義済みテストを使用してスキップまたは失敗することができます。例:

tasks:
    - name: Run the command if "foo" is defined
      ansible.builtin.shell: echo "I've got '{{ foo }}' and am not afraid to use it!"
      when: foo is defined

    - name: Fail if "bar" is undefined
      ansible.builtin.fail: msg="Bailing out. This play requires 'bar'"
      when: bar is undefined

したがって、あなたの場合はwhen: deployed_revision is not definedうまくいくはずです。

おすすめ記事