如何在Ansible中跳过角色执行

23

我试着为我的Vagrant虚拟机编写playbook.yml文件,但面临以下问题。 Ansible提示我设置这些变量,我将这些变量设置为null/false/no/[just enter],但是角色仍然被执行了!我该如何防止这种行为?我只想在没有设置变量时不执行任何操作。

---
- name: Deploy Webserver
  hosts: webservers
  vars_prompt:
    run_common: "Run common tasks?"
    run_wordpress: "Run Wordpress tasks?"
    run_yii: "Run Yii tasks?"
    run_mariadb: "Run MariaDB tasks?"
    run_nginx: "Run Nginx tasks?"
    run_php5: "Run PHP5 tasks?"

  roles:
    - { role: common, when: run_common is defined }
    - { role: mariadb, when: run_mariadb is defined }
    - { role: wordpress, when: run_wordpress is defined }
    - { role: yii, when: run_yii is defined }
    - { role: nginx, when: run_nginx is defined }
    - { role: php5, when: run_php5 is defined }
1个回答

40

我认为当您使用vars_prompt时,变量将始终被定义,因此“已定义”的情况将始终为真。您可能想要的是以下内容:

- name: Deploy Webserver
  hosts: webservers
  vars_prompt:
    - name: run_common
      prompt: "Product release version"
      default: "Y"

  roles:
    - { role: common, when: run_common == "Y" }

编辑:回答你的问题,不会导致错误。 我制作了一个稍微不同的版本,并使用 ansible 1.4.4 进行了测试:

- name: Deploy Webserver
  hosts: localohst
  vars_prompt:
    - name: run_common
      prompt: "Product release version"
      default: "N"

  roles:
    - { role: common, when: run_common == "Y" or run_common == "y" }

而 roles/common/tasks/main.yml 包含:

- local_action: debug msg="Debug Message"

如果您运行上面的示例并只是按回车键接受默认值,则角色将被跳过:

Product release version [N]:

PLAY [Deploy Webserver] *******************************************************

GATHERING FACTS ***************************************************************
ok: [localhost]

TASK: [common | debug msg="Debug Message"] ************************************
skipping: [localhost]

PLAY RECAP ********************************************************************
localhost            : ok=1    changed=0    unreachable=0    failed=0

但是,如果您在提示时输入Y或y,则将按预期执行该角色:

Product release version [N]:y

PLAY [Deploy Webserver] *******************************************************

GATHERING FACTS ***************************************************************
ok: [localhost]

TASK: [common | debug msg="Debug Message"] ************************************
ok: [localhost] => {
    "item": "",
    "msg": "Debug Message"
}

PLAY RECAP ********************************************************************
localhost            : ok=2    changed=0    unreachable=0    failed=0

据我所知,当run_common不匹配"Y"时,此示例会抛出错误。您测试过吗? - Timur Fayzrakhmanov
1
查看我编辑过的示例,展示了两种运行方式的输出结果。 - Bruce P

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接