【 note 】 this article translation: www.edureka.co/blog/ansibl… Before you read this article, you should already know that Ansible forms a key part of DevOps certification as a tool for configuration management, deployment, and choreography. The main content of this tutorial includes:

  • Learn how to write Ansible scripts
  • Learn the differences between different Ansible modules
  • Learn to write Ansible Adhoc commands
  • Ansible hands-on practice

Write Ansible scripts

Scripts in Ansible are written in YAML format. It is a human-readable data serialization language. It is usually used for configuration files. It can also be used in many applications where data is stored. For Ansible, almost every YAML file starts with a list. Each item in the list is a list of key/value pairs, often called a “hash” or a “dictionary.” Therefore, we need to know how to write lists and dictionaries in YAML. All members of the list are lines with the same level of indentation beginning with “-” (dashes and Spaces). There may also be more complex data structures, such as dictionary lists or hybrid dictionaries, whose values are lists or mixtures of both. For example, a list of departments related to Edureka:

departments:
- marketing
- sales
- solutions
- content writing
- support
- product
Copy the code

Here is an example of a dictionary:

-USA
-continent: North America
-capital: Washington DC
-population: 319 million
Copy the code

Hosts and Users:

For each item in the script, you can choose which computer in the infrastructure is the target and which remote user will perform the task. To include the host in the Ansible listing, we will use the IP address of the host. Typically, a host is a list of one or more groups or host modes separated by colons. A remote user is simply the name of a user account.

Variables:

Ansible uses predefined variables to give scripts and characters more flexibility. They can be used to iterate over a given set of values, access various information (such as the host name of the system), and replace certain strings in a template with specific values. Ansible has defined a rich set of variables for each system. When Ansible is running on a system, all facts and information about the system are gathered and set as variables. But there is a rule for naming variables. Variable names should be letters, numbers, and underscores. Variables should always start with a letter. For example. Wamp_21, port5 are valid variable names, but 01_port, _server are invalid.

Task:

Tasks allow you to break configuration policies into smaller files. Tasks include extracting from other files. Ansible’s task is pretty much what it means in English. For example, Install <package_name>, update <software_name> and so on.

Handler:

The handler is just like a normal Task in an Ansible script, but only runs if the Task contains the notify directive and also indicates that it has changed something. For example, if a configuration file is changed, a task referencing that configuration file might tell the service to restart the handler. Here is an example of a script that will start the Apache HTTPD server program:

---
- hosts: webservers
vars:
http_port: 80
max_clients: 200
remote_user: root
tasks:
- name: ensure apache is at the latest version
yum: name=httpd state=latest
- name: write the apache config file
template: src=/srv/httpd.j2 dest=/etc/httpd.conf
notify:
- restart apache
- name: ensure apache is running (and enable it at boot)
service: name=httpd state=started enabled=yes
handlers:
- name: restart apache
service: name=httpd state=restarted
Copy the code

I hope this example will associate you with the description of the playbook component I mentioned above. If you are still confused, don’t worry; these questions will be clarified later in this article. It’s all scripted. You’re going to write that script. But Ansible also provides you with a variety of modules that you can use. Modules Modules in Ansible are idempotent. From a RESTful service perspective, to make an operation (or service call) idempotent, a client can make the same call repeatedly while producing the same result. In other words, making multiple identical requests has the same effect as making a single request. There are different types of modules in Ansible:

  • The core module
  • Additional modules

The core module

These are modules maintained by the Ansible core team and will always be available with Ansible. They will also be given higher priority to all requests than those in the “additional” buyback. The source code for these modules is hosted by Ansible in ansible-modules-core on GitHub.

Additional modules

These modules are currently provided with Ansible, but may be provided separately in the future. They are also primarily maintained by the Ansible community. The non-core modules are still fully usable, but the response rate to questions and requests may be slightly lower. Over time, popular “add-on” modules may be upgraded to core modules. The source code for these modules is hosted by Ansible in Ansible-modules-Extras on GitHub. For example, an additional module in the remote management module is the IPMI_power module, which is the power manager for the remote computer. It requires Python 2.6 or higher and Pyghmi to run. You can use this module by writing an adhoc command like the one I wrote below:

ipmi_power : name ="test.domain.com" user="localhost" password="xyz" state="on"
Copy the code

The return value

Ansible modules typically return a data structure that can be registered in variables or seen directly when an Ansible program is output. Each module can record its own unique return value. Some examples of return values are:

  • Changed: : A Boolean value is returned whenever any changes are made to the task.
  • Failed: Returns a Boolean value if the task fails.
  • MSG: Returns a string to give the user a usable message.

Adhoc commands an Adhoc command is a simple one-line command that performs some action. The module that runs with Ansible commands is the adhoc command. Such as:

ansible host -m netscaler -a "nsc_host=nsc.example.com user=apiuser password=apipass"
Copy the code

The adhoc command above uses the netscaler module to disable the server. Ansible provides hundreds of modules in which you can reference and write adhoc commands. Now that all the theoretical explanations have been covered, let’s learn Ansible with a hands-on approach. I am going to write a script to install Nginx on my node/host. Let’s get started 🙂Step 1:Use SSH to connect to the host. To do this, you need to generate a public SSH key. Use the following command:ssh-keygen Command, as you can see in the snapshot abovessh-keygenAn SSH public key is generated.

** Step 2: Your next task is to copy the SSH public key on the host. To do this, use the following command:ssh-copy-id -i root@<IP address of your host> The snapshot above shows copying the SSH public key to the host.

** Step 3: ** List the IP addresses of the hosts/nodes in the list. Use the following command:vi /etc/ansible/hosts This opens a VI editor where you can list the IP address of the host. This is your list now. ** Step 4: ** Let’s ping to make sure the connection is established.The snapshot above confirms that a connection has been established between your control machine and the host. ** Step 5: ** Now let’s write a script to install Nginx on the host. You can write the script in the VI editor. To do this, simply create your play using the following command:vi <name of your file>.ymlThe snapshot below shows my script, written in YAML format for installing Nginx.The tasks of a play are defined in YAML as a dictionary list and executed top-down. If we have multiple hosts, each task will be tried for each host before moving on to the next task. Each task is defined as a dictionary and can have multiple keys, such as “name” or “sudo,” which indicate the name of the task and whether it requires sudo privileges. Set a variable server_port to listen for incoming user requests on TCP port 8080. Here, the first task is to get the necessary packages to install Nginx, and then install them. Internally, Ansible checks for the existence of the directory, creates it if it doesn’t exist, and does nothing else. The next task is to configure Nginx. In Nginx, the context contains configuration details. In this case, a template is a file that can be deployed on a host. However, the template file also contains reference variables extracted from variables defined as part of Ansible scripts or from facts collected from the host. Facts, which contain configuration details, are extracted from the source directory and copied to the target directory. The handler here defines actions that are performed only when a task or state change is notified. In this script, we define the following notification: Restart the Nginx handler, which will restart Nginx once the files and templates are copied to the host. Now, save the file and exit. ** Step 6: ** Now run the script using the following command:ansible-playbook <name of your file>.yml We can see our task in action in the screenshot above; Nginx is being installed. ** Step 7: ** Let’s check if Nginx is installed on my host. Use the following command:ps waux | grep nginx You can see in the screenshot above that different process ids 3555 and 103316 are running, which ensures that Nginx is running on your host. * * congratulations! ** You have successfully deployed Nginx on the host using Ansible scripts.