diff --git a/110.Conditional/110.Conditional.md b/110.Conditional/110.Conditional.md new file mode 100644 index 0000000..0098c56 --- /dev/null +++ b/110.Conditional/110.Conditional.md @@ -0,0 +1,25 @@ +# 11 - Conditionals + +This exercise makes you write a playbooks with tasks that are run when specific condition is met. + +## Playbook Creation + +Write a playbook following the given specs: +* Run on host group `lab` +* Reboot the server if the uptime is more than 600 seconds +* Wait for the server to reboot +* Print a message stating that "Host has been rebooted" (only if it has been rebooted) + +## Hints and Caveats +* If you just run the reboot command, Ansible will fail because the connection will be lost with the managed host. +* You must use the `poll` and `async` task settings to run the reboot task asynchronously. +* There is a `wait_for_connection` module that may be useful. +* You need the reboot task to be run even if Ansible close the session and you need to give some time to Ansible to perform its operation before the actual reboot. For this run it like this: +```bash +nohup sh -c '(sleep 5 ; reboot)' +``` +* Because of [this bug](https://github.com/ansible/ansible/issues/37941), asynchronous tasks seems to be failing with Python 3. Use Python2 instead. + +## Validation + +There is a working playbook in `solution/solution.yml`. diff --git a/110.Conditional/solution/solution.yml b/110.Conditional/solution/solution.yml new file mode 100644 index 0000000..e04b5cf --- /dev/null +++ b/110.Conditional/solution/solution.yml @@ -0,0 +1,22 @@ +- hosts: lab + gather_facts: true + tasks: + - name: Reboot the host if it is up for more than 600s + shell: nohup sh -c '(sleep 5 ; reboot)' + become: true + poll: 0 + async: 1 + ignore_errors: true + when: ansible_uptime_seconds > 600 + notify: + - Wait for Reboot + - Rebooted msg + handlers: + - name: Wait for Reboot + wait_for_connection: + delay: 10 + - name: Rebooted msg + debug: + msg: "Host {{ ansible_ssh_host }} has been rebooted" + +# vim: set ft=yaml sw=2 et: diff --git a/README.md b/README.md index 9afa5fa..71f6ffe 100644 --- a/README.md +++ b/README.md @@ -16,5 +16,6 @@ Install Ansible and clone this repo. Customize the `hosts` file to your lab setu 1. [Loops](080.Loops/080.Loops.md) 1. [Vault](090.Vault/090.Vault.md) 1. [User Prompt](100.Prompt/100.Prompt.md) +1. [Conditionals](110.Conditionals/110.Conditionals.md)