如何跳过Ansible中的角色执行

时间:2014-01-11 14:01:26

标签: deployment webserver vagrant administration ansible

抱歉我犯过的错误,我不是英国人。

我尝试为我的流浪汉机器编写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 个答案:

答案 0 :(得分:24)

我相信在使用vars_prompt时将始终定义变量,因此“已定义”将始终为true。您可能想要的是这些内容:

- 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" }

而角色/ common / tasks / main.yml包含:

- local_action: debug msg="Debug Message"

如果您运行上面的示例并按Enter键,接受默认值,则跳过该角色:

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