{"id":17881,"date":"2022-08-03T18:46:44","date_gmt":"2022-08-03T18:46:44","guid":{"rendered":"https:\/\/linuxways.net\/?p=17881"},"modified":"2024-03-25T02:10:29","modified_gmt":"2024-03-25T02:10:29","slug":"ansible-when-conditionals","status":"publish","type":"post","link":"https:\/\/linuxways.net\/de\/centos\/ansible-when-conditionals\/","title":{"rendered":"Ansible When Conditionals"},"content":{"rendered":"<p>\u201cAnsible is a configuration management tool used for automating remote system management tasks like software deployment and installing updates, configuration management, orchestration, and many other IT tasks.\u201d<\/p>\n<h2><strong>In This Article<\/strong><\/h2>\n<p>We will cover:<\/p>\n<p>1. Purpose of the \u201cWhen\u201d statement.<\/p>\n<p>2. How to use the \u201cWhen\u201d statement in different scenarios.<\/p>\n<p>3. Present some working examples of using the \u201cWhen\u201d statement.<\/p>\n<h2><strong>What Will You Need?<\/strong><\/h2>\n<p>In this tutorial, we assume that:<\/p>\n<p>1. You have installed Ansible on your system(Ubuntu 20.04 in our case).<\/p>\n<p>2. You know what Ansible is used for and how to set up a basic local testing environment.<\/p>\n<h2><strong>Experimental Setup<\/strong><\/h2>\n<p>In this lab, we have an Ansible controller host with Ubuntu 20.04 system. There are two target nodes: one with the Ubuntu 20.04 system and another one with Debian Buster.<\/p>\n<h2><strong>The When Clause in Ansible<\/strong><\/h2>\n<p>Suppose you are working on a certain Ansible project, and at a certain point, you want to skip a specific step for a specific host. To understand it better, let&#8217;s take an example, suppose you want to skip installing some sort of package on a host if the required version of the software is not available. This is where the \u201cWhen\u201d clause comes in handy. This is pretty simple to use, as we will see it later.<\/p>\n<h2><strong>1. A Simple Conditional With \u201cwhen\u201d<\/strong><\/h2>\n<p>A basic conditional statement works with a single task. What you have to do is to create a task and then add a condition using the \u201cwhen\u201d statement. This \u201cwhen\u201d statement applies to a test or simply a condition for this task. Look at this example:<\/p>\n<pre>\r\ntasks:\r\n- name: Running shutdown command on CentOS-based systems\r\n\r\nansible.builtin.command: \/sbin\/shutdown -t now\r\n\r\nwhen: ansible_facts['os_family'] == \"CentOS\"\r\n<\/pre>\n<p>When a task or playbook is executed, the tests are checked against all the hosts. If the test is passed for any host, Ansible will execute the task; otherwise, it will skip the execution. In the above example, the shutdown command will be executed for any system that matches the criteria of being a CentOS-based OS.<\/p>\n<h2><strong>2. Using the \u201cansible_facts\u201d With the \u201cwhen\u201d Conditional<\/strong><\/h2>\n<p>A task can also be skipped based on facts. Facts are property of a host, such as IP of the host, type of operating system, etc. The following are some fact-based use cases:<\/p>\n<p>1. Installing a package for a particular OS version.<\/p>\n<p>2. Skipping firewall configuration on hosts with private IP addresses.<\/p>\n<p>3. Shutting down system with specific OS family.<\/p>\n<p>Multiple conditions for a \u201cwhen\u201d clause can also be merged. This uses logical operators<strong><em> like or not. <\/em><\/strong>An example is shown below:<\/p>\n<pre>\r\ntasks:\r\n\r\n\r\n- name: Shut off Debian 10 and Debian 11 systems\r\n\r\nansible.builtin.command: \/sbin\/shutdown -t now\r\n\r\nwhen: (ansible_facts['distribution'] == \"Debian\" and ansible_facts['distribution_major_version'] == \"10\") or\r\n\r\n(ansible_facts['distribution'] == \"Debian\" and ansible_facts['distribution_major_version'] == \"11\")\r\n<\/pre>\n<p>As mentioned earlier, Ansible performs conditional evaluations on the targets(hosts) prior to running a task. In the task above, If the condition, i.e., the system is Debian 10 or Debian 11, is found to be true, Ansible will execute the requested shutdown task. If the condition is unmet, Ansible will simply skip this task.<\/p>\n<p>If multiple tasks are required to be true simultaneously(a logical \u201cand\u201d condition), we can list them as:<\/p>\n<pre>\r\ntasks:\r\n\r\n- name: Shut off Ubuntu 17.04 systems\r\n\r\nansible.builtin.command: \/sbin\/shutdown -t now\r\n\r\nwhen:\r\n\r\n- ansible_facts['distribution'] == \"Ubuntu\"\r\n\r\n- ansible_facts['distribution_major_version'] == \"17.04\"\r\n<\/pre>\n<h2>3. <strong>Using the \u201cregistered variables\u201d With \u201cwhen\u201d Conditional<\/strong><\/h2>\n<p>In Ansible, registered variables can also be used with conditionals. These variables are obtained from the output of a task in a play and can be used as a base for further tasks.<\/p>\n<p>Example:<\/p>\n<pre>\r\n- hosts: web_servers\r\n\r\ntasks:\r\n\r\n- name: Running a shell command and registering its outcome as a variable using the \u2018register\u2019 keyword.\r\n\r\nansible.builtin.shell: \/usr\/bin\/pwd\r\n\r\nregister: var_object\r\n\r\n&nbsp;\r\n\r\n- name: Running a shell command based on the result of the last task\r\n\r\nansible.builtin.shell: \/usr\/bin\/ls\r\n\r\nwhen: var_object.stdout = =\u201dubuntu\u201d\r\n<\/pre>\n<p>To see how the when clause works in Ansible, let&#8217;s take some working examples.<\/p>\n<h3><strong>Example 1: Basic Usage<\/strong><\/h3>\n<p>In this example, Ansible will check if a specific user exists on the remote host. If the user\u2019s (myuser) directory is found, it will create a file(myfile.txt) inside this directory. First, create a playbook (my-playbook.yml) with the below content:<\/p>\n<pre>\r\n---\r\n\r\n- hosts: all\r\n\r\ngather_facts: no\r\n\r\nbecome: true\r\n\r\ntasks:\r\n\r\n- name: Check if the user is present or not.\r\n\r\nstat:\r\n\r\npath: \/home\/vagrant\r\n\r\nregister: myuser\r\n\r\n- name: If the directory is present, then create a file(myfile.txt)\r\n\r\nfile:\r\n\r\npath: \/home\/vagrant\/myfile.txt\r\n\r\nstate: touch\r\n\r\nwhen: myuser.stat.exists\r\n<\/pre>\n<p>When this playbook is run, the output is as follows:<\/p>\n<p><em><img loading=\"lazy\" decoding=\"async\" width=\"883\" height=\"670\" class=\"wp-image-17886\" src=\"http:\/\/linuxways.net\/wp-content\/uploads\/2022\/08\/word-image-17881-1.png\" srcset=\"https:\/\/linuxways.net\/wp-content\/uploads\/2022\/08\/word-image-17881-1.png 883w, https:\/\/linuxways.net\/wp-content\/uploads\/2022\/08\/word-image-17881-1-300x228.png 300w, https:\/\/linuxways.net\/wp-content\/uploads\/2022\/08\/word-image-17881-1-768x583.png 768w\" sizes=\"auto, (max-width: 883px) 100vw, 883px\" \/><\/em><\/p>\n<h3><strong>Example 2: Usage-based on ansible_facts<\/strong><\/h3>\n<p>In this example, Ansible will gather facts about the OS family and shut off all the Ubuntu-based remote systems using the when statement.<\/p>\n<pre>\r\n---\r\n\r\n- hosts: all\r\n\r\ngather_facts: yes\r\n\r\nbecome: true\r\n\r\ntasks:\r\n\r\n- name: shutdown Debian-based servers\r\n\r\nansible.builtin.command: \/sbin\/shutdown -t now\r\n\r\nwhen: ansible_facts['os_family']==\"Debian\"\r\n<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" width=\"770\" height=\"609\" class=\"wp-image-17887\" src=\"http:\/\/linuxways.net\/wp-content\/uploads\/2022\/08\/word-image-17881-2.png\" srcset=\"https:\/\/linuxways.net\/wp-content\/uploads\/2022\/08\/word-image-17881-2.png 770w, https:\/\/linuxways.net\/wp-content\/uploads\/2022\/08\/word-image-17881-2-300x237.png 300w, https:\/\/linuxways.net\/wp-content\/uploads\/2022\/08\/word-image-17881-2-768x607.png 768w, https:\/\/linuxways.net\/wp-content\/uploads\/2022\/08\/word-image-17881-2-150x120.png 150w\" sizes=\"auto, (max-width: 770px) 100vw, 770px\" \/><\/p>\n<h2><strong>Conclusion<\/strong><\/h2>\n<p>In this guide, we have seen how to use the \u201cwhen\u201d clause in Ansible. We have just seen a high-level overview of the \u201cwhen\u201d statement; you can further explore how to use the \u201cwhen\u201d conditional with loops, imports, and includes statements.<\/p>","protected":false},"excerpt":{"rendered":"<p>A basic conditional statement works with a single task. What you have to do is to create a task and then add a condition using the \u201cwhen\u201d statement.<\/p>","protected":false},"author":110,"featured_media":18080,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-17881","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-centos"],"_links":{"self":[{"href":"https:\/\/linuxways.net\/de\/wp-json\/wp\/v2\/posts\/17881","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/linuxways.net\/de\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/linuxways.net\/de\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/linuxways.net\/de\/wp-json\/wp\/v2\/users\/110"}],"replies":[{"embeddable":true,"href":"https:\/\/linuxways.net\/de\/wp-json\/wp\/v2\/comments?post=17881"}],"version-history":[{"count":1,"href":"https:\/\/linuxways.net\/de\/wp-json\/wp\/v2\/posts\/17881\/revisions"}],"predecessor-version":[{"id":18162,"href":"https:\/\/linuxways.net\/de\/wp-json\/wp\/v2\/posts\/17881\/revisions\/18162"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/linuxways.net\/de\/wp-json\/wp\/v2\/media\/18080"}],"wp:attachment":[{"href":"https:\/\/linuxways.net\/de\/wp-json\/wp\/v2\/media?parent=17881"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/linuxways.net\/de\/wp-json\/wp\/v2\/categories?post=17881"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/linuxways.net\/de\/wp-json\/wp\/v2\/tags?post=17881"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}