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

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

如果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"}
python ansible yaml condition
3个回答
0
投票
when:

my_environment is defined

my_environment != ”prod”

0
投票

我们可以使用jinja2快捷键'default(False)':'d(False)'。

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

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
© www.soinside.com 2019 - 2024. All rights reserved.