不满足条件时如何跳过任务

时间:2019-03-18 17:14:28

标签: python ansible yaml conditional-statements

在以下任务中担任角色,如果 my_environment var是“ prod” ,则该任务应该创建cron作业。

我希望剧本在不满足条件的情况下跳过而不是失败:

---
- name: Configure cron job to export patch logs
  cron:
    name: export patch logs daily
    minute: 0
    hour: 0
    user: root
    cron_file: patch_logs
    job: "/usr/local/bin/aws s3 cp /var/log/dpkg.log s3://{{ patch_logs_bucket }}/dpkg.log.$(hostname).$(date +\\%F)"
  when: my_environment == "prod"

失败消息:

TASK [ansible-contxt-base : Configure cron job to export patch logs] ***********
    fatal: [ubuntu-1604]: FAILED! => {"msg": "The conditional check 'scx_environment == \"prod\"' failed. The error was: error while evaluating conditional (scx_environment == \"prod\"): 'my_environment' is undefined\n\nThe error appears to have been in '/**<path>**/tasks/base.yml': line 125, 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: Configure cron job to export patch logs\n  ^ here\n"}

3 个答案:

答案 0 :(得分:0)

when:

my_environment is defined

my_environment != ”prod”

答案 1 :(得分:0)

我们可以将jinja2快捷方式用于'default(False)’:'d(False)'。

when: my_environment|d(False) == "prod"

答案 2 :(得分:0)

在这里找到https://ansible-docs.readthedocs.io/zh/stable-2.0/rst/playbooks_conditionals.html#the-when-statement

- shell: echo "This certainly isn't epic!"
  when: not epic

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