This challenge will test your ability to use conditionals, variable prompts, and task execution based on variable values in an Ansible playbook. By constructing a playbook that incorporates these elements, you will enhance your skills in creating dynamic and interactive automation scripts.
- Prompt the user for input using
vars_prompt
. - Validate and use the input with conditionals.
- Execute tasks based on logical conditions.
- Basic knowledge of Ansible playbooks.
- Ansible installed on your ansible machine.
- Access to target hosts categorized as "webservers."
Estimated Time: 30 minutes
-
Create a YAML file named
conditional_prompt_challenge.yml
. -
Define the play's name, target hosts, and skip fact gathering:
--- - name: Conditional play hosts: webservers gather_facts: no
-
Add a
vars_prompt
section to solicit user input for a variable namedquestion
. The input should be either "yes" or "no":vars_prompt: - name: "question" prompt: "Please answer 'yes' or 'no'" private: no
-
Add the following pre-defined variables:
vars: epic: true distro: "Ubuntu"
Explanation:
epic
: A boolean variable.distro
: Represents the operating system.
-
Add a task to validate that the
question
variable holds a valid value:- name: Validate user input assert: that: - question in ["yes", "no"] fail_msg: "Invalid input. Please enter 'yes' or 'no'."
-
Add the first task to execute if
question
is "yes" anddistro
is "Ubuntu":- name: Print message if question is 'yes' and distro is Ubuntu debug: msg: "Condition met: question is 'yes' and distro is Ubuntu." when: question == "yes" and distro == "Ubuntu"
-
Add the second task to execute if
question
is "no" orepic
is true:- name: Print message if question is 'no' or epic is true debug: msg: "Condition met: question is 'no' or epic is true." when: question == "no" or epic
-
Save the
conditional_prompt_challenge.yml
file. -
Run the playbook using the following command:
ansible-playbook conditional_prompt_challenge.yml
-
Provide input when prompted and observe the task execution based on the conditions.
You can compare your solution with the provided examples:
In this challenge, you practiced creating Ansible playbooks that prompt users for input, validate the input, and execute tasks based on logical conditions. Mastering these techniques is essential for creating dynamic and adaptable automation scripts in Ansible. Keep refining your skills to handle more complex scenarios! 👏