Introduction to Ansible

Ansible is an open-source automation configuration management tool based on OpenSSH. It can be used to configure systems, deploy software, and orchestrate more advanced IT tasks such as continuous deployment or zero-downtime updates. The main goals of Ansible are simplicity and ease of use, and it also places a strong emphasis on security and reliability. Based on these goals, Ansible is suitable for developers, system administrators, release engineers, IT managers, and everyone in between. Ansible is suitable for managing almost any environment, from small environments with a few instances to enterprise environments with thousands of instances.

Using Ansible does not require installing agents on the managed machines, so there are no issues with upgrading remote daemons or being unable to manage systems due to uninstallation of daemons.

Main Features of Ansible

Administrators can execute commands (tasks) simultaneously on hundreds or thousands of computers using Ansible.For administrators, it is often necessary to perform the following tasks:

  • When maintaining existing complex servers, manual login can easily lead to missed operations or unintended actions.

  • Manually initializing new servers is time-consuming and labor-intensive!

For both of these scenarios, implementing everything through shell scripts would make the scripts overly complex and difficult to maintain. Of course, we can also use similar tools like Puppet and Chef. The characteristic of these two tools is that they require learning a new knowledge stack (Ansible also has a learning cost).

Compared to Puppet and Chef, using Ansible allows for continuity in the work habits and methods previously used with shell scripts, thus lowering the learning cost. Here are some advantages of Ansible:

  • Can execute shell commands line by line.

  • No additional client tools are needed (Linux generally comes with SSH tools).

  • The same configuration is executed only once (repeated execution of the same configuration will not cause issues).

How Ansible Works

Using Ansible does not require installing agents or similar components on the managed client computers. It communicates via standard SSH to retrieve information from remote computers, issue commands, and copy files. This is a way Ansible simplifies server management. Any server with an open SSH port can be configured and managed through Ansible.

Ansible adopts a modular design, making it very easy to extend to various specific use cases. Modules can be written in any language and communicate using standard JSON. Ansible’s configuration files are written in YAML format, as it is very simple to use and resembles mainstream markup languages. In addition to the command-line tool, Ansible can also interact with clients through configuration scripts (Playbooks).

Installing Ansible

This article describes how to install and use Ansible in an Ubuntu 16.04 environment. Since the version provided by the official Ubuntu repository is quite old, we will install it from a third-party repository to get a newer version:

$ sudo apt-add-repository -y ppa:ansible/ansible
$ sudo apt-get update
$ sudo apt-get install -y ansible

After installation, check the version:

$ ansible --version

Introduction to Ansible

2.7.1 is the latest version at the time of writing this article.

Configuring SSH Keys for Client Hosts

For automation, authentication is ultimately done through keys, so user passwords are not written in plain text in scripts. The following command installs the current user’s SSH public key from the host with Ansible to the managed clients 192.168.21.145 and 192.168.21.148:

$ ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
$ ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]

Note: Both managed client hosts are also running Ubuntu 16.04.

Then try to connect to the remote hosts without entering a password using the following commands:

$ ssh [email protected]
$ ssh [email protected]

If you can log in successfully, it means the SSH configuration is OK.

Configuring Users to Execute sudo Without a PasswordIn our automated operations, a significant portion requires root privileges, such as performing updates, installing software, etc. Such operations will fail because the user is prompted to enter a password when executing with sudo, as in the following command:

$ ansible testservers -b -u nick -a "apt update"

Introduction to Ansible

The -b option defaults to elevating the user nick to root privileges, but it requires entering the password for user nick, so the automated command fails. Of course, we can also add the -K option, which will cause Ansible to pause and interact with the user, waiting for the password:

Introduction to Ansible

But this is not the desired outcome; I need the script to complete tasks automatically without interaction!

The solution to this problem is to configure the user toexecute sudo commands without entering a password, so let’s execute the following command on client 192.168.21.148:

$ sudo visudo

Add the following line for user nick:

nick ALL=(ALL) NOPASSWD: ALL

This line configures user nick to not require a password when executing sudo commands. After saving, let’s execute the following command again:

$ ansible testservers -b -u nick -a "apt update"

Introduction to Ansible

This time, we can finally execute commands with root privileges!

Inventory

The inventory is a configuration file for Ansible, where we can specify the managed client machines. The default inventory file for Ansible is /etc/ansible/hosts, but we can also specify other inventory files using the -i option, as in the following example:

$ ansible myservers -i /etc/ansible/myhosts -b -u nick -a "apt update"

In the inventory file, we can specify the host objects that the Ansible command will operate on. For a single host, we can write the hostname or directly the IP address in the inventory:

Introduction to Ansible

If you want to operate on multiple hosts simultaneously, you can define them in a group:

Introduction to Ansible

When executing Ansible commands, simply specify the host name or group name defined in the inventory. For example, if we defined a group named testservers in the /etc/ansible/hosts file that contains two hosts:

Introduction to Ansible

Then execute the df -h command on both hosts using the following command:

$ ansible testservers -u nick -a "df -h"

Introduction to Ansible

From the output, we can see that the df -h command was executed on both target hosts.

Modules

Ansible encapsulates similar operations into modules, allowing for the extension of Ansible through plugins. Each module can accept parameters, and almost all modules accept key-value (key=value) parameters, which are separated by spaces. Some modules do not accept parameters and can be invoked by simply entering the relevant command in the command line. To execute a single command, you can use the command module:

$ ansible testservers -m command -u nick -a "df -h"
$ ansible webservers -m command -a "/sbin/reboot -t now"

Since command is the default module used by Ansible to execute commands, we can omit it in the command line:

$ ansible testservers -u nick -a "df -h"
$ ansible testservers -b -u nick -a "/sbin/reboot -t now"

This way of writing is essentially the same as the previous one.

If you want to execute commands from other modules, you need to explicitly specify the module name using the -m option, for example, to execute a command from the service module:

$ ansible testservers -m service -a "name=httpd state=started"

If you want to copy files from the local machine to the client host, you need to use the copy module:

$ ansible testservers -m copy -u nick -a "src=./app.js dest=./myapp/app.js"

Ansible comes with many useful built-in modules, and you can learn more about them from the module section in its official documentation.

Playbook

If Ansible’s functionality were limited to executing individual commands and scripts, it would be too weak. Ansible’s playbook feature supports writing commands in YAML format in configuration files, allowing all commands in the configuration file to be executed at once (similar to cookbooks in Chef). For example, we can write the previously demonstrated df -h command in a playbook format:

----
hosts: testservers
become: true
become_user: root
tasks:
- name: check disk
  command: df -h

Save the above code in a file named playbook.yml, and of course, you can name this file according to your preference. The hosts indicate which hosts to operate on, become is the -b option we used on the command line, and here we explicitly specify to elevate the current user’s privileges to root to execute the command using become_user: root. The tasks section defines the tasks, where name is a unique task name (if there are multiple tasks with the same name, only the first one will be executed), followed by the command in the task, which is still simply executing df -h. Then execute the following command, noting that this time we are executing the ansible-playbook command and need to specify the name of the prepared playbook file as a parameter:

$ ansible-playbook -u nick playbook.yml

Introduction to Ansible

This simple playbook can work normally, and of course, in a production environment, you may write playbooks that are very complex!

Skipping the First SSH Connection Confirmation Prompt

This is a common issue encountered during automation, so it is worth mentioning. If you did not add the public key to the target machine using the ssh-copy-id command (most environments do not do this), you will need to confirm the security of the connection when executing the Ansible command for the first time:

Introduction to Ansible

This is very unfortunate because our goal is to execute commands automatically without requiring interactive operations.The solution to this problem is to configure Ansible to skip this step of checking. Specifically, find the line host_key_checking = False in the configuration file /etc/ansible/ansible.cfg and uncomment it:

Introduction to Ansible

Then executing the Ansible command will not prompt the user for interactive verification.

Conclusion

Ansible is a powerful automation tool and has carved out a niche in the automation process with its concise usage and developer (system operation and maintenance engineer) friendly features. In this era where DevOps has become mainstream, being proficient in using Ansible will undoubtedly enhance your DevOps practices.

Link: https://www.cnblogs.com/sparkdev/p/9905290.html

(Copyright belongs to the original author, please delete if infringed)

WeChat group

To facilitate better communication on operation and maintenance and related technical issues, a WeChat group has been created. Friends who want to join the group can scan the QR code below to add me as a friend (note: join the group).

Introduction to Ansible

Blog

CSDN Blog: https://blog.csdn.net/qq_25599925

Introduction to Ansible

Juejin Blog: https://juejin.cn/user/4262187909781751

Introduction to Ansible

Knowledge Planet: https://wx.zsxq.com/group/15555885545422

Introduction to Ansible

Long press to recognize the QR code to visit the blog website and see more high-quality original content.

Leave a Comment