How to Build (And Actually Understand) a Solid Ansible Playbook

choubertsprojects

VPN offers!

1. NordVPN

2. Surfshark

3. ExpressVPN

An Ansible playbook is a series of tasks that need to be completed in order to run your playbook. This article will walk you through how to build and understand the structure of an Ansible playbook, which includes many examples so you can see what’s happening as we go along.
The Future Of Blockchain-Powered Games?
Experts say gaming will be the first real use case for blockchain, revamping the industry and making games more immersive than ever. How gaming navigates the remaining hurdles will become a case study for other industries considering mass blockchain adoption.

Ansible is a configuration management tool that allows you to manage your servers and applications. This article will guide you through the process of building an ansible playbook, as well as explaining what makes up a solid playbook. Read more in detail here: ansible playbook pdf.

How to Build (And Actually Understand) a Solid Ansible Playbook

Are you new to Ansible and having trouble creating your first playbook? An Ansible playbook example would be a great place to start to understand how an Ansible playbook works. Fortunately, this guide has you covered.

You’ll learn how to develop and create Ansible playbooks for service deployment in this lesson, as well as the components that make up an Ansible playbook.

Continue reading and start constructing right now!

Prerequisites

This tutorial includes detailed instructions. If you want to join in, make sure you have the following items:

Ansible Installation Guide (Ubuntu, RHEL, CentOS, macOS)

  • To test the Tomcat installation, you’ll need a remote Linux PC. The remote node in this tutorial is Ubuntu 20.04.3 LTS.
  • One or more hosts set to perform Ansible commands and playbooks, as well as an inventory file. Myserver is the name of the remote Linux machine, and web is the inventory group for this lesson.
  • Both your Ansible controller host and the remote node system must have Python v3.6 or later installed – this article utilizes Python v3.9 on an Ubuntu machine.

How Do You Install Python 3.6? Related:

Creating a Simple Ansible Playbook

Ansible playbooks allow you to deploy complicated apps, manage reusable configurations, deploy to numerous machines, and repeat multiple processes. Ansible playbooks are authored in YAML and include several tasks that are run in sequence.

You’ll define an Ansible playbook to install Apache on your remote node to better understand how it works.

1. Open your preferred SSH client and connect to the Ansible Controller server.

2. Using your favourite text editor, create a file titled apache.yml in your home directory. Fill in the following information (playbook) in the file to start and activate the Apache service.

With the remote user, the code below deploys the Ansible job to install Apache to the target server IP (web) (ubuntu).

Installing Apache service hosts: my app servers # Playbook apache.yml —- – name: # Define all hosts remote user: ubuntu # Task definition for Ansible: Install the most recent Apache apt: state: latest name: httpd

3. Verify the playbook (apache.yml) using the ansible-playbook tool to detect syntax errors (—syntax-check) and other issues.

Always execute your Ansible playbook after doing this syntax check. You can prevent accidently messing up your project by doing so.

—syntax-check apache.yml ansible-playbook

There are no problems reported, indicating that the Ansible playbook (apache.yml) is free of syntax mistakes and may be securely performed.

Verifying Ansible Playbook Syntax Errors (apache.yml)Verifying Ansible Playbook Syntax Errors (apache.yml)

4. Finally, use the following command to run the Ansible playbook (apache.yml).

apache.yml ansible-playbook

If you observe an OK status, it means that the Ansible job does not need to do anything. The job is completed successfully on the remote node if you get the altered status.

Putting the Ansible Playbook into ActionPutting the Ansible Playbook into Action

Keeping Ansible Playbook from halting task execution

You already know how to create a simple Ansible playbook. However, Ansible may get a non-zero return code from a command when running the playbook. Or a module failure that prevents the playbook from continuing to run.

Consider utilizing the Ansible playbook’s error handling functionality to avoid errors from preventing other tasks from running. Error handling enables you to continue working even if a job fails by employing rescue and always operates as well as the desired outcome.

Copy/paste the code below into a new playbook called main.yml. The Ansible Playbook below conducts several operations while using the built-in debug module in Ansible to handle unsuccessful tasks (ansible.builtin.debug)

—- – name: web server updates # On your local workstation, run the Ansible Playbook. remote user: ubuntu hosts: localhost tasks: – name: Ansible block for doing error handling: – name: A message is printed by the Ansible job msg: ‘I run properly’ ansible.builtin.debug: – name: Ansible job will fail /bin/false ansible.builtin.command: – name: Ansible task will not continue owing to the failure of the preceding task ansible.builtin.debug: msg: ‘I never execute,’ rescue: – task name: Ansible msg: ‘I noticed an issue, can do something here to repair it always: ansible.builtin.debug: msg: – name: This Ansible task is always run ansible.builtin.debug: msg: ‘This always executes’

To run the playbook, use the following command (main.yml)

main.yml for ansible-playbook

Rescue functions in the Ansible block enabled Ansible tasks to continue and execute, whereas other jobs were terminated when they failed:

  • The first job completed successfully, printing the message “I execute regularly.”
  • The second job fails because the command supplied (ansible.builtin.cmd: /bin/false) is wrong.
  • Because the second task failed, the third task will not be completed.
  • Because they include rescue and always functions, the fourth and fifth jobs always run.

The main.yml Playbook is being executed.The main.yml Playbook is being executed.

Ansible Role Tomcat Definition for an Ansible Playbook

You now have a rudimentary grasp of how to create Ansible playbooks to do simple tasks. Consider utilizing Ansible roles if you need to execute a lot of deployment work or many operations that may be repeated many times.

Because the material in roles may be reused and shared, using Ansible roles is a smart idea. Create an Ansible-playbook to install Apache Tomcat service on your remote node to observe how Ansible roles function in action. However, you must first build an Ansible role folder.

1. Open the terminal on your Ansible controller host, then perform the following commands to create and switch to the directory /ansible playbook demo. This directory will include the playbook as well as all of the necessary configuration files for Apache Tomcat deployment.

/ansible playbook demo/mkdir ansible playbook demo/cd

2. Then, within the /ansible playbook demo directory, execute the command below to create a new directory called roles and switch to it.

The Tomcat role you need to deploy is located in the /ansible playbook demo/roles directory.

Ansible searches for roles in two places by default: a directory named roles/ inside the directory where the playbook is located, and /etc/Ansible/roles. Declare the pathways using the – role: argument in the playbook if you want to store roles at separate paths.

mkdir -p roles && cd roles

3. Finally, use the command below to build the tomcat role’s needed directories.

The p option instructs the mkdir command to construct the tomcat parent directory as well as the directories tasks, handlers, defaults, vars, and templates. Each of these directories is shared by all Ansible roles, and will ultimately include a main.yml file that will be used to deploy the Tomcat role.

Within the roles directory, you may name the role anything you like.

# task directory – includes a set of tasks that a role must complete # handlers directory – is similar to conventional Ansible tasks. # However, they will only execute if the job has a “notify” directive. # files directory – transfer any files from the Ansible controller host to other nodes # library directory – store any plugins or modules such as Python The vars directory holds all of the variables you’ll need in the main. yml file # defaults directory – contains the variables needed for the role to run. The dynamic values are specified as variables in the Ansible mkdir -p tomcat/tasks, handlers, defaults, vars, templates file.

4. Finally, run the tree command to ensure that the roles directory has all essential folders.

At this point, you should have the following file structure.

Verifying the contents of the roles folder's files and foldersVerifying the contents of the roles folder’s files and folders

Putting Together an Ansible Playbook

You’ll add a main.yml file to each subfolder of the /ansible playbook demo/roles/tomcat/ directory now that you’ve built up the Ansible role tomcat folder.

The settings are automatically selected from the proper file (main.yml) in the appropriate folder by the Ansible playbook, which then installs Apache Tomcat on the remote node.

1. In the tasks directory, open your preferred text editor and create a file titled main.yml.

Fill in the following information (playbook) in the file to start and activate the Tomcat service.

—- # Java installation (Open Jdk) – name: apt: name=openjdk-8-jdk Install Java 1.8 # Adding the group “tomcat” – name: add group “tomcat” # Along with Ansible, the user tomcat is added. When the name criteria is met, the user “tomcat” is added. home=/usr/share/tomcat group=tomcat createhome=no when ansible os family == “Debian” become: True become method: sudo # Using Ansible variables to get the Tomcat package – get url: url: “tomcat download url” dest: “tomcat download location” – name: Download Tomcat Create a tomcat directory file with the following name: /usr/share/tomcat/path owner: tomcat group: tomcat state: tomcat # Unarchiving the tomcat archive – name: Extract tomcat archive owner: tomcat group: tomcat remote src: yes extra opts: “—strip-components=1” src: “tomcat download location” dest: /usr/share/tomcat /usr/share/tomcat/bin is created. # Copying the Tomcat.service.j2 Ansible Jinja template to the target node – template name: Copy Tomcat Service File: templates/tomcat.service.j2 (source) tomcat.service in /etc/systemd/system # On the target node, start and enable the Tomcat service. daemon reload: yes – name: Start and enable Tomcat service enabled: yes name: tomcat state: started when systemd == ansible service mgr

How to Work with When and Other Conditionals in Ansible

2. Next, under the vars directory, create a new file called main.yml and paste the content below into it.

The variables tomcat download url and tomcat download location are defined in the code below. While executing the playbook, the Ansible role selects values from the main.yml file in the tasks directory for these variables.

http://dlcdn.apache.org/tomcat/tomcat-10/v10.0.14/bin/apache-tomcat-10.0.14.tar.gz tomcat download url /tmp/apache-tomcat-10.0.14.tar.gz tomcat download location

3. Finally, in the templates directory, create a template file called tomcat.service.j2 and fill it with the code below.

The tomcat.service.j2 template that Ansible uses when you run the playbook is shown below. The data from this template is subsequently copied to the target node in the /etc/systemd/system/tomcat.service directory by Ansible.

# The unit specifies the name of the service to be deployed, which is Tomcat in this case. Tomcat [Unit] Description After=network.target # The Service section enables you to specify the service type. # Forking enables you to operate the Tomcat service in the background by starting it as a system start-up #. [Service] Type=forking User=tomcat Group=tomcat # The environment variable # JAVA HOME, for example, includes a set of environment variables that Tomcat needs to execute. Environment=JAVA HOME=/usr/lib/jvm/java-8-openjdk-amd64 Environment=CATALINA HOME=/usr/share/tomcat Environment=CATALINA BASE=/usr/share/tomcat Environment=CATALINA PID=/usr/share/tomcat/temp/tomcat.pid ExecStart=/usr/share/tomcat/bin/startup.sh ExecStop=/usr/share/tomcat/bin/shutdown.sh # The Install section determines whether or not the given Unit is activated. # At startup, WantedBY runs Tomcat automatically. [Install] WantedBy=multi-user.target

Using the Tomcat Ansible Role to deploy an Ansible Playbook

Within the Tomcat Ansible role, you’ve managed to set up and configure the Ansible role file structure and files/folders. However, the role you established will accomplish nothing until you execute the playbook, so you’ll use the Ansible playbook to swiftly deploy the Ansible role.

Copy/paste the code below into a YML file with a name you like. The file is titled /ansible playbook demo/tomcat-setup.yml in this example.

The code below deploys the Ansible role (tomcat) that you configured in the “Ansible Role Tomcat Definition for an Ansible Playbook” section to the destination server address (web). Notice you deploy the Ansible role with the remote user (ubuntu) with admin access.

Roles may be used in three ways: on the play level with the roles option, on the tasks level with the include role and import role choices, and on the import role option.

– Tomcat deployment’s name remote user: ubuntu roles: playbook hosts: web – tomcat

Validating the Ansible playbook using the —check option with the ansible-playbook command, as demonstrated below, is a recommended practice before running it. The —check parameter instructs Ansible to simulate the playbook without actually executing it. –check ansible-playbook tomcat-setup.yml

To run the playbook, use the following command.

ansible-playbook tomcat-setup.yml

Using the Tomcat Ansible Role to Deploy the Ansible PlaybookUsing the Tomcat Ansible Role to Deploy the Ansible Playbook

Using a Remote Machine to Test the Tomcat Service

Your Ansible playbook was run, and Apache Tomcat was installed on the remote system. The next step is to verify that the Tomcat service is up and functioning. You’ll check the status of the Tomcat service and see whether you can reach the Apache Tomcat landing page.

To check the Tomcat service, open the terminal on the remote node and run the command below. The tomcat command displays the Tomcat service’s status.

The status reveals that the Tomcat service is up and functioning.

Verifying the remote machine's Tomcat serviceVerifying the remote machine’s Tomcat service

To view Apache Tomcat’s landing page, perform the curl command below (localhost:8080).

You’ve reached Apache Tomcat’s landing page, as shown by the output of an HTML code below. This result verifies that your Ansible script installed Apache Tomcat successfully.

Verifying the remote machine's Tomcat service landing pageVerifying the remote machine’s Tomcat service landing page

Conclusion

You’ve learned how to write a rock-solid Ansible playbook utilizing different Ansible capabilities like Ansible roles, variables, and so on in this course. You learnt how deploy Apache Tomcat using the same Ansible playbook you prepared.

Which application do you aim to install using Ansible playbooks now that you’ve mastered the Ansible playbook? Or maybe you’d want to learn how to use Ansible variables in roles and playbooks?

Related Tag

  • ansible playbook tutorial