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

Ansible Automated Operation and maintenance tool

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

Share

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

With the mobile Internet, Internet of things, Internet +, big data, cloud computing and other large-scale applications, as well as the Internet in people's daily life, the Internet is also gradually popularizing thousands of households. The development of the Internet affects not only our lives, but also the whole economy. While experiencing the convenience brought by the Internet, people are no longer satisfied with "available", but "simple and convenient to use" is called the standard of people's life. Under the trend of national policies, needs and interests, the speed of the development of the Internet can be imagined. As we all know, behind the intelligence means complexity, means that the workload of operation and maintenance engineers increases, this phenomenon is reflected incisively and vividly in the development of the Internet!

With the rapid development of the Internet, the job of operation and maintenance has gradually moved from obscurity to the public view, which is known by more and more people. In the early Internet companies, there were ten or dozens of servers on a very large scale, and the operation and maintenance engineers could barely operate a dozen or even twenty machines at the same time. But how to ensure that everyone's operation is exactly the same? And how to ensure that all operations are accurate? It is not uncommon for today's Internet companies, such as Taobao, JD.com, Tencent and so on, to own dozens or even hundreds of machines, and it is no longer realistic to maintain them one by one in the traditional way. In this context, operation and maintenance automation arises at the historic moment!

Operation and maintenance of automatic chemical industry has a lot, but now the most widely used is-Ansible.

The main contents of this blog post are:

Understand the working mechanism of Ansible; master the common modules of Ansible; write Playbook files to realize automatic operation and maintenance

The theoretical part of the beginners always do not want to know, most of them are "I know how to configure, on the line!" , "check the information on the Internet when you need it". However, to really master a tool, the most important thing is to understand how it works and the relevant configuration! If you do not understand how it works, if there is an abnormal situation in the service one day, those who do not understand its working principle will be "black with two eyes" and do not know where to start. So, you know how important it is to understand and master the working principle behind the tool!

I. Overview of Ansible

Ansible is a more and more popular open source operation and maintenance automation tool in recent years, which can realize operation and maintenance automation through Ansible, improve the work efficiency of operation and maintenance engineers and reduce human errors. Ansible implements a variety of management tasks through a wealth of modules integrated by itself, and it has more than thousands of modules. More importantly, its operation is very simple, even beginners are relatively easy to use, but it does provide very rich functions, in the field of operation and maintenance, it can do almost anything.

Since its release in 2012, Ansible has quickly become popular all over the world. Its characteristics are as follows:

Ansible automatic operation and maintenance tools are open source; Ansible operation is very simple, even beginners are very easy to use; Ansible is based on Python development, operation and maintenance engineers to its secondary development is relatively easy; Ansible rich built-in modules, basically meet all needs; management mode is very simple, a command can affect thousands of machines; clientless mode, the underlying communication through SSH After the release of Ansible, it has been accepted and put into use by AWS, Google Cloud Platform, Microsoft Azure, Cisco, HP, VMware, Twitter and other big companies.

Ansible does not have a client, so there is no need to add agents on the managed host, and the underlying communication is done through SSH, while SSH is installed and enabled by default in the distribution of Linux. In the Windows system, depending on the PowerShell,Ansible, the management side must be the Linux system, and the management node sends instructions to the managed host through the application module, and automatically deletes the temporary files after execution.

According to the different orange colors used by Ansible in Huo City, it can be divided into the following three parts:

User: how to use Ansible to automate operation and maintenance? Ansible toolset: what functions can be achieved by Ansible? Target: which hosts can be affected by Ansible? 1. User

As shown in the figure, Ansible users can interact with Ansible in a variety of ways, which are shown in four ways:

CMDB:CMDB stores and manages the configuration information in the enterprise IT architecture, which is the core tool for building ITIL projects. Operators can combine CMDB and Ansible and directly issue instructions through CMDB to call the Ansible toolset to achieve the desired goals of the operator. PUBLIC/PRIVATE mode: in addition to rich built-in modules, Ansible also provides rich API language interfaces, such as PHP, Python, PERL and other popular languages, which run by API call based on PUBLIC/PRIVATE,Ansible; Ad-Hoc command set: Users invokes Ansible tool set directly through Ad-Hoc command set to complete tasks; Playbooks:Users prepares Ansible Playbooks and executes tasks sequentially by executing pre-scheduled task sets in Playbooks 2.Ansible tool set

The Ansible toolset contains Inventory, Modules, Plugins, and API. Where:

Inventory: used to manage the list of devices, which can be implemented through grouping, and the call to the group directly affects all hosts in the group; Modules: various execution modules, almost all management tasks are performed through the module; Plugins: provides a variety of additional functions; API: provides an interface for programmers, based on which you can do the secondary development of Ansible

The specific performance is as follows:

Ansible Playbooks: task script, orchestration defines Ansible tasks and configuration files, executed sequentially by Ansible, usually YML files in JSON format; Inventory:Ansible management host list; Modules:Ansible command execution function module, most of which are built-in core modules that can also be customized; Plugins: additions to module functions, such as connection type plug-ins, loop plug-ins, variable plug-ins, filter plug-ins, etc., which are less commonly used API: application programming interface for third-party programs; Ansible: it is not obvious in this part of the diagram. The combination of Inventory, API, Modules and Plugins can be understood as an Ansible command tool, which is the core execution tool. Action object

The role of Ansible is not only for Linux and non-Linux operating system hosts, but also for all kinds of PUBLIC/PRIVATE, commercial and non-commercial equipment network facilities.

When a user uses Ansible or Ansible-Playbooks, after the server terminal enters the Ad-Hoc command set or Playbooks of Ansible, Ansible will follow the rules of pre-selection arrangement to disassemble Playbooks into Play step by step, then organize Play into tasks that Ansible can recognize, then call all modules and plug-ins involved in the task, transfer the task set to the remote client as temporary files or commands through SSH according to the list of hosts defined in Inventory and return the execution result If it is a temporary file, it will be deleted automatically after execution.

II. Configuration of Ansible 1.Ansible installation

The installation and deployment of Ansible is very simple. Take RPM installation as an example, its dependent software is only Python and SSH, and the system is installed by default. The management side of Ansible can only be Linux, such as Redhat, Debian, Centos. This experiment takes CentOS Linux release 7.3.1611 as an example:

1) install Ansible through YUM

The experimental environment can download the required software packages directly from the Internet. This blog provides dependent software packages needed to install Ansible automated operation and maintenance tools. Network disk link: link: https://pan.baidu.com/s/1l47WxsEpq99lYmxsVTUQMg

Extraction code: axmg

If you use the network disk link provided by yourself, set up your own yum configuration file and mount the CD, you don't have to say that, after all, it's too basic! Install it directly using the Internet (the lab environment recommends that both the firewall and SELinux be turned off)!

[root@localhost ~] # yum-y install ansible// install Ansible Automated Operation and maintenance tool 2) verify the installation results [root@localhost ~] # ansible-- versionansible 2.3.1.0 config file = / etc/ansible/ansible.cfg configured module search path = Default wdebo overrides python version = 2.7.5 (default, Nov 6 2016, 00:28:07) [GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] / / if the command can be executed normally Then the Ansible tool is installed successfully! 3) create SSH interaction-free login

Ansible manages the device through SSH, while SSH includes two authentication methods: one is authenticated by password, the other is verified by key pair. Password authentication must interact with the system; key pair authentication is interactive login-free. If you want to automatically manage the device through Ansible, it should be configured to avoid interactive login to the managed device. If you don't know much about SSH interactive login, you can refer to the blog post: there is a detailed introduction to Linux remote access and control, which will not be introduced in detail here!

[root@localhost ~] # ssh-keygen-t rsa / / generate key pair Generating public/private rsa key pair.Enter file in which to save the key (/ root/.ssh/id_rsa): / / key pair storage path Created directory'/ root/.ssh'.Enter passphrase (empty for no passphrase): / / enter the private key protection password Press enter directly to indicate no password Enter same passphrase again: / / enter Your identification has been saved in / root/.ssh/id_rsa.Your public key has been saved in / root/.ssh/id_rsa.pub.The key fingerprint is:36:9f:34:06:b2:d4:7d:64:81:34:9e:8c:a2:fd:6b:27 root@localhost.localdomainThe key's randomart again Image is:+-- [RSA 2048]-+ | .o. +. | |. =. = | + =. | | +. . | |. O S + | | o = o | |. O | | E.. | |. O | +-+ [root@localhost ~] # ssh-copy-id root@192.168.1.2 / / copy the public key to the remote 192.168.1.2The authenticity of host '192.168.1.2 (192.168.1.2)' can't be established.ECDSA key fingerprint is 25:54:5c:d5:ce:e1:04:9f: 25:19:be:73:ce:93:86:54.Are you sure you want to continue connecting (yes/no)? Yes/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key (s), to filter out any that are already installed/usr/bin/ssh-copy-id: INFO: 1 key (s) remain to be installed-- if you are prompted now it is to install the new keysroot@192.168.1.2's password: / / enter remote root password Number of key (s) added: 1Now try logging into the machine With: "ssh 'root@192.168.1.2'" and check to make sure that only the key (s) you wanted were added. [root@localhost ~] # ssh-copy-id root@192.168.1.3The authenticity of host' 192.168.1.3 (192.168.1.3) 'can't be established.ECDSA key fingerprint is 2b:03:6d:2b:d0:14:69:35:8b:7f:44:80:9a:a5:94:8a.Are You sure you want to continue connecting (yes/no)? Yes/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key (s), to filter out any that are already installed/usr/bin/ssh-copy-id: INFO: 1 key (s) remain to be installed-- if you are prompted now it is to install the new keysroot@192.168.1.3's password: Number of key (s) added: 1Now try logging into the machine With: "ssh 'root@192.168.1.3'" and check to make sure that only the key (s) you wanted were added. [root@localhost ~] # ssh 192.168.1.2 / / Test whether you can log in to Last login directly without a password: Wed Oct 9 21:26:24 2019 from 192.168.1.200 [root@localhost ~] # exit login Connection to 192.168.1.2 closed . [root@localhost] # ssh 192.168.1.3Last login: Wed Oct 9 21:26:28 2019 from 192.168.1.200 [root@localhost ~] # exit log out Connection to 192.168.1.3 closed.

At this point, the deployment of Ansible is complete, and the device can be managed through Ansible.

2.Ansible configuration

Inventory is a configuration file for Ansible to manage host information, which is equivalent to the function of the system Hosts file and is stored in / etc/ansible/hosts by default. In the hosts file, devices are organized by grouping, Ansible defines hosts and groups through Inventory, and Inventory is specified by using the option-I or-- inventory-file in the ansible command. For example:

[root@localhost] # ansible-I / etc/ansible/hosts web-m ping

If you use the default Inventory file (/ etc/ansible/hosts), you can also leave the Inventory file unspecified, such as:

[root@localhost] # ansible web-m ping

Ansible implements the management of devices by adding the device list to the / etc/ansible/hosts file in a grouped way, so before formal management, the hosts file should be written first. In the hosts file, the group name is represented by the part contained in [], and the device list supports hostname and IP address. By default, devices are managed by accessing port 22 (SSH). If the target host uses a non-default SSH port, you can also use a colon plus a port after the host name to separate the configuration by behavior units. In addition, hosts files support wildcards. As follows:

[root@localhost] # vim / etc/ansible/hosts. / / omit part of the content, fill in the following content according to the actual situation [web] 192.168.1.2192.168.1.3 [test] www.benet.com:222 / / manage the equipment [mail] yj1.kgc.cnyj [2:5] .kgc.cn / / [2:5] indicates all the numbers between 2 and 5, that is, yj2.kgc.cn, yj3.kgc.cn. All hosts of

A host can be placed in different groups at the same time.

After the configuration is complete, you can manage groups defined by hosts remotely or operate on one or more hosts in the group. For example:

(1) operate only on the 192.168.1.2 CVM in the web group, and limit the changes of the CVM by-- limit parameter:

[root@localhost ~] # ansible web-m command-a "systemctl status httpd"-- limit "192.168.1.2" 192.168.1.2 | SUCCESS | rc=0 > > / / you will know the success when you see SUCCESS, so if you test the httpd service below, the host under test must have installed and started the httpd service.

(2) operate only on 192.168.1.2 host. Limit changes to the host through IP:

[root@localhost ~] # ansible 192.168.1.2-m command-a "systemctl status httpd" 192.168.1.2 | SUCCESS | rc=0 > > / / the effect is the same, so I won't introduce it here.

(3) for the operation of the host in the 192.168.1.0 network segment, you need to use wildcards to limit the changes of the host:

[root@localhost ~] # ansible 192.168.1.*-m command-a "systemctl status httpd" 192.168.1.2 | SUCCESS | rc=0 > > / / Experimental environment, the effect is the same, so I won't talk about the 3.Ansible command here.

Most of the maintenance commands of Ansible start with ansible. Pressing the Tab key twice after the terminal enters ansible will complete all ansible-related commands, such as:

[root@localhost ~] # ansibleansible ansible-console-2 ansible-galaxy ansible-playbook-2.7 ansible-vault-2ansible-2 ansible-console-2.7 ansible-galaxy-2 ansible-pull ansible-vault-2.7ansible-2.7 ansible-doc ansible-galaxy-2.7 ansible-pull-2 ansible-connection ansible-doc-2 Ansible-playbook ansible-pull-2.7 ansible-console ansible-doc-2.7 ansible-playbook-2 ansible-vault

Here are just a few commonly used commands:

1) ansible

Ansible is one of the most frequently used commands in production environments and is mainly used in the following scenarios:

Non-solidified requirements; temporary one-time operation; secondary development interface call

Non-solidified requirements refer to temporary maintenance, such as viewing web server group disk usage, copying a file to another machine, and so on. Similar to these irregular, temporary tasks that need to be done, we become non-solidified requirements, temporary one-time operations, the syntax is as follows:

Ansible [options]

Available options, as shown in the figure:

(1) check whether all hosts are alive, and the command is as follows:

[root@localhost ~] # ansible all-f 5-m ping / / calls the ping module, and all represents all hosts in the / etc/ansible/hosts file There is no need to create an all grouping (default exists) 192.168.1.2 | SUCCESS = > {/ / indicates successful execution "changed": false / / No changes have been made to the host "ping": "pong" / / indicates the returned result of executing the ping command} 192.168.1.3 | SUCCESS = > {"changed": false "ping": "pong"} / / due to the experimental environment, only two test machines have been opened.

(2) list all the hosts in the web group with the following command:

[root@localhost ~] # ansible web-- list / /-- list: indicates the list of hosts hosts (2): 192.168.1.2 192.168.1.3

(3) batch display the disk usage space in the web group. The command is as follows:

[root@localhost ~] # ansible web-m command-a "df-hT" 192.168.1.3 | SUCCESS | rc=0 > > File system type capacity available available mount point / dev/mapper/cl-root xfs 17G 4.4G 13G 26% / devtmpfs devtmpfs 897M 0897m 0% / devtmpfs tmpfs 912m 84K 912m 1% / dev/shmtmpfs tmpfs 912M 0912M 0% / sys/fs/cgroup/dev/sda1 xfs 1014M 173M 842M 18% / boottmpfs tmpfs 183M 16K 183M 1% / run/user/42tmpfs tmpfs 183M 0 183M 0% / run/user/0192.168.1.2 | SUCCESS | rc=0 > > File system Type capacity used used mount point / dev/mapper/cl-root xfs 17G 4.3G 13G 26% / devtmpfs devtmpfs 897M 0897M 0% / devtmpfs tmpfs 912M 84K 912m 1% / dev/shmtmpfs tmpfs 912M 0912M 0% / sys/fs/cgroup/dev/sda1 xfs 1014M 173M 842M 18% / boottmpfs tmpfs 183M 16K 183M 1% / run/user/42tmpfs tmpfs 183M 0 183M 0% / run/user/0/dev/sr0 iso9660 4.1G 4.1G 0100% / mnt

The web keyword needs to define the group in the / etc/ansible/hosts file in advance.

The return result of Ansible is very friendly, and the execution result is generally represented in three colors:

Red: indicates that the execution process is abnormal; orange color: indicates that the target has a state change after the command is executed; green: indicates that the execution is successful and no modification has been made by the target machine; 2) Ansible-doc

Ansible-doc is used to query the documentation of ansible module. Similar to the man command, there are detailed usage instructions and application case descriptions for each module. The syntax is as follows:

Ansible-doc [options] [module...]

Commonly used commands:

[root@localhost ~] # ansible-doc-pong' on successful contact / list supported modules [root@localhost ~] # ansible-doc ping// description information about ping module > PING (/ usr/lib/python2.7/site-packages/ansible/modules/system/ping.py) A trivial test module, this module always returns `module. It does not make sense in playbooks, but it is useful from `/ usr/bin/ansible' to verify the ability to login and that a usable python is configured. This is NOT ICMP ping, this is just a trivial test module.EXAMPLES:# Test we can logon to 'webservers' and execute python with json lib.ansible webservers-m pingMAINTAINERS: Ansible Core Team, Michael DeHaanMETADATA: Status: [' stableinterface'] Supported_by: core3) Ansible-playbook

Ansible-playbook is the most frequently used command in daily applications, similar to the sh or source command in Linux, which is used to perform a series of tasks. Its working mechanism: to achieve centralized processing tasks by reading pre-written playbook files. The Ansible-playbook command is followed by a playbook file in yml format, and the playbook file stores the code of the task to be executed. The command is used as follows:

Ansible-playbook playbook.yml// but the playbook.yml file should be written in advance. It is recommended to use the absolute path 4) Ansible-console

Ansible-console is an interactive tool provided by Ansible, similar to cmd of Windows or shell of Linux. Users can use various commands built in Ansible like shell on ansible-console virtual terminals, which provides a good experience for users who are accustomed to using shell interactive mode. After the terminal enters the ansible-console command, it is displayed as follows:

[root@localhost ~] # ansible-consoleWelcome to the ansible console.Type help or? To list commands.// enter help or? Get help root@all (2) [FRV 5] $cd web / / use the cd command to switch hosts or group root@web (2) [FRV 5] $list / / list the current device 192.168.1.2192.168.1.3Cash / support Tab key completion, the shortcut key Ctrl+D or Ctrl+C can exit the current virtual terminal 4.Ansible module

There are many modules supported by Ansible. Here are a few commonly used ones, as follows:

1) command module

The command module executes commands on remote hosts, but does not support shell features such as pipes, redirects, and so on.

The common parameters are as follows:

Chdir: the directory to be entered before running the command on the remote host; creates: create a file when the command is running, and if the file already exists, the creation task will not be executed; removes: remove one when the command is running, and the removal task will not be executed if the file does not exist; executeable: indicates the shell program that runs the command

Example:

[root@localhost ~] # ansible all-m command-a "chdir=/home ls" / / run the "ls" command on all hosts, but switch to the / home directory before running 2) shell module

The shell module executes commands on the remote host, which is equivalent to calling the shell process of the remote host, and then opens a sub-shell to run the command under that shell. The difference from the command module is that it supports shell features such as pipes, redirects, etc.

Example:

[root@localhost ~] # ansible all m shell-an echo "hello" > > / tmp/hello.txt' [root@localhost ~] # ssh 192.168.1.2 cat / tmp/hello.txtHello// create a hello.txt file with the content Hello in the / tmp directory of all hosts, and view 3) copy module

The copy module is used to copy the specified host files to the specified location of the remote host.

Common parameters are:

Dest: indicates the destination directory location of the copied file, using an absolute path. If the source is a directory, the destination should also be a directory. If the destination file already exists, the original content will be overwritten. Src: indicates the path of the source file. You can use relative and absolute paths, and you can specify a directory directly. If the source is a directory, the destination also depends on the directory; mode: indicates the permissions of the target file when copying, optional; owner: indicates the owner of the target file, optional

* group: indicates the group of the target file when copying (optional); content: indicates the content copied to the target host and cannot be used with src, which is equivalent to copying the data specified by content to the target file

Example:

[root@localhost ~] # ansible web-m copy-a "src=/etc/hosts dest=/tmp mode=777 owner=nobody group=root" / / copy the local hosts file to all hosts in the web group and store it in the / tmp directory. The permission is 777, the owner is nobody, and the group is root4) hostname module

The hostname module is used to manage hostnames on remote hosts.

Commonly used parameters:

Name: indicates the hostname

Example:

[root@localhost ~] # ansible 192.168.1.2-m hostname-a name=aaa "/ / change the hostname of 192.168.1.2 to aaa, but 192.168.1.2 requires switching shell to take effect 5) yum module

The yum module is based on the yum mechanism and manages the package to the remote host.

The commonly used parameters are:

Name: the package name, which can be accompanied by the version number. If the version is unknown, it defaults to the latest version; state=present | atest | absent: indicates the action performed on the package: present indicates to install the package, latest indicates to install the latest version of the package, and absent indicates to uninstall the package; disablerepo: temporarily disables the ID;enablerepo of a warehouse when installing with yum: temporarily enables the ID;conf_file:yum runtime configuration file of a warehouse when installing with yum instead of using the default configuration file Disable_gpg_check=yes | no: whether to enable integrity check

Example:

[root@localhost ~] # ansible web-m yum-a "name=httpd state=present" / / controls the remote host to install the http service, but only if the remote host's yum repository is available. 6) service module

The service module is mainly used to manage services on remote hosts.

Common parameters are:

Name: the name of the managed service; state=started | stopped | restarted: the action includes startup, shutdown or restart; enable=yes | no: indicates whether to set the service to start automatically; runlevel: if enabled is set to start automatically, you need to define which targets to start automatically.

Example:

[root@localhost ~] # ansible web-m service-a "name=httpd state=started enabled=yes" / / start the httpd service of all hosts in the web group and set it to boot self-boot 7) user module

The user module is mainly used to manage user accounts on remote hosts.

Common parameters are:

Name: required parameter, account name; state=present | absent: create or delete account; present: create; absent: delete; system=yes | no: whether it is a system account; uid: user's basic group; group: user's basic group; groups: user's additional group; shell: default shell;home: user's home directory; mve_home=yes | no: if the set home directory already exists, whether to move the existing home directory Pssword: user's password. Encrypted string is recommended; comment: user's comment information; remore=yes | no: whether to delete the user's home directory when state=absent

Example:

[root@localhost ~] # ansible web-m user-a 'name=user1 system=yes uid=502 group=root'// create a new system user on all hosts in the web group, UID is 502, and the group is root

That's all the common modules are introduced!

5.playbook profile 1) execute profile

The playbook configuration file uses YAML syntax and has the characteristics of conciseness and clear structure. The playbook configuration file, similar to the Shell script, is an YAML format file that holds a list of tasks for specific needs. Although the ansible commands mentioned earlier can accomplish a variety of tasks, it is inefficient to enter commands one by one when configuring complex tasks. A more efficient way is to place all the task codes in the playbook configuration file, which can be automated by using the ansible-playbook command to execute the file. The extension of the YAML file is common sense. Yaml or .yml.

YAML syntax is similar to other high-level languages, the syntax is very strict (it is recommended to type by hand, do not copy, otherwise errors may occur), its structure is shown by indentation, using "-" to represent items; ":" is used to separate keys and values; the whole file starts with "-" and begins with "." The end is as follows:

[root@localhost ~] # vim / etc/ansible/a.yml----hosts: web / / operate on all hosts in the web group remote_user: root / / remote execution user as root tasks: / / Task list-name: adduser / / Task name user: name=user2 state=present / / execute user module Create user tags: / / create tags tag-aaa / / tags tag as aaa-name: addgroup group: name=root system=yes tags:-bbb...

All "-" and ":" are followed by spaces, and pay attention to indentation and alignment, as shown in the figure:

The core elements of playbook contain the following, as shown in the figure:

The tasks defined by the playbook file need to be invoked and executed through the ansible-playbook command. Commonly used parameters are shown in the figure:

Example:

[root@localhost ~] # ansible-playbook-- syntax-check / etc/ansible/a.ymlplaybook: / etc/ansible/a.yml// No error message Indicates that there is no syntax error [root@localhost] # ansible-playbook-C / etc/ansible/a.yml// prediction test PLAY [web] * * TASK [Gathering Facts] * ok: [192.168 .1.2] ok: [192.168.1.3] TASK [adduser] * changed: [192.168.1.2] changed: [192.168.1.3] TASK [addgroup] * * * ok: [192.168.1.2] ok: [192.168.1.3] PLAY RECAP * * 192.168.1.2: ok=3 changed=1 unreachable=0 failed=0 192.168.1.3: ok=3 changed=1 unreachable=0 failed=0 / / failed does not Indicates success [root@localhost ~] # ansible-playbook-- list-hosts / etc/ansible/a.yml// lists host playbook: / etc/ansible/a.yml play # 1 (web): web TAGS: [] pattern: [ubiweb'] hosts (2): 192.168.1.3 192.168.1.2 [root@localhost ~] # ansible-playbook-- list-tasks / etc/ansible/a.yml/ / list tasks playbook: / etc/ansible/a.ymlplay # 1 (web): web TAGS: [] tasks: adduser TAGS: [aaa] addgroup TAGS: [bbb] [root@localhost ~] # ansible-playbook-- list-tags / etc/ansible/a.ymlplaybook: / etc/ansible/a.ymlplay # 1 (web): web TAGS: [] TASK TAGS: [aaa Bbb] [root@localhost ~] # ansible-playbook / etc/ansible/a.yml// execute task PLAY [web] * * TASK [Gathering Facts] * ok: [192.168.1.3] ok: TASK [adduser] * changed: [192.168.1] .2] changed: [192.168.1.3] TASK [addgroup] * ok: [192 .168.1.2] ok: [192.168.1.3] PLAY RECAP * * 192.168.1.2: ok=3 changed=1 unreachable=0 failed=0 192.168.1.3: ok=3 changed=1 unreachable=0 failed=0

Remote host view effect:

[root@localhost ~] # tail-1 / etc/passwduser2:x:1001:1001::/home/user2:/bin/bash [root@localhost ~] # tail-1 / etc/passwduser2:x:1001:1001::/home/user2:/bin/bash

Usually the test is carried out first, there is no problem with the test, and then the task is carried out!

2) trigger

For tasks that need to be triggered to execute, if you want to trigger other tasks based on the successful execution of the tasks previously defined in tasks, you need to define handlers.

Handlers has the following characteristics:

Handlers is one of the conditional mechanisms provided by Ansible. Handlers is similar to task, but it triggers execution only when notified by task; handlers only executes after all tasks are completed, and even if notified multiple times, ta executes only once and in the defined order

Example:

[root@localhost ~] # ansible web-m shell-a "netstat-anpt | grep 80" 192.168.1.2 | SUCCESS | rc=0 > > tcp6 0 0:: 80:: * LISTEN 3527/httpd 192.168.1.3 | SUCCESS | rc=0 > > tcp6 0 0: 80 / / confirm the port information of httpd service in web group [root@ Localhost ~] # vim / etc/ansible/httpd.yml----hosts: web remote_user: root tasks:-name: change port command: sed-I 's/Listen 80/Listen 8080GPG' / etc/httpd/conf/httpd.conf notify: / / configure trigger condition-restart httpd server / / after completing the task Call this trigger handlers: / / configure trigger-name: restart httpd server / / define trigger name service: name=httpd state=restarted / / trigger task to restart the httpd service. [root@localhost ~] # ansible-playbook / etc/ansible/httpd.yml// execute yml File PLAY [web * TASK [Gathering Facts] * * ok: [192.168.1.3] ok: [192.168.1.2] TASK [change port] * * * [WARNING]: Consider using template or lineinfile module rather than running sedchanged: [192.168.1.2] changed: [192.168.1.3] RUNNING HANDLER [restart httpd server] * changed: [192.168.1.3] changed: [192.168.1.2] PLAY RECAP * * 192.168.1.2: ok=3 changed=2 unreachable=0 failed=0 192.168.1.3 : ok=3 changed=2 unreachable=0 failed=0 [root@localhost ~] # ansible web-m shell-a "netstat-anpt | grep 8080" 192.168.1.3 | SUCCESS | rc=0 > > tcp6 0 0: 8080:: * LISTEN 4947/httpd 192.168.1.2 | SUCCESS | rc=0 > > tcp6 00: 8080 : * LISTEN 4929/httpd / / View the port of the httpd service of the remote host has been changed to 80803) trigger

If you store a variety of different tasks files in a directory, the directory is the role. The role is generally stored in the / etc/ansible/roles/ directory. The default role directory can be adjusted through the ansible configuration file. There are many subdirectories under the / etc/ansible/roles/ directory, each of which corresponds to a role, and each role has its own directory structure, as shown in the figure:

/ etc/ansible/roles/ is a collection of roles. The subdirectories under this directory are customized, as shown in the figure:

In the directory in the figure, tasks, handlers, vars, meta, and default contain at least one main.yml file, and there can also be other .yml files, but you need to include the other .yml files in the main.yml file with the include directive.

Once you have the role, you can invoke the role directly in the yaml file (playbook configuration file). As follows:

[root@localhost ~] # vim / etc/ansible/mariadb.yml----hosts: web remote_user: root roles:-mariadb...

You can call only one role, or you can call multiple roles. When the role is defined, then use the ansible-playbook playbook file name! At this point, ansible will go to the directory of the role collection (/ etc/ansible/roles) to find the corresponding directory mariadb, and then execute all the code under the mariadb directory in turn.

① case 1: installing the mariadb database

It is required to install the mariadb database on the remote host, and after the installation is complete, create a new database and allow the test user to have all permissions on it.

The specific operations are as follows:

Both the remote host and the ansible management side have been configured to complete the yum warehouse. The ansible host installs the mariadb database and generates the mariadb database configuration file.

[root@localhost ~] # mkdir-p / etc/ansible/roles/mariadb/ {files,tasks Handles} [root@localhost ~] # vim / etc/ansible/roles/mariadb/tasks/main.yml---- name: install mariadb yum: name=mariadb-server state=present- name: move config file shell: "[- e / etc/my.cnf] & & mv / etc/my.cnf / etc/my.cnf.bak"-name: provide a new config file copy: src=my.cnf dest=/etc/my.cnf- name: reload mariadb shell: systemctl restart mariadb- name: create database testdb shell: mysql-u root-e "create database testdb Grant all on testdb.* to 'test'@'192.168.1.%' identified by' test123';flush privileges "notify:-restart mariadb... [root@localhost ~] # vim / etc/ansible/roles/mariadb/handles/main.yml---- name: restart mariadb service: name=mariadb state=restarted... [root@localhost ~] # cd / etc/ansible/roles/mariadb/files/ [root@localhost files] # cp / etc/my.cnf. [root@localhost files] # lsmy.cnf [root@localhost ~] # ansible-playbook-C / etc/ansible/mariadb.yml / / after there is no problem with the test Execute the following command [root@localhost ~] # ansible-playbook / etc/ansible/mariadb.yml [root@localhost ~] # mysql-u root Welcome to the MariaDB monitor. Commands end with; or\ g.Your MariaDB connection id is 3Server version: 5.5.52-MariaDB MariaDB ServerCopyright (c) 2000, 2016, Oracle, MariaDB Corporation Ab and others.Type 'help;' or'\ h' for help. Type'\ c'to clear the current input statement.MariaDB [(none)] > show databases +-+ | Database | +-+ | information_schema | | mysql | | performance_schema | | test | | testdb | +-+ 5 rows in set (0.00 sec) / / View effect of remote host

Remote installation of mariadb database has been completed!

② case 2: remote installation of ftp Services

In fact, it is similar to installing mariadb database!

[root@localhost ~] # yum-y install vsftpd [root@localhost ~] # mkdir-pv / etc/ansible/roles/vsftpd/ {files,tasks Handlers} [root@localhost ~] # vim / etc/ansible/roles/vsftpd/tasks/main.yml-name: install vsftpd yum: name=vsftpd state=present- name: move config file shell: "[- e / etc/vsftpd/vsftpd.conf] & & mv / etc/vsftpd/vsftpd.conf / etc/vsftpd/vsftpd.conf.bak"-name: provide a new config file copy: src=vsftpd.conf dest=/etc/vsftpd/vsftpd.conf- name: reload vsftpd shell: systemctl restart vsftpd- name: shangchuan Copy: src=/soft dest=/etc/vsftpd- name: zidongqidong shell: systemctl enable vsftpd- name: create user user: name=zhangsan state=present- name: set password shell: echo "123456" | passwd-- stdin zhangsan... [root@localhost ~] # cd / etc/ansible/roles/vsftpd/files/ [root@localhost files] # cp / etc/vsftpd/vsftpd.conf. [root@localhost files] # mkdir soft [root@localhost ~] # vim / etc/ansible/vsftpd.yml-hosts: web remote_user: root Roles:-vsftpd... [root@localhost ~] # ansible-playbook-C / etc/ansible/vsftpd.yml [root@localhost ~] # ansible-playbook / etc/ansible/vsftpd.yml

Client authentication:

[root@localhost ~] # ansible web-m shell-a "netstat-anpt | grep vsftpd" 192.168.1.3 | SUCCESS | rc=0 > > tcp6 0 0: 21:: * LISTEN 7552/vsftpd 192.168.1.2 | SUCCESS | rc=0 > > tcp6 00: 21: * LISTEN 7594/vsftpd

This is a brief introduction to the automated operation and maintenance tool Ansible.

-this is the end of this article. Thank you for reading-

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