Reddy Bhavani Prasad
Reddy Bhavani Prasad

Reputation: 1115

Conditionally import a playbook based on vars_prompt in Ansible

I am using the following ansible script to import a playbook based on the user input,

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

Execution log:

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

It throws error in the imported playbook not in the mail playbook. Please help me to import a playbook based on user input.

Upvotes: 1

Views: 2368

Answers (1)

Alassane Ndiaye
Alassane Ndiaye

Reputation: 4777

vars_prompt variables are only defined in the play in which they were called. In order to use them in other plays, a workaround is to use set_fact to bind the variable to a host, then use hostvars to access that value from the second play.

For instance:

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

Upvotes: 2

Related Questions