Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Ansible

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how to use Ansible, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

Configuration

The configuration file for Ansible is saved in / etc/ansible, which makes sense, because / etc/ is where the system program should keep the configuration file. The two files I need to use are ansible.cfg and hosts.

Ansible.cfg

After doing some practical exercises found in documentation and online, I encountered some warnings about abandoning some older Python files. Therefore, I set deprecation_warnings to false in ansible.cfg so that those angry red warning messages do not appear:

Deprecation_warnings = False

These warnings are important, so I'll review them later and figure out what I need to do. But now, they no longer disturb the screen, nor do they confuse me with errors that actually require attention.

Hosts file

Unlike the / etc/hosts file, the hosts file is also known as the manifest inventory file, which lists the hosts on the network. This file allows hosts to be grouped into related collections, such as "servers", "workstations" and any name you need. This file contains help and a large number of examples, so I won't go into detail here. But there's something you need to know.

Hosts can also be listed outside groups, but groups are helpful in identifying hosts that share one or more common characteristics. The group uses the INI format, so the server group looks like this:

[servers] server1server2.

There must be a hostname in this file for Ansible to operate on it. Even though there are some subcommands that allow you to specify a hostname, the command fails unless the hostname is in the hosts file. A host can also be placed in multiple groups. Therefore, in addition to the [servers] group, server1 may also be a member of the [webservers] group and can also be a member of the [ubuntu] group to distinguish it from the Fedora server.

Ansible is very smart. If the all parameter is used as the hostname, Ansible scans the hosts file and performs the defined tasks on all hosts listed by it. Ansible only tries to work once on each host, no matter how many groups it appears in. This also means that there is no need to define all groups because Ansible can determine all hostnames in the file and create its own unique list of hostnames.

Another thing to note is multiple entries for a single host. I use CNAME records in the DNS file to create aliases that point to the A records of some hosts so that I can call a host host1 or H2 or myhost. If you specify multiple hostnames for the same host in the hosts file, Ansible will try to perform its tasks on all of those hostnames, and it will not know that they point to the same host. The good news is that this doesn't affect the overall result; it just takes a little more time because Ansible works on the secondary hostname and it makes sure that everything has been done.

Ansible truth

Most of the materials I've read about Ansible talk about Ansible fact facts, which is data related to remote systems, including operating systems, IP addresses, file systems, and so on. This information can be obtained in other ways, such as lshw, dmidecode, or / proc file systems. However, Ansible generates an JSON file that contains this information. Each time Ansible runs, it generates this factual data. In this data stream, there is a large amount of information in the form of key-value pairs. All of these variables can be used in Ansible scripts, and the best way to understand the large amount of information available is to actually show it:

# ansible-m setup | less

Do you get it? Everything you want to know about mainframe hardware and Linux distributions is here, and they can be used in the script. I haven't reached the point where I need to use these variables, but I'm sure I'll use them in the next few days.

Module

The above ansible command uses the-m option to specify the setup module. Ansible already has a lot of modules built in, so you don't need to use-m for these modules. You can also install many downloaded modules, but the built-in module can do everything I need for my current project.

Script

The script playbook can be placed almost anywhere. Because I need to run as root, I put it under / root/ansible. When I run Ansible, it can find my script as long as this directory is the current working directory (PWD). Ansible also has an option to specify different scripts and locations at run time.

A script can contain notes, but it is rarely mentioned in articles or books I read. But as a system administrator who believes in recording everything, I find it helpful to use annotations. This is not to do the same thing as the task name in the comments, but to determine the purpose of the task group and make sure that I record the reasons for doing these things in some way or in order. When I may forget my original idea, this can help solve debugging problems later.

The script is just a collection of tasks that define the state required by the host. Specify the hostname or manifest group at the beginning of the script and define the host on which Ansible will run the script.

Here is an example of one of my plays:

# This Ansible playbook updates Midnight commander configuration files. #-name: Update midnight commander configuration files hosts: all tasks:-name: ensure midnight commander is the latest version dnf: name: mc state: present -name: create ~ / .config/mc directory for root file: path: / root/.config/mc state: directory mode: 0755 owner: root group: root-name: create ~ / .config/mc directory for dboth file: path: / home/dboth/.config/mc state: directory mode: 0755 owner: dboth group: dboth-name: copy latest personal skin copy: src: / Root/ansible/UpdateMC/files/MidnightCommander/DavidsGoTar.ini dest: / usr/share/mc/skins/DavidsGoTar.ini mode: 0644 owner: root group: root-name: copy latest mc ini file copy: src: / root/ansible/UpdateMC/files/MidnightCommander/ini dest: / root/.config/mc/ini mode: 0644 owner: root group: root-name: copy latest mc panels.ini file copy: Src: / root/ansible/UpdateMC/files/MidnightCommander/panels.ini dest: / root/.config/mc/panels.ini mode: 0644 owner: root group: root

The script starts with its own name and the host it is going to operate on, and in this article, all hosts are in my hosts file. The tasks section lists specific tasks that bring the host to the desired state. This script starts with updating Midnight Commander with DNF (if it's not the latest version). The next task ensures that the required directories are created (if they do not exist), the remaining tasks copy the files to the appropriate location, and these file and copy tasks can also set ownership and file mode for directories and files.

The details of the script are beyond the scope of this article, but I used a little brute force on this issue. There are other ways to determine which users need to update files instead of using a task for each file for each user. My next goal is to simplify the script and use some more advanced technology.

Running the script is easy, just use the ansible-playbook command. The .yml extension stands for YAML, and I've seen several different meanings, but I think it's "another markup language, Yet Another Markup Language," although some people claim that YAML is not.

This command will run the script and update the Midnight Commander file:

# ansible-playbook-f 10 UpdateMC.yml

The-f option specifies that Ansible uses 10 threads to perform the operation. This can greatly speed up the completion of the entire task, especially when working on multiple hosts.

Output

Each task and execution result are listed when the script is run. Ok represents that the machine state of task management has been completed, because the state defined in the task is true, so Ansible does not need to do anything.

Changed indicates that Ansible has performed the specified task. In this case, the machine state defined in the task is not true, so the specified action is performed to make it true. On the color terminal, TASK lines are displayed in color. My terminal color is "amber-on-black", the TASK line is amber, changed is brown, ok is green, and the error is red.

The following output is the script I finally used to configure the new host after installation:

PLAY [Post-installation updates, package installation And configuration] TASK [Gathering Facts] ok: [testvm2] TASK [Ensure we have connectivity] ok: [testvm2] TASK [Install all current updates] changed: [testvm2] TASK [Install a few command line tools] changed: [testvm2] TASK [copy latest personal Midnight Commander skin to / usr/share] changed: [testvm2] TASK [create ~ / .config/mc directory for root] changed: [testvm2] TASK [Copy the most current Midnight Commander configuration files to / root/.config/mc] changed: [testvm2] = > (item=/root/ansible/PostInstallMain/files/MidnightCommander/DavidsGoTar.ini) changed: [testvm2] = > (item=/root/ansible/PostInstallMain/files/MidnightCommander/ini) changed: [testvm2] = > (item=/root/ansible/PostInstallMain/files/MidnightCommander/panels.ini) TASK [create ~ / .config/mc directory in/ etc/skel] changed: [testvm2] cowsay

If you install the cowsay program on your computer, you will find that the name TASK appears in the cow's voice bubble:

_ _

< TASK [Ensure we have connectivity] >

--\ ^ _ ^\ (oo)\ _ (_ _)\)\ /\ | |-w |

If you don't have this interesting program, you can install the Cowsay program using the distribution's package manager. If you have this program but don't want it, you can disable it by setting nocows=1 in the / etc/ansible/ansible.cfg file.

I like this cow, it's interesting, but it takes up part of my screen. So I disabled it when it started to interfere with my use.

Catalogue

As with my Midnight Commander task, I often need to install and maintain various types of files. There are as many "best practices" to create a directory tree for storing plays as system administrators, or at least as many authors as write books and articles about Ansible.

I chose a simple structure that made sense to me:

/ root/ansible └── UpdateMC ├── files │ └── MidnightCommander │ ├── DavidsGoTar.ini │ ├── ini │ └── panels.ini └── UpdateMC.yml

You can use any structure. Please note, however, that other system administrators may need to use the script you set up to work, so the directory should have a certain degree of logic. When I use the RPM and Bash scripts to perform installation tasks, my file repository is a bit fragmented and has absolutely no logical structure. When I create scripts for many administrative tasks, I will introduce a more logical structure to manage my directories.

Run the script multiple times

It is safe to run the script multiple times as needed or expected. Each task is executed only if the host state does not match the state specified in the task. This makes it easy to recover from errors encountered in previous script runs. Because when the script encounters an error, it will stop running.

When testing my first script, I made a lot of mistakes and corrected them. Assuming that my correction is correct, each time the script runs, it skips those tasks that have matched the specified state and performs tasks that do not match the state. When my fix works, the previously failed task completes successfully and executes the task after this task-until another error is encountered.

This makes testing easier. I can add new tasks, and when I run the script, only new tasks are executed because they are the only tasks that do not match the expected state of the test host.

Thank you for reading this article carefully. I hope the article "how to use Ansible" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report