Getting started with Ansible 06 - Writing our first Playbook
Estimated read time: 1:20
Learn to use AI like a Pro
Get the latest AI workflows to boost your productivity and business performance, delivered weekly by expert consultants. Enjoy step-by-step guides, weekly Q&A sessions, and full access to our AI workflow archive.
Summary
In this episode of the Ansible series by Learn Linux TV, viewers learn how to write their first Ansible playbook. The episode kicks off with a brief overview of ad-hoc commands used in managing servers, emphasizing the power that lies in using playbooks to automate and maintain consistent server states. The guide walks through creating a playbook file using a text editor, writing tasks to install and remove packages, updating repository indexes, and finally managing and committing these changes with Git. The presenter cleverly balances foundational insights with practical tips, aiming to advance understanding of automation using Ansible playbooks.
Highlights
Learn how to write your first Ansible playbook in YAML format! 🎉
Emphasis on automation and maintaining server states with Ansible playbooks. 🖥️
Discover the importance of proper spacing and alignment in playbook syntax. 📚
Ansible playbooks automate package installation across multiple servers seamlessly. 🚀
Use 'ansible-playbook' to execute the playbook on all servers efficiently. 🌐
Playbooks can ensure packages are up-to-date and can even uninstall packages. 🔄
Git commands like 'git add', 'git commit', and 'git push' help sync playbook changes. 🛠️
Key Takeaways
Ansible playbooks define the desired state of servers and automate tasks. 📜
Playbooks are written in YAML format, capturing sets of tasks to execute. 📝
Writing playbooks ensures repeatable, consistent server management. 🔄
The 'ansible-playbook' command executes the playbook on all targeted hosts. 💻
Ansible gathers facts from each server before executing playbooks to understand the server environment. 🤖
Playbooks can manage package states, ensuring they're up-to-date or removed when needed. 📦
Grouping multiple tasks in playbooks reduces manual steps and streamlines server management automation. ⚙️
Version control with Git helps manage and track playbook changes for better collaboration. 🔧
Overview
In this engaging tutorial, viewers are introduced to writing their very first Ansible playbook. Starting off with a lively explanation of ad-hoc commands, the video quickly dives into the playbooks' powerful ability to automate server state management. The importance of playbooks comes into focus as they drive consistency and automation in server administration, making tasks like package installation a breeze!
The video meticulously walks through creating and editing a playbook file using basic text editors. Viewers learn about the significance of YAML formatting rules, such as the crucial spacing and alignment needed in Ansible syntax. The host demonstrates the process of installing and updating the Apache2 package across servers, highlighting the essential aspects of task management within a playbook.
Further expanding on Ansible's capabilities, the tutorial covers how to revert changes, install additional packages, and why version controlling playbooks using Git is beneficial. Throughout the session, viewers are encouraged to experiment and enjoy the process, as they witness firsthand the simplicity and effectiveness of Ansible in managing complex IT infrastructures.
Chapters
00:00 - 01:30: Introduction to Writing Playbooks In the introduction to writing playbooks, the video begins a new chapter in an Ansible series, emphasizing the shift from ad-hoc commands to the creation of playbooks. Previously demonstrated ad-hoc commands allowed for simplified server administration, such as installing updates on all servers with just one command. However, the video suggests that the true power of Ansible lies in its playbooks, which allow users to define the desired state of their servers more precisely and flexibly.
01:30 - 03:30: Creating the First Playbook File The chapter introduces the concept of Ansible playbook files, which contain 'plays' or commands that Ansible executes to configure servers to a desired state. The chapter emphasizes the importance of understanding playbooks in the context of managing server configurations. It also includes a personal note from the author expressing enthusiasm for Ansible as a favorite technology and encourages viewers to engage with the content by liking the videos and visiting the author's Patreon page.
03:30 - 05:00: Writing the Playbook Content The chapter starts with the author addressing the patrons of their channel, mentioning that patrons typically get early access to tutorial videos. The author expresses excitement about the main topic, Ansible, and specifically about writing their first playbook.
05:00 - 06:30: Understanding YAML Formatting The chapter introduces the concept of creating a playbook file using YAML formatting. It discusses using a text editor to write the playbook, with a specific mention of using nano for the demonstration, though other editors like vim or emacs are acknowledged as options. The focus is on facilitating an understanding of how to begin working with playbook files in YAML.
06:30 - 08:30: Running the Playbook The chapter titled 'Running the Playbook' begins by instructing on the installation of 'underscore apache dot yml'. It explains that '.yml' is the standard extension for playbook files, which are written in YAML format. The chapter reassures that a deep understanding of YAML files is not necessary for writing a playbook. It then instructs to begin the playbook by typing three dashes followed by entering. This sets the foundation for proceeding with playbook setup and execution steps.
08:30 - 11:30: Explaining Output and Re-Running Playbook In this chapter, the focus is on explaining the output and re-running a playbook. It begins with instructions to type a dash and 'hosts: all' to indicate the start of a block or statement in a playbook. This notation is likened to the Ansible command 'ansible all', indicating the intention to run the playbook on all hosts. Proper alignment is emphasized as critical.
11:30 - 13:00: Editing and Expanding the Playbook This chapter focuses on editing and expanding a playbook. It details the importance of configuring the environment using 'ansible.cfg' to streamline the process and eliminate repetitive tasks. The speaker gives an example of setting up the 'become: true' directive and demonstrates how to structure a play with proper indentation, utilizing spaces to correctly format the YAML configuration.
13:00 - 16:00: Adding More Plays and Packages In the chapter titled 'Adding More Plays and Packages', the focus is on installing the Apache 2 package. The instructor emphasizes the importance of choosing a descriptive title for the task to ensure that anyone reading the output immediately understands the action being performed. The use of the 'apt' module for this installation is highlighted, and the correct formatting and alignment for scripting are demonstrated.
16:00 - 18:30: Removing and Reinstalling Apache The chapter titled 'Removing and Reinstalling Apache' covers the creation and understanding of a playbook in the YAML format for managing the Apache2 service using Ansible. It emphasizes that while a deep understanding of YAML can be beneficial, only a basic knowledge is necessary to use Ansible effectively. The importance of correct spacing in YAML files is highlighted, although detailed exploration of YAML's complexities is beyond the scope of this chapter.
18:30 - 20:00: Synchronizing with Git This chapter discusses the process of synchronizing with Git, focusing on the necessity of proper alignment and indentation in the configuration files. It begins by explaining the targeting of all hosts, indicated by a hyphen, and emphasizes the importance of maintaining alignment, using spaces for precise formatting. The correct alignment is crucial to ensure that commands execute properly without failure. Additionally, the chapter touches on aspects such as 'become' and 'sudo' as part of configuration setups.
20:00 - 21:00: Conclusion and Next Steps The chapter titled 'Conclusion and Next Steps' addresses a series of concluding actions. It begins with a structured list of tasks, emphasizing proper alignment and naming conventions for clarity and descriptiveness. The section specifies that certain characters are not allowed in task names, though details are not expanded upon. The narrative focuses on including understandable text for immediate purposes and clarifies the purpose of the referenced play and the module 'apt' to be executed. Alignment techniques and spacing are mentioned as well.
Getting started with Ansible 06 - Writing our first Playbook Transcription
00:00 - 00:30 hello and welcome back to my ansible series i'm really excited because in this video we are actually going to write our first playbook in the previous video i showed you an example of some ad-hoc commands that actually simplify our administration of our servers for example with one command we were able to install the updates on all of our servers but the real strength of ansible comes from its playbooks when we write a playbook we can define the state that we want our servers to be
00:30 - 01:00 in and the plays or the commands that ansible will carry out to bring our servers to that state and that's what we're going to explore in this video so i hope you are loving this series so far i love ansible it's my favorite technology or at least one of them and if you also are enjoying this series please click that like button because that lets youtube know that you want to see more content just like this and also be sure to check out my patreon page
01:00 - 01:30 because if you are a patron of my channel then chances are you have already seen this video because when it comes to tutorials my patrons get first dibs on those i upload them there first but anyway let's go ahead and dive back into ansible because i'm really excited to write our first playbook [Music]
01:30 - 02:00 so now let's go ahead and well create our first playbook file let's dive right into it so we will use whatever our editor of choice is mine is vim but you know nano is easy for everybody now regardless of whatever your favorite text editor is i won't judge you even if it's emacs but i'll go ahead and use nano for the purposes of this video and then we can call our playbook
02:00 - 02:30 install underscore apache dot yml and the dot yml extension is basically the standard extension for playbook files they are in the yaml format i'll show you what that means in a moment but don't worry i'm not going to go too into detail on that because you don't need to understand everything about yaml files to write a playbook so i'll press enter here and then we can go ahead and get started so we're going to begin the playbook by typing three dashes and then enter
02:30 - 03:00 and then i'll press enter again to go to another new line and then i'll type dash and then hosts colon all so basically the beginning of a statement or a block is going to begin with the hyphen and this is kind of similar to the commands that we've been running where we say ansible all here it's essentially the same thing host colon space all we want to run this on everybody i'll press enter and alignment is very
03:00 - 03:30 very important here so i will press space twice and then i will type become colon true if you recall we've been using the dash dash become option or at least we were but we added it to ansible.cfg so we don't always have to do that two spaces and then tasks and then i will do another blank line here then two spaces and we're going to write our first place so we're going to give it a name so dash space name colon
03:30 - 04:00 and the name i'm going to give it it's basically a title that's going to show in the output so we want to be kind of descriptive here so i'm going to just type exactly what this does which is install the apache 2 package so that's a decent name i think everybody who looks at that will know exactly what this is doing so i'm going to line my cursor up underneath the end here apt is the module that i want to use so i just pressed enter now i'm spaced
04:00 - 04:30 over to underneath the t name colon apache2 and that's basically our entire first playbook right here now again this is in the yaml format but you don't have to know everything about the yaml format you only need to know what's required for using ansible which honestly is not all that much but you can unlock more power with ansible if you really dive deep into yaml but we're not going to get too deep into that here now again spacing is very important so if i go
04:30 - 05:00 back to the top here we have this line here which basically is targeting all hosts it's the very beginning so we have a hyphen here now here we have two spaces because we want all of this to be aligned notice that everything is right underneath the other if i had it like this that's not going to work that's going to fail it needs to be lined up hosts all i've already explained become true is sudo as you know
05:00 - 05:30 and then we have a list of tasks now the first task is lined up to the t right here we have the hyphen here they're lined up we give it a name we want something descriptive so it doesn't matter what you put here there are some characters that you can't put here i'm not going to get into that i just wanted to include some text that's good enough for now and this line here just explains again what this play actually does and the module that we want to run is apt that's lined up here to the end down here we've gone two spaces to the
05:30 - 06:00 right name colon apache two now if we take a quick look at the documentation for app this is the documentation page from the ansible wiki right here we can see that if we go down here to name which is what i used it basically allows us to type the name of a package we want to install and again if you want to go even further you can check out these other options here but that's essentially all we're doing we're just installing the apache 2 package
06:00 - 06:30 so control o and then enter and then ctrl x to exit out now to run our actual yaml file our playbook against our hosts we can use the ansible hyphen playbook command which is not something that we explicitly installed this actually came with ansible we've only ever installed a package named ansible to get ansible but there are several binary several commands that come with ansible when you install it and the ansible hyphen playbook command is one of those
06:30 - 07:00 we're going to do dash dash ask become pass and then we're going to type the name of the playbook we just created which was install apache.yml as you see here i'll press enter asking us our become password which i'll type in let's see what happens now we have quite a bit of output here don't we so obviously the playbook that we wrote it took more time to write that playbook then it
07:00 - 07:30 would take to just do sudo apt install apache 2. but that's not the point we could definitely make that more advanced and we will but we have successfully ran a playbook against all of our servers so it asked us for the become password which we entered in and we are targeting all hosts with this playbook now the first thing it's doing here is gathering facts we did not tell it to gather facts we didn't say hey ansible please gather facts i'm sure
07:30 - 08:00 you remember earlier in the series we ran the gather facts module against our host it was one of the ad hoc commands that we ran to pull information from those servers ansible is actually going to do that every time before it runs any playbooks it wants some information about those servers you know what operating system are you is what it might ask the server and when the server responds linux it's going to ask which distribution are you which release version are you and so on
08:00 - 08:30 and so on it gathers all of those facts and it stores it for each of the three servers or however many servers you have and then it actually executes our play notice here install apache 2 package that is the same title that we gave the actual instruction inside the playbook this is what we wrote now if we said pizza is awesome it would actually show that here so it doesn't really matter what you put here for the name we just wrote install apache2 package just to be descriptive
08:30 - 09:00 to show what it's doing now here it ran it against each of these three servers and it said that it changed something so here it says okay equals two changed equals one unreachable is zero failed is zero skipped a zero rescued to zero and ignored a zero what does this actually mean so changed equals one means that it did change something now it's only going to make changes that are necessary so if we had like 10 different plays here
09:00 - 09:30 and all of those 10 requirements were made it would say changed equals zero if the host was down if the server was offline or there was some kind of network issue then it would say unreachable equals one if it wasn't able to reach this server but it says unreachable equals zero because well there's no problem skipped is when you have a task that you are basically saying only run this task if this requirement is true and if that requirement is not met basically it'll skip it but that's not
09:30 - 10:00 the case here we haven't even gotten into that yet rescued equals zero that's probably something we won't get into in this series but that's basically a way to make a task run as a rescue if a previous task fails ignored well we're able to ignore things but we're not so that's basically what the output means if i was to go ahead and run this again i'm not going to change anything i'm just going to run the command as it is i'll type the password yet again for the millionth time
10:00 - 10:30 now here the output is a little bit different changed is zero so when we ran this the first time it already installed the apache two package it's not going to reinstall it it's going to check if that package is installed if it's not it's going to go ahead and install it and then this will be changed equals one but if it is already installed there's nothing to do here so it'll just be zero for the number of changes
10:30 - 11:00 so now what's really interesting here is that we can actually go to a web browser here open a new tab and as long as the ip address for your server is routable to your network you should be able to access the default web page so let's see if we can do that 172.16.250.132 that is my ubuntu server number one i'll press enter and we have the default ubuntu webpage right here so using ansible we were able to install
11:00 - 11:30 apache and well here it is it's working just fine that is awesome so you can go ahead and test that for yourself and make sure that you're able to get to the default web page for your server so let's go ahead and edit the playbook and i'm going to change this here to just a random name here i'm going to call the package chocobo which is a famous bird character from final fantasy
11:30 - 12:00 basically i'm just typing the name of a package that doesn't actually exist there's no package with that name i'll save the file exit out here and let's go ahead and run it and it failed now i did keep the name of the task as install apache 2 package even though i'm installing a package named chocobo or at least i would be
12:00 - 12:30 if there was such a name of a package there is no such package so this failed and we see in red here failed equals one because i tried to do something that failed no package matching chocobo is available i knew that i did that on purpose so let's go ahead and fix it and then i will go ahead right here and change the name of the package back to what it should be apache 2 and save the file so we're not going to run into that problem again now let's go ahead and add another play
12:30 - 13:00 to this now this worked just fine but what if our package index was stale then this might actually fail so before our install apache 2 package play right here i'm going to press enter twice and i'm going to add a new play i want to keep them lined up so i will press space twice hyphen and then name update repository index and i want to line that up right there so again i'm going to use the apt module
13:00 - 13:30 and then the module i will use update cache yes so i will save the file exit out and it's not going to do anything different but i'll go ahead and run it again so it changed the repository index on
13:30 - 14:00 each of the three servers so it's going to say changed equals 1. even though the install apache 2 package display right here which makes sure that that package is installed that requirement was already met so it didn't actually register a change for those but it did actually register a change for the fact that we have updated the repository index which was actually a good thing to do so we can make sure that that's not stale when we go to install packages
14:00 - 14:30 so let's go ahead and actually take another look at that playbook file here and add another change now admittedly this playbook is somewhat of a mess and i'm going to make it a bit messier here but we'll get into cleanup and reorganization in a future video but let's go ahead and install another package so i will call this one let's see add php support for apache again we're going to use apt
14:30 - 15:00 then the name is going to be lib apache 2 mod php just like that let's save it again that's ctrl o to save and then ctrl x to exit out and let's run the playbook again now we are actually installing two packages with one playbook
15:00 - 15:30 so now it's telling us that there were two changes for each of the servers so we have the change right here on each where we update the repository index and then another change when we go ahead and add php support for apache which we have done by installing that lib apache 2 mod php package and that was done on each of the servers
15:30 - 16:00 now let's go ahead and expand on this playbook just a little bit more and what i'm going to do is go here to the task where i'm installing the apache 2 package and i'm going to add another option here state latest and then i'm going to do the same thing here this is going to make sure that each time i run this playbook that the packages are the latest versions available so again i'll save it and exit out
16:00 - 16:30 and let's run it and it's not actually going to do anything different for the php support or even the apache 2 package those are already the most recent versions when i ran this playbook but now this playbook can be run over and over again to simply make sure that the packages are of the latest versions
16:30 - 17:00 each time we run it and that's awesome now what we can also do is use the app module to remove packages as well i'm going to copy the install apache yaml file to remove apache.yml let's go ahead and open that up in our tried and true editor and what i'm going to do is change the state to absent
17:00 - 17:30 on each of these packages here all right so i think you already know what's going to happen but what i'm going to do is run that playbook remove apache so we basically have a playbook that is the polar opposite of the original that we can use to reverse the changes so press enter
17:30 - 18:00 and there we go so if i go back to the browser here we have the default apache website that comes with apache when you install it i'll refresh and it's gone why is it gone well because we were able to remove the package we ran the playbook to remove apache and the only thing different is we
18:00 - 18:30 changed state latest to state absent so you have some control over the state of the packages as well then i can go ahead and just run the install playbook again to put apache back on the servers
18:30 - 19:00 and there we go so back here on the browser we have the default web page again now when it comes to our playbooks they are incredibly inefficient don't worry we'll get to best practices later in the series so let's go ahead and synchronize with git we'll do git status and we have these two files the ones that we created in this video so i'm going to do this git add and then
19:00 - 19:30 dot and what that's going to do is add pretty much everything in the current working directory to the commit that we are going to be sending up to the server so what we can do right now is get commit dash m added install remove playbooks for apache then enter and we can see if we run git status again that we have one commit that's
19:30 - 20:00 pending let's go ahead and send that up to github git push origin master there we go and then back here at the browser we can see if i refresh the page here we have the install apache and remove apache playbooks there on our github account inside the repository so how does it feel you have created your first playbooks in this video and hopefully now you are beginning to see
20:00 - 20:30 just what ansible can do for us when it comes to automation now obviously it gets much more advanced than this and in future videos in this series we are going to explore this even deeper so i hope that was helpful for you guys make sure that you subscribe to my youtube channel to ensure that you get the notification as soon as the next episode in this series is available and when it is i'll see you