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

Detailed explanation of Ansible Automation Operation and maintenance

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

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

As an increasingly popular open source operation and maintenance automation tool this year, Ansible can automate operation and maintenance through Ansible, improve the work efficiency of operation and maintenance engineers and reduce human error. Ansible can achieve a variety of management tasks through its own integration of very rich modules, with more than thousands of modules. More importantly, it is easy to operate, but provides 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 around the world, with the following characteristics:

1. Ansible is developed based on Python, and it is relatively easy for operation and maintenance engineers to redevelop it.

2. Ansible's rich built-in modules can meet almost all requirements.

3. The management mode is very simple. A single command can affect thousands of hosts.

4. Clientless mode, and the underlying layer communicates through SSH

There are four ways we can interact with Ansible, and I've only studied two of them here, and it's enough to deal with daily work. They are as follows:

1. Ad-Hoc command set: user calls the Ansible tool set directly through the Ad-Hoc command set to complete the task.

2. Playbooks:user prepares the ansible playbooks and executes the tasks in order by executing the pre-scheduled task set in playbooks.

1. Ansible working set:

.

The Ansible working set contains inventory, Modules, Plugins and API, in which inventory (list) is used to manage the list of devices, which can be realized by grouping, and the call to the group directly affects all the hosts in the group; modules is a variety of execution modules, almost all management tasks are performed through the module; plugins provides a variety of additional functions; API provides programmers with an interface based on which you can do the secondary development of Ansible.

.

Ansible can control and change multiple hosts through a single command or configuration file, which will be written from installation and configuration below.

2. Playbook configuration file

.

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 command described above can accomplish a variety of tasks, it is very inefficient to type one by one when configuring some complex tasks. A more efficient solution is to place all the task codes in the playbook configuration file, which can be automated by executing the file with the ansible-playbook command. YAML files usually have a .yaml or .yml extension.

.

Installation and configuration of Ansible

.

The environment is as follows:

1. Preparatory work:

1. Local yum repository: https://pan.baidu.com/s/1-ERCVm6QaUA4XQd_X5Kwow extraction code: exnp version: Ansible 2.3.1.0

2. If the local computer is connected to the Internet, it can point to the Internet yum warehouse.

3. TCP 22 is used by default to communicate with the client. If there is any change, you need to set up your own firewall to release it.

Second, install Ansible:

[root@ansible /] # mount / dev/sr0 / media/ # Mount yum repository [root@ansible /] # rm-rf / etc/yum.repos.d/* # Delete or remove other configuration files in the yum directory [root@ansible /] # vim / etc/yum.repos.d/a.repo [aaa] baseurl= file:///mediagpgcheck=0[root@ansible yum.repos.d] # yum clean All # clear yum cache [root@ansibleyum.repos.d] # yum-y install ansible # install version [root @ ansibleyum.repos.d] # ansible-- you can see this information Ansible 2.3.1.0 config file = / etc/ansible/ansible.cfg.

I use the Internet yum repository for installation here, that is, ansible 2.4.2.0.

.

The installation has been completed, but if you want to use Ansible normally, you need to solve another problem, that is, when you control multiple hosts, if you have to enter the peer password every time you execute a command or script, it will be very scary, so you also need to create a SSH interactive-free login, as follows:

.

The following operations are done on the Ansible server:

[root@ansible ~] # ssh-keygen-t rsa # generates a key pair on the Ansible server Press enter Generating public/private rsa key pair.Enter file in which to save the key (/ root/.ssh/id_rsa) by default after execution: # press enter Enter passphrase (empty for no passphrase) by default: # press enter Enter same passphrase again by default: # press enter Your identification has been saved in / root/.ssh/id_rsa.Your public key has been saved in / by default Root/.ssh/id_rsa.pub.The key fingerprint is: # default press enter SHA256:zhd2++KvByxFPE4ZKmDdmTHp6cjsuIEz5M26QrkBfes root@ansibleThe key's randomart image is: # default press enter +-[RSA 2048]-+ | o. O * .o |. .. = o* | |. . =. | |. . . .o o | |. o.。 OSooo. | | + o.+ o+.ooo. | | |. + = + oo.... | | o Emission. | . | | .o. .o = o | +-[SHA256]-+ # so far the key pair has been generated and hidden in the host directory of the current user. [root@ansible ~] # ls-a | grep ssh # View .ssh [root@ansible ~] # cd .ssh [root@ansible .ssh] # ls # View the files in the .ssh directory Id_rsa id_rsa.pub known_ hosts with public key and private key [root @ ansible ~] # ssh-copy-id root@192.168.1.20 # copy the public key to the host 192.168.1.20root@192.168.1.20's password: # enter the root user password of host 1.20 [root@ansible ~] # ssh-copy-id root@192.168.1.30 # Copy the public key to the host 192.168.1.30root@192.168.1.30's password: # enter the root user password of host 1.30 # in the actual production environment Instead of using the root identity, just change the user you specified when you copied the public key. [root@ansible ~] # ssh 192.168.1.20 # Test password-free login Last login: Tue Jul 23 08:11:39 2019 from 192.168.1.88 [root@server1 ~] # exit # exit from the shell environment of 192.168.1.2 [root@ansible ~] # ssh 192.168.1.30 # Test whether password-free login is possible for Last login: Tue Jul 23 08:43:16 2019 from 192.168.1.88 [root@server 2] # exit # quit the shell environment of 192.168.1.3

3. Ansible configuration:

Inventory is a configuration file for Ansible to manage host information, which is equivalent to the hosts file function of the system. It is stored in / etc/ansible/hosts by default. In the hosts file, devices are organized by grouping, and Ansible defines hosts and groups through inventory. If you do not use the default / etc/ansible/hosts, you can specify inventory through the new inventory path of ansible-I. I directly use the default path here.

.

1. Add the hosts to be managed by grouping:

.

Just before management, you first need to write a hosts file, because Ansible manages devices by adding hosts files to the list of devices in groups. In the hosts file, [] contains the group name. The device list supports domain names and IP addresses. By default, you can manage devices by accessing port 22 (SSH). If the target host uses a non-default SSH port, you can also use colons plus port numbers after the host name to separate units by behavior, and wildcards are also supported.

.

[root@ansible ~] # vim / etc/ansible/hosts # edit the manifest file and write the following at the end of the file. # omit part of [web] # define a packet named web, the following is the host 192.168.1.20192.168.1.30 [test01] # in the web group, define a packet named test01, and the following is the host www.test.com:222 in the test01 group # if the target host uses a non-default SSH port You can add a port number after the domain name to specify www [2:5] .test.com # [2:5] to represent all the numbers between 2 and 5, such as www2.test.com, www3.test.com. You can also specify a non-default port number # after all the hosts 192.168.1.4 IP 66 # address can be written to the host to be managed, and then save and exit. Notice that this file contains an implicit grouping of "all" for all hosts.

.

After the configuration is completed, you can operate remotely on the group defined by hosts, or on one or more hosts specified in the group, as follows:

[root@ansible ~] # ansible web-m command-a "systemctl status httpd"-limit "192.168.1.20" # View the status of the 192.168.1.20 host httpd service in the web group 192.168.1.20 | FAILED | rc=3 > > ● httpd.service-The Apache HTTP Server Loaded: loaded (/ usr/lib/systemd/system/httpd. Preset: disabled) Active: inactive (dead) Docs: man:httpd (8) man:apachectl (8) non-zero return code# can also be like this: [root@ansible ~] # ansible 192.168.1.20-m command-a "systemctl status httpd" 192.168.1.20 | FAILED | rc=3 > > ● httpd.service-The Apache HTTP Server Loaded: loaded (/ usr/lib/systemd/system/httpd. Preset: disabled) Active: inactive (dead) Docs: man:httpd (8) man:apachectl (8) non-zero return code [root@ansible ~] # ansible 192.168.1.*-m command-a "systemctl status httpd" # query the httpd service status of all hosts in this network segment 192.168.1.20 | FAILED | rc=3 > .192. 168.1.30 | FAILED | rc=3 > >.

4. Ansible command:

[root@ansible ~] # ansible # press tab twice after entering tab You can view all ansible-related commands, ansible ansible-doc ansible-playbook-2ansible-2 ansible-doc-2 ansible-playbook-2.7ansible-2.7 ansible-doc-2.7 ansible-pull..

Command 1, ansible:

.

Ansible is one of the most frequently used commands in the production environment, which is mainly used in the following scenarios:

.

Temporary maintenance, irregular, temporary tasks that need to be done, also known as non-solidified requirements. Temporary one-time operation. The secondary development interface is called.

The options available for ansible are as follows:

-v: output detailed information about the execution process, and you can get all the information about the execution process. -I PATH: specify inventory information. Default is / etc/ansible/hosts. -f: number of concurrent threads. Default is 5 threads. -- private-key=PRIVATE_KEY_FILE: specifies the key file. -m: specifies the module to be used for execution. -M: specify the storage path of the module. The default is / usr/share/ansible. You can also set the default path through ANSIBLE_LIBRARY. -a: specify module parameters. -u: specifies which user the remote host uses to run the command. -l: limit running hosts, which is equivalent to "--limit". -- list-hosts: lists the hosts that meet the criteria and does not execute any commands.

Usage example 1 (you need to define the web group in the / etc/ansible/hosts file in advance):

[root@ansible ~] # ansible all-f 5-m ping 192.168.1.30 | SUCCESS = > {"changed": false, "ping": "pong"} 192.168.1.20 | SUCCESS = > {"changed": false, "ping": "pong"}

Usage example 2:

[root@ansible ~] # ansible web-- list # lists all hosts in the web group hosts (2): 192.168.1.20 192.168.1.3 "above means that the web contains two hosts, 1.20 and 1.30, respectively.

Usage example 3:

[root@ansible ~] # ansible web-m command-a "df-hT" # shows the disk usage of the hosts in the web group 192.168.1.20 | SUCCESS | rc=0 > > File system type capacity used available mount point / dev/mapper/centos-root xfs 50G 5.8G 45G 12% / devtmpfs devtmpfs 895m 0895m 0% / dev.. # omit part 192.168.1.30 | SUCCESS | rc=0 > > File system type capacity available available mount point / dev/mapper/cl-root xfs 17G 5.5g 12g 33% / devtmpfs devtmpfs 897M 0897m 0% / devtmpfs tmpfs 912m 84K 912m 1% / dev/shm .. # omit part

The return result of ansible is very friendly, and the execution result is generally represented in three colors: red, green, and orange yellow (which color is harmonious). Red indicates that there is an exception during execution; orange yellow indicates that the target has changed after the command is executed; and green indicates that the execution is successful and no changes have been made to the target host.

Command 2, ansible-doc:

Ansible-doc is used to query the documentation of the ansible module, similar to the man command, with detailed usage instructions and application cases for each module.

[root@ansible ~] # ansible-doc-l | wc-l # list supported modules 1378 # supported modules have 1378 [root@ansible ~] # ansible-doc ping # query ping module description > 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. # omit part of the content

Command 3, 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 is 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 task code to be executed. The command is used as follows (the playbook.yml file needs to be written in advance. It is best to specify the absolute path of playbook.yml):

[root@ansible ~] # ansible-playbook playbook.yml

Command 4, ansible-console:

.

Ansible-console is an interactive tool provided by ansible, similar to cmd in Windows and shell in Linux. Ansible built-in commands can be used on ansible-console virtual terminals like shell, which provides a good experience for users who are accustomed to shell interaction, all operations are similar to shell, and support tab completion. The specific operations are as follows:

[root@ansible ~] # ansible-console # Connect interactive tool Vault password: # ansible 2.4.2.0 will prompt for a password. Enter it casually and press enter. Null Welcome to the ansible console.Type help or is not allowed. To list commands.root@all (2) [FRV 5] $cd web # switch to web group root@web (2) [FRV 5] $list # list the hosts in the group 192.168.1.20192.168.1.30root@web (2) [FRV 5] $ifconfig ens33 # query the network card information of each host root@web (2) [FRV 5] $exit # exit the ansible-console environment

5. Introduction of modules included in Ansible:

1. Command module:

The command module executes commands on the remote host and does not support shell features such as pipeline and redirection. The rest are similar to shell. The common parameters are as follows:

Chdir: a directory that needs to be entered in advance before running a command on a remote host. Creates: create a file while the command is running, and if the file already exists, the creation task will not be performed. Removes: remove a file while the command is running, and if the file does not exist, the removal task will not be performed. Executeble: indicates the shell program that runs the command. [root@ansible ~] # ansible all-m command-a "chdir=/home ls. /" # run the "ls. /" command on all hosts and change to the / home directory before running.

2. Shell module (equivalent to a universal module, which can execute most commands):

.

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 under shell to run the command. The difference from the command module is that it supports shell features, such as pipe characters, redirects, and so on.

.

[root@ansible ~] # ansible web-m shell-a 'echo "hello world" > > / tmp/hello.txt'# write a txt file 192.168.1.20 on the host of web group | SUCCESS | rc=0 > > 192.168.1.30 | SUCCESS | rc=0 > > [root@ansible ~] # ansible web-m shell-a' cat / tmp/hello.txt'# View the file 192.168.1.30 | SUCCESS | rc=0 > > hello world192.168.1.20 | SUCCESS | rc=0 > > hello world

3. Copy module:

The copy module is used to copy the specified host file to the location of the remote host. Common parameters are as follows:

Src: indicates the source file path, which can be used in both relative and absolute paths. It is supported to specify a directory directly, and if the source is a directory, the destination is also a directory. Dest: indicates the destination directory location of the copied file, using an absolute path, and allows you to specify a directory directly. If the source is a directory, the destination is also a directory, and if the destination already exists, the original content will be overwritten. Mode: indicates the permissions of the target file when copying. Optional. Owner: indicates the owner of the target file when copying, optional. Group: indicates that when copying, the target file belongs to the group, optional. Content: indicates that the content copied to the target host cannot be used with src, which is equivalent to copying the data specified by content to the target file. [root@ansible ~] # ansible web-m copy-a "src=/etc/hosts dest=/tmp/ mode=777 owner=nobody group=root" # copy the local / etc/hosts file to the host in the web group, and specify a permission of 777. the owner is nobody and the group is root.

4. Hostname module:

The hostname module is used to manage hostnames. Common parameters are as follows:

Name: indicates the hostname.

[root@ansible ~] # ansible 192.168.1.20-m hostname-a "name=web1" # change the hostname of host 192.168.1.20 to web1192.168.1.20 | SUCCESS = > {ansible_facts: {ansible_domain:, ansible_fqdn: web1, ansible_hostname web1 ansible_nodename: web1} Changed: true name: web1} [root@server1 ~] # hostname # View web1 on the 192.168.1.20 host [root @ server1 ~] # cat / etc/hostname # check the web1# on the 192.168.1.20 host and then restart for the new host name to take effect.

5. Yum module:

The yum module is based on yum mechanism. For remote host management packages, the common parameters are as follows:

Name: the name of the package, with a version number. If the version is not specified, the latest version is installed by default. State=present | latest | absent: indicates the action to be performed on the package. Present means to install the package, latest means to install the latest version of the package, and absent means to uninstall the package. Disablerepo: temporarily disable ID for a warehouse when installing with yum. Enablerepo: when installing with yum, temporarily enable the ID of a warehouse. The configuration file for the conf_file:yum runtime instead of using the default configuration file. Diable_gpg_check=yes | no: whether to enable integrity verification. [root@ansible] # ansible web-m yum-a "name=httpd state=present"

6. Service module:

Service module A module used to manage services on a remote host. Common parameters are as follows:

Name: the name of the service being managed. State=started | stopped | restarted | reloaded: actions include starting, shutting down, restarting and reloading configuration files. Enabled=yes | no: indicates whether to set the service to start automatically. Runlevel: if enabled boot is set, then define automatic startup under those running targets, such as 2, 3, 4, and 5. [root@ansible ~] # ansible web-m service-a "name=httpd state=started enabled=yes" # starts the httpd service and sets it to boot automatically.

7. User module:

The user module is used to manage user accounts on remote hosts. Common parameters are as follows:

Name: required parameter, account name. State=present | absent: create or delete an account. Present: create, and absent: delete. System=yes | no: whether it is a system account. Uid: user UID. Group: the basic group of the user. Groups: an additional group for the user. Shell: the shell used by default. Home: the user's home directory. Move_home=yes | no: if the home directory already exists, whether to move the existing home directory. Password: the user's password. Comment: the user's comment information. Remove=yes | no: whether to delete the user's home directory when state=absent. [root@ansible ~] # ansible web-m user-a 'name=user1 system=yes uid=501 group=root groups=sshd shell=/sbin/nologin home=/home/user1 password=user1 comment= "test user"' # create a user named user1 [root@ansible ~] # ansible web-m user-a "name=user1 remove=yes state=absent" # delete the user1 user you just created

8. Group module:

The group module is used to manage groups and to create or delete groups. Common parameters are as follows:

Gid: gidname of the specified group: namestate=present of the specified group | absent: create or delete system=yes | no: whether to create a system group [root@ansible ~] # ansible web-m group-a 'name=test gid=300 state=present system=yes'# whose gid is 300and the group name is test. [root@ansible ~] # ansible web-m group-a 'name=test gid=300 state=absent system=yes'# deletes the group you just created.

9. Mount module:

Mount module is used to mount the file system. The common parameters are as follows:

Src: device or file system to be mounted name: specify mount point fstype: specify file system type ots=w | r | o: set the file read and write type, which can be used in combination. State=present | absent | mounted | unmounted:present: only modify the configuration in the fstab file, do not automatically create mount points, and do not mount them; absent: delete mount points, modify fstab files; mounted: automatically create mount points and mount them, and add automatic mount (fstab); unmounted: only unmount, do not delete mount points, and do not modify fstab files. [root@an..~] # ansible web-m mount-a 'name=/warrent src=/dev/cdrom fstype=iso9660 state=mounted'# mount iso is mirrored to the / warrent directory, and auto mount is set when powered on. [root@ansible ~] # ansible web-m mount-a 'name=/warrent state=absent'# unmount the ISO image, delete the mount point, and delete the auto mount when powered on. [root@an..~] # ansible web-m mount-a "path=/mnt/data src=/dev/sdb1 fstype=xfs ots=wr state=mounted" # Note: mount has used path instead of the name parameter, but the name parameter can still be used.

10. Cron module:

The cron module is used to manage scheduled tasks. The common parameters are as follows:

Name: specify scheduled task description, required job: task to be executed user: the user running scheduled task: minute:0-59, default is * hour:0-23, default is * day:1-31, default is * month:1-12, default is * weekday:1-7, default is * state=present | absent:present means to add scheduled task; absent means to delete scheduled task. [root@ansible ~] # ansible web-m cron-a 'name=test user=root minute=*/2 job= "echo test > > / tmp/warrent.txt" state=present'# add a scheduled task test [root@ansible ~] # ansible web-m shell-a "crontab-l" # View the created task plan 192.168.1.20 | SUCCESS | rc=0 > > # Ansible: test*/2 * echo test > > / tmp/warrent.txt192 .168.1.30 | SUCCESS | rc=0 > > # Ansible: test*/2 * echo test > > / tmp/warrent.txt

11. Script module:

Function: execute the script of the host on the remote host, which is equivalent to the combination of scp+shell.

The usage is as follows:

[root@ansible ~] # ansible web-m script-a "/ home/test.sh"

For more information about the use of playbook configuration files, please refer to: https://blog.51cto.com/14227204/2442514

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