EX294 Red Hat Certified Engineer RHCE – Ansible Plays and Playbooks, Conditional Execution Part 2

  • By
  • January 19, 2023
0 Comment

4. Understanding Jinja2 Template loop Statements loop & with_items

Hello, welcome to this lecture. In this lecture we will discuss about how we can use loops in ancient playbooks. Loops are used to repeat some task multiple times based on some condition. Important example of using loop is to create multiple users with details defined as list items in some dictionary. I will explain this later on in more details. Ansible offers two keywords to create loops loop and with underscore lookup. We will be using loop most of the time during this course. But I will also explain a bit about this keyword. Loop is the best choice for simple loops. So here we have one example of using loops in ansible in display I set target as Mhost one. Also we need to set become to true because we are adding users which is system administration task. In the tasks section we’ll define our task using dash space name. I’m adding some description here.

We’ll add some description here. Then we’ll use user module using named directive. I will specify this expression using item which is lookup variable. So this is new. You must keep in mind you can use item as lookup variables in ancient loops. But you must use item keyword only the state we set to present to create user. Although this is default, we can omit this as well. Here this is important. We are using loop keyword again, level of indentation of this keyword and module must be same to this loop. I am providing two usernames as list items. So what will happen when this playbook will be executed? So this item variable will be replaced with user one during first iteration and user with username user one will be created during second iteration.

This item which is looker variable will be set to user two and user two will be created. We know loop filetrate through all the list items specified. Here we have only two. We’ll see this how it works practically when we’ll move to ansible control node. Here we have one more example where user details are defined in file details YML as list of items within dictionary. So here is sample file details YML defining list variable with name users which contains two list items. One for each user to define details about user. Here each list item is further dictionary. So here we have playbook again. I’m taking m host one as target. We must set become to true. We know why we need this. Here important is you must include VARs underscore files directive to use this file details dot YML in which our variable is defined. In the tasks section we will use user module.

Then here important is named directive. We set namedirective to this expression. In last task we used item as lookup variable. But here we are using item dot username. Why? Because in last task we used simple list items. But here list items are dictionaries. And we know how we can access some value from a dictionary. We must use key key for username is username. Here it can be something else. For example name. In that case you must use item dot name. So idea is you must use key along with item which is looker variable.

Then in the end using loop will set this expression. We know this expression will evaluate to the list of items defined by users list variable. So when this playbook will be executed loop will start with first item which is this dictionary. And it will check item username which is username. So this will be set to user one. User one will be created. Then it will move to second item during second iteration. Again it will evaluate this expression for second item. This will be user two. So user two will be created. In this way, we can create multiple users with details defined in some file in the form of list items under some named list variable. Now let’s move to the ansible control node and understand how will this work practically. Now we are on ansible control node and I am logged in as ansible user. We are inside tasks directory to explain how we can use loop in playbook. I will create one playbook with name loop YML. Here I will use mhostone as target become must be set to true.

Because we are going to create users. Here I will set gather underscore facts to fold. Because we don’t need facts for this task. In the task section we’ll define our task. We know we need to use user module. And here we’ll define our lookup variable using Ginger to expression I’m not using state. Here by default user will be created. So very important is loop using loop keyword I will list two list items defining usernames user one, user two. This is all we need to do. Now I will execute this playbook. We know what will happen. Task adding Users so here we can see item is set to user one during first iteration. Then user two during second iteration. Two users with usernames. User one and user two have been created. Now to verify this we’ll use ansible ad hoc command ensible target is m host one. We’ll use command module. Here I will provide command to display password file. This is all we need to do. We can display this file as normal user as well.

So here we can see our users on the list. I will clear the screen again. I will open this playbook. In a similar way we can delete users. But in that case we must use state set to absent. Also I will change description removing users again we’ll execute this playbook. Now both users will be deleted from Mhost one. Now we’ll move ahead with our next example where we’ll use variable file to create users. First of all we need to create file defining users list variable. We’ll create file with name details dot YML as per example, every ML file should start with three dashes on the toe here we’ll define list variable with name users. Under this list variable, we’ll define two list items for each user. Username user. One department HR, username user. Two department testing. Then, three doors indicating end of YAML document. I will save and quit.

Now I will open same playbook loop YML and I will modify this according to our example here, we must use VARs underscore files directive to specify variable file name, which is details YML. In our case, I will also change description adding users we know here we need to change this lookup variable. We must use key along with lookup variable state must be present or we can omit this directive here instead of providing list items will provide variable defining to list items we know expression to use here this is all we need to do I will save and quit now we’ll execute this playbook. So here we can see two users have been created. The first time item is set to this value which is dictionary.

During second iteration, item is set to this dictionary value which is second item on the list. We used item dot username variable to refer to these usernames. In similar way we can delete users. I will open this file again. I will set state two absent. I will change description according to action removing users will execute this playbook again now. Users have been deleted.

We can verify using ansible ad hoc command. We know what we need to do. We don’t see users on the list. So this is how we can use loops in playbooks using loop keyword here one thing I would like to mention instead of loop, we can also use with underscore items again, I will execute this playbook so this is working fine. But output is green because users have been already deleted. So both will work fine but with underscore item is being deployed indicator. So I would prefer to use loop always this is.

5. Understanding Jinja2 Template statements: loop and when combined

Hello, welcome to this lecture. In this lecture we will understand how we can combine loops with conditionals in playbooks. In some cases, we need to combine when statement with loop. For such cases when statement will be executed for each loop item this is important here. Here we have simple example to display some item variables based on loop and when condition. Here I’m using command module to display variable. I’m using eCommand here then here we are using item as lookup variable. Using loop will define list of items. We can define list of items in this format as well. Then in the end we are using when condition when colon space item is greater than five mind the space in between. So what will happen when we execute this playbook?

During first iteration, item will be set to one. Now we know for each item when condition will be executed then this check will be performed. We know item is node greater than five. In this case, because one is not greater than five, this will be skipped. Same will happen till five when item will be set to six. Because six is greater than five. So it will be displayed using this command same in case of seven and eight. In this way we can combine loop and when together. Here we have one more example. This is more practical example.

We will be using same logic in one of our tasks. This is similar to example we discussed while discussing loops. The only difference is I added one extra one condition. So in this case what will happen? User will be created when user department is HR. When this playbook will be executed it will start first item defined inside this variable. So here it will check if department is HR. So department is HR here so it will create user with name user one. Then it will go to next iteration and here again it will check department. Because we know for every loop item when condition will be executed. Here department is testing so this condition will fail. So user two will not be created. So we will have only user one created on Mhost one. Now let’s move to the ansible control node and see how this practically works. Now we are on ansible control node and I am logged in as ansible user. We are rolled inside tasks directory. Now to explain first example, I will create one playbook with name when and loop dot YML. Here I will use mhostone as target. I will set gather underscore facts to false. Because we don’t need facts for this task. Then the tasks section will define our task displaying items greater than five we know we need to use command module as per example here I will use eCommand. Here we need to specify lookup variable which is item. Now using loop, I will specify list of items. One comma space, two comma space 34567 and eight. Here we’ll specify when condition when item is greater than five. When colon space item. Then again space greater than space five. Then three dots in the end indicating end of YAML file. I will save and close. Now we will execute this playbook. We know what will be the results.

So here we can see items from one to five are skipped. But items from six to eight they are displayed in similar way. You can define to execute some other task on the manage nodes based on same logic. Now I will clear the screen. Now we need to discuss second example. For this I will copy contents of this file to this file. Again I will open this playbook. So here we know what we need to do. I will just change the description adding users. I will remove this. Because this is default behavior. Here I will use loop instead of with underscore items. I will add one extra condition. Here. When item dot department space equal to equal to HR in double quotation marks. Then we have three dots. In the end this is all I will save and quit. Now we’ll execute this playbook.

We know only user one will be created on Mhost one. So here we can see user with username user one is created where department is HR. But this entry is skipped. This is failed. Because this didn’t note pass when test. Because department is testing this is all about this lecture. In next lecture we’ll discuss about magic variables.

6. Introducing & Understanding Magic Variables

Hello welcome to this lecture. In this lecture we discuss about magic variables which contain information about ansible plus remote nodes. We know information about ansible inventory nodes and groups. The directories for playbook Python version rules path is available on ansible control node. We define most of the information on the ansible control node itself and all this information is stored in special variables called magic variables. Apart from this locally available information magic variable host wires osos information about remote nodes. We’ll discuss about this later on. Now here this is important magic variable names are reserved. We are not allowed to use variable with same names. This makes sense. Here is list of commonly used magic variables. There are many magic variables but we’ll discuss only important ones we need to know for this exam inventory underscore hostname the inventory name for the current host being iterated over in the play. So this variable contains host name for each host active in the play.

We can use this variable with when condition we’ll discuss more on this later on. For now we should keep in mind this variable is set to host name assigned to host for all the managed nodes. Then ansible underscore play underscore badge list of active hosts in the current play run failed and unreachable hosts are considered not active. This variable contains list of all the hosts which are active in the play we will be using this variable when we’ll discuss if statement and for statement for conditional playbook execution in next section. Then ansible underscore play underscore hosts same as ansible underscore play underscore badge. So this is now being deprecated in favor of this. So we will prefer to use this variable then group underscore names list of groups current host is part of for example in our case m host one is part of prod group and prod one group.

So this variable will be set to prode and prode one for Mhost one then groups a dictionary with all the groups in inventory and all the hosts in each group. So groups variable contains all the groups and the hosts belonging to groups under dictionary with name groups. I will display information contain all these variables when we move to the system. Now here host VARs so this is different from other variables a dictionary with all the hosts in inventory and variable assigned to them. So here variables represent all the variables including ansible facts. So in case we’ll set ansible underscore facts to true this variable will contain ansible facts for all the remote nodes under this dictionary with name host walls. Again it will be more clear when I will display information contained in this variable. Here we can just go through this. This variable stores information about remote nodes ansible facts in dictionary with same name as hostname. So there are further dictionaries under this variable with same name as that of hostname for each host active in the playbook and all other information about nodes related to ansible. Here we are talking about information which is available locally on ansible control node. This is very useful variable that enables us to access and use variables of other remote nodes on any node. So it means we can access or use variables of some other host on any other managed nodes. We’ll use this special variable to configure hosts file to serve as local DNS in next section. Now next question which comes in mind how we can display magic variables?

We can display magic variables using VAS variable. It stores all the information about ansible operations. So here ansible operations means all the information which is available locally unanimsible control node and ansible facts of remote nodes if gather underscore facts is set to true which is default. So here I’m just telling this was variable is equal to information stored in ensible magic variables plus facts of all the nodes with facts gathered. Now let’s move to the ansible control node and understand what is contained in these variables by displaying them now viral ansible control node and I am logged in as ansible user. We are already inside Tasks directory. Now I will create one playbook to display magic variables with name magic YML. I will set m host one as target gather underscore facts. I will set this to folds for the moment. Now here in the Tasks section we will use debug module to display VARs variable displaying magic variables using MSG directive will specify expression ginger to expression to access or refer variable. This is all we need to do.

I will save and exit. Now we’ll execute this playbook so we have the output. We’ll go over this information from the beginning. Here we can see this is information about m host one which is available locally on this node NCBLE underscore play underscore badge. So here we can see m host one as list item. Why we have only one node here? Because only one node is active in this playbook. In similar way we can see ansible underscore play underscore hosts containing same information. We also have ansible underscore play underscore hosts underscore all containing same info. There are many magic variables but we don’t need to know all of them. You can just go through them. So here important is group underscore names. We know m host one is part of these three groups. Earlier I told you m host one is part of two groups. So I was wrong. M host one is part of these three groups. Because Linux group contains all the nodes. So here we can see information under this name as one list item. Then we have groups under this dictionary we have different list items. This is for all.

All is default group on ansible which contains all the managed nodes by default we don’t need to define this group. We know we defined Linux group which contains all the nodes. Prode contains two nodes prode one contains mhostone prode two contains M host two. So here we can see this is information about Nsie bull. Note only about M host one. Then here we have web servers group containing two managed nodes. Here this is important host VAS. This is dictionary variable contains plenty of information. So here we can see information about M host one under dictionary with name Mhostone. So this is information specific to Mhost one plus common information about anise bull.

So very important is inventory underscore host name which is set to Mhost one. So which is true for Mhost one. Here we can see inventory underscore Dir is set to this path where our playbook is present. Inventory underscore file is set to path of inventory file. So this is information about M host one plus common information about an Siebel. Then as I told you earlier, hostwars contains information about all managed nodes. Because in this case we set gather underscore facts to fold. So we have only locally available information about all managed nodes. So here we have Mhost two. Again we have same information repeated. Of course this can be different for m host two depending upon the groups m host two is part of. Then we have groups variable containing all the groups as list items. Inventory underscore hostname Mhost two. Again we can find similar information here. Same four m host three and same four m host four. You should keep in mind host bars contains all the information which is available locally about all managed nodes which are defined in inventory file. In case gather underscore facts is set to false. But when we set gather underscore fact to true. This variable will contain also information about remote nodes. Now I will explain this. I will clear the screen. Will again open this playbook in editing mode. I will change this to true. Now again we’ll execute this playbook. But I will save the output or redirect the output to some file magic underscore VARs it’s completed. Now we’ll open this file. And we’ll just go through this. Having already said.

Now this VARs variable will contain first ancient facts of this node. I will come to host VIRS later on. Now we are discussing or talking about top level variable VARs here. Because we set gather underscore facts to true. VARs variable will store all the information about remote node. In our case this is M host one. So here you can find all the information. You can just scroll down. Now here I will search for hostwars. So here we have hostwars under hostwars we have dictionary with name Mhost one containing old ansible facts of M host one again under hostwars. So this is duplicated information. So here I would like to tell you apart from ansible facts. This will also contain here common information about ansible operations. We already discussed about this. So same will be stored under host bars as well. So this is again duplicate information. Now here you can move ahead. I will hear search for Mhost two. Here we can see one more dictionary with name m host two.

We’ll move down and here we can see all the information again under host VAR. So here we have only information which is available locally on the ansible control node. Because Mhost two is node target in display same four, M host three, same four m host four. So here we noticed virt variable contains ansible facts gathered from remote node m host one plus local information available on the ansible control node. Then we have hostwars variable which contains again old dansible facts of Mhstone plus local available information about node and common information. It also contains all locally available information about M host two, m host three and m host four for which we are not gathering facts. In fact they are not target of display.

Now I will save and quit again. I will make one change here what happens if I will set target to all? We’ll have plenty of information. I will just display it. We don’t need to discuss this again and again. Here we will find plenty of information and duplicated information under voas variable on the top which we are using to display all this information. So here if you start from the top, I’m not going to show you everything. Here I will just tell you. If you start from the top, first you will see ancible facts of all four managed nodes plus locally available information. Then afterwards you will see hostwars. Hostwars will have further four dictionary with name m host one, m host two, m host three and m host four, where each dictionary contains ansible facts of corresponding node plus locally available information about ansible including information about that node. This enables host bars to use variables of other node on any other managed nodes. This is all about magic variables. In next lecture we’ll execute one task check using magic variable as conditional check.

Comments
* The most recent comment are at the top

Interesting posts

The Growing Demand for IT Certifications in the Fintech Industry

The fintech industry is experiencing an unprecedented boom, driven by the relentless pace of technological innovation and the increasing integration of financial services with digital platforms. As the lines between finance and technology blur, the need for highly skilled professionals who can navigate both worlds is greater than ever. One of the most effective ways… Read More »

CompTIA Security+ vs. CEH: Entry-Level Cybersecurity Certifications Compared

In today’s digital world, cybersecurity is no longer just a technical concern; it’s a critical business priority. With cyber threats evolving rapidly, organizations of all sizes are seeking skilled professionals to protect their digital assets. For those looking to break into the cybersecurity field, earning a certification is a great way to validate your skills… Read More »

The Evolving Role of ITIL: What’s New in ITIL 4 Managing Professional Transition Exam?

If you’ve been in the IT service management (ITSM) world for a while, you’ve probably heard of ITIL – the framework that’s been guiding IT professionals in delivering high-quality services for decades. The Information Technology Infrastructure Library (ITIL) has evolved significantly over the years, and its latest iteration, ITIL 4, marks a substantial shift in… Read More »

SASE and Zero Trust: How New Security Architectures are Shaping Cisco’s CyberOps Certification

As cybersecurity threats become increasingly sophisticated and pervasive, traditional security models are proving inadequate for today’s complex digital environments. To address these challenges, modern security frameworks such as SASE (Secure Access Service Edge) and Zero Trust are revolutionizing how organizations protect their networks and data. Recognizing the shift towards these advanced security architectures, Cisco has… Read More »

CompTIA’s CASP+ (CAS-004) Gets Tougher: What’s New in Advanced Security Practitioner Certification?

The cybersecurity landscape is constantly evolving, and with it, the certifications that validate the expertise of security professionals must adapt to address new challenges and technologies. CompTIA’s CASP+ (CompTIA Advanced Security Practitioner) certification has long been a hallmark of advanced knowledge in cybersecurity, distinguishing those who are capable of designing, implementing, and managing enterprise-level security… Read More »

Azure DevOps Engineer Expert Certification: What’s Changed in the New AZ-400 Exam Blueprint?

The cloud landscape is evolving at a breakneck pace, and with it, the certifications that validate an IT professional’s skills. One such certification is the Microsoft Certified: DevOps Engineer Expert, which is validated through the AZ-400 exam. This exam has undergone significant changes to reflect the latest trends, tools, and methodologies in the DevOps world.… Read More »

img