首页 > 解决方案 > Ansible 中基于 vars_prompt 有条件地导入剧本

问题描述

我正在使用以下 ansible 脚本根据用户输入导入剧本,

---
- hosts: localhost
  vars_prompt:
    - name: "cleanup"
      prompt: "Do you want to run cleanup? Enter [yes/no]"
      private: no

- name: run the cleanup yaml file
  import_playbook: cleanup.yml
  when: cleanup == "yes"

执行日志:

bash-$ ansible-playbook -i hosts cleanup.yml

Do you want to run cleanup? Enter [yes/no]: no

PLAY [localhost] *********************************************************************************************************************

TASK [Gathering Facts] ***************************************************************************************************************
ok: [127.0.0.1]

PLAY [master] ********************************************************************************************************************

TASK [Gathering Facts] ***************************************************************************************************************
fatal: [192.168.56.128]: FAILED! => {"msg": "The conditional check 'cleanup == \"yes\"' failed. The error was: error while evaluating conditional (cleanup == \"yes\"): 'cleanup' is undefined"}
        to retry, use: --limit @/home/admin/playbook/cleanup.retry

PLAY RECAP ***************************************************************************************************************************
127.0.0.1                  : ok=1    changed=0    unreachable=0    failed=0
192.168.56.128             : ok=0    changed=0    unreachable=0    failed=1

它在导入的剧本中而不是在邮件剧本中引发错误。请帮助我根据用户输入导入剧本。

标签: ansibledevops

解决方案


vars_prompt变量仅在调用它们的剧本中定义。为了在其他游戏中使用它们,一种解决方法是使用set_fact将变量绑定到主机,然后使用hostvars从第二次游戏访问该值。

例如:

---
- hosts: localhost
  vars_prompt:
    - name: "cleanup"
      prompt: "Do you want to run cleanup? Enter [yes/no]"
      private: no
  tasks:
    - set_fact:
          cleanup: "{{cleanup}}"
    - debug:
          msg: 'cleanup is available in the play using: {{cleanup}}'
    - debug:
          msg: 'cleanup is also available globally using: {{hostvars["localhost"]["cleanup"]}}'

- name: run the cleanup yaml file
  import_playbook: cleanup.yml
  when: hostvars["localhost"]["cleanup"] == True

推荐阅读