In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/03 Report--
Automatic operation and maintenance tool-- ansible detailed explanation case sharing (1)
Catalogue
Introduction to ansible
What is ansible?
Characteristics of ansible
Ansible architecture diagram
Ansible task execution
Ansible task execution mode
Ansible execution process
Ansible command execution process
Ansible configuration details
Ansible installation mode
Install using pip (the package management module of python)
Install using yum
Ansible program structure
Ansible profile lookup order
Ansible profile
Ansuble host list
Ansible common commands
Ansible command set
Ansible-doc command
Detailed explanation of ansible command
Ansible configuration of public and private keys
Common modules of ansible
1) Host connectivity test
2) command module
3) shell module
4) copy module
5) file module
6) fetch module
7) cron module
8) yum module
9) service module
10) user module
11) group module
12) script module
13) setup module
Text
Introduction to ansible
What is ansible?
Ansible is a new automatic operation and maintenance tool. Based on Python development, it integrates the advantages of many operation and maintenance tools (puppet, chef, func, fabric), and realizes the functions of batch system configuration, batch program deployment, batch running commands and so on.
Ansible is based on paramiko development, and is based on modular work, and does not have the ability to deploy in batches. What really has batch deployment is the module that ansible runs, and ansible only provides a framework. Ansible does not need to install client/agents on remote hosts because they are based on ssh and remote
Through the host computer. Ansible has been officially acquired by Red Hat and is the most recognized automated operation and maintenance tool. It is easy to use and easy to learn. It is one of the skills that every operation and maintenance engineer must master.
Characteristics of ansible
The deployment is simple, only the Ansible environment needs to be deployed on the master side, and the controlled side does not need to do anything.
SSH protocol is used by default to manage the device.
There are a large number of routine operation and maintenance operation modules, which can realize most of the daily operations.
Simple configuration, powerful function and strong expansibility
Support for API and custom modules, which can be easily extended through Python
Customize powerful configuration and state management through Playbooks
Lightweight, no need to install agent on the client side, you only need to make an update on the manipulator when updating
Provide a powerful and operational Web management interface and REST API interface-AWX platform.
Ansible architecture diagram
The main modules we see in the above figure are as follows:
Ansible:Ansible core program.
HostInventory: records host information managed by Ansible, including port, password, ip, etc.
Playbooks: "script" YAML format file, where multiple tasks are defined in one file, defining which modules the host needs to call to complete the function.
CoreModules: core module, the main operation is to call the core module to complete the management task.
CustomModules: custom module, complete the core module can not complete the function, support multiple languages.
ConnectionPlugins: connection plug-in, used for Ansible and Host communication
Ansible task execution
Ansible task execution mode
The operation mode of the managed node by the control host in the Ansible system can be divided into two types, namely adhoc and playbook:
Ad-hoc mode (point-to-point mode)
Using a single module, batch execution of a single command is supported. The ad-hoc command is a command that can be entered quickly and does not need to be saved. It is equivalent to a word shell in bash.
Playbook mode (script mode)
It is not only the main management mode of Ansible, but also the key to the powerful function of Ansible. Playbook completes a class of functions through multiple task collections, such as the installation and deployment of Web services, batch backups of database servers, and so on. You can simply think of playbook as a configuration file by combining multiple ad-hoc operations.
Ansible execution process
The simple understanding is that when Ansible is running, it first reads the configuration in ansible.cfg, obtains the list of management hosts in Inventory according to the rules, executes the configuration tasks in these hosts in parallel, and finally waits for the returned results.
Ansible command execution process
Load your own configuration file, default / etc/ansible/ansible.cfg
Find the corresponding host configuration file and find the host or group to execute
Load your own corresponding module files, such as command
Generate a corresponding temporary py file (python script) through ansible and transfer the file to a remote server
The .ansible / tmp/XXX/XXX.PY file corresponding to the home directory of the executing user
Give file + x execute permission
Execute and return the result
Delete temporary py file and exit with sleep 0
Back to the top.
Ansible configuration details
Ansible installation mode
There are two common ways to install ansible: yum installation and pip program installation. Let's introduce these two installation methods in detail.
Install using pip (the package management module of python)
First, we need to install a python-pip package. After the installation is complete, we directly use the pip command to install our package. The specific procedure is as follows:
Yum install python-pippip install ansible
Install using yum
Yum installation is a familiar installation method. We need to install an epel-release package before installing our ansible.
Yum install epel-release-yyum install ansible-y
Ansible program structure
The installation directory is as follows (yum installation):
Configuration file directory: / etc/ansible/
Executive file directory: / usr/bin/
Lib library depends on directory: / usr/lib/pythonX.X/site-packages/ansible/
Help document directory: / usr/share/doc/ansible-X.X.X/
Man document directory: / usr/share/man/man1/
Ansible profile lookup order
Ansible is very different from our other services in that the profile lookup here is found from multiple places in the following order:
Check the path file (export ANSIBLE_CONFIG=/etc/ansible.cfg) pointed to by the environment variable ANSIBLE_CONFIG
~ / .ansible.cfg, check the ansible.cfg configuration file in the current directory
/ etc/ansible.cfg checks the configuration file of the etc directory.
Ansible profile
The configuration file for ansible has many parameters for / etc/ansible/ansible.cfg,ansible. Here are some common parameters:
The parameter inventory = / etc/ansible/hosts # indicates that the location of the resource list inventory file library = / usr/share/ansible # points to the directory where the Ansible module is stored. Multiple directories are supported. You can forks = 5 # concurrent connections as long as you are separated by a colon (:). The default setting is 5sudo_user = root # the user who executes the command by default remote_port = 22 # specifies the management port to connect the managed node, default is port 22. It is recommended to modify it to make it more secure host_key_checking = False # setting whether to check the key of the SSH host, with a value of True/False. The first connection after closing does not prompt to configure the instance timeout = 60 # to set the timeout of the SSH connection, in seconds log_path = / var/log/ansible.log # specify a file to store ansible logs (no logs are recorded by default)
Ansuble host list
In the configuration file, we mentioned the resource list, which is our host list, which contains a list of hosts that ansible needs to connect to and manage. Let's take a look at the way he defines it:
1. Directly specify the host address or host name:
# www.wangwang.com#
192.168.10.10
192.168.10.20
2. Define a host group [group name]. Add the address or host name.
[mysql_test]
192.168.10.10
192.168.10.20
192.168.10.30
It is important to note that the group members here can use wildcards to match, which is easy and convenient for some standardized management.
We can configure our list of hosts according to the actual situation, as follows:
[root@server ~] # vim / etc/ansible/hosts
[web]
192.168.10.10
192.168.10.20
Back to the top.
Ansible common commands
Ansible command set
/ usr/bin/ansible Ansibe AD-Hoc temporary command execution tool, often used for temporary command execution
/ usr/bin/ansible-doc Ansible module function view tool
/ usr/bin/ansible-galaxy download / upload excellent code or Roles module official website platform, web-based
/ usr/bin/ansible-playbook Ansible customized automated task set orchestration tool
/ usr/bin/ansible-pull Ansible tool for remote command execution, pull configuration rather than push configuration (less used, used on massive machines, and higher requirements for operation and maintenance architecture)
/ usr/bin/ansible-vault Ansible File encryption tool
/ usr/bin/ansible-console Ansible is a command execution tool that can interact with users based on Linux Consoble interface.
Among them, we are more commonly used are / usr/bin/ansible and / usr/bin/ansible-playbook.
Ansible-doc command
The ansible-doc command is often used to get module information and its usage help, and the general usage is as follows:
Ansible-doc-l # get information about all modules ansible-doc-s MOD_NAME # get help for the use of specified modules
We can also look at the full usage of ansible-doc:
[root@server ~] # ansible-doc
Usage: ansible-doc [options] [module...]
Options:
-h,-- help show this help message and exit # displays the command parameter API document
-l,-- list List available modules # lists available modules
-M MODULE_PATH,-- module-path=MODULE_PATH # specify the path of the module
Specify path (s) to module library (default=None)
-s,-- snippet Show playbook snippet for specified module (s) # shows the usage of the playbook formulation module
-v,-- verbose verbose mode (- vvv for more,-vvvv to enable # displays the version number of ansible-doc to view the list of modules:
Connection debugging)
-- version show program's version number and exit
Let's take a look at the mysql-related example:
[root@server ~] # ansible-doc-l | grep mysql
Mysql_db Add or remove MySQL databases from a remote...
Mysql_replication Manage MySQL replication
Mysql_user Adds or removes a user from a MySQL databas...
Mysql_variables Manage MySQL global variables
[root@server] # ansible-doc-s mysql_user
Detailed explanation of ansible command
The specific format of the command is as follows:
Ansible [- f forks] [- m module_name] [- an args]
You can also view the help through ansible-h. Here are some of the more common options and explain what they mean:
-a parameter of the MODULE_ARGS # module. If the module that executes the default COMMAND, it is the command parameter, such as "date", "pwd", etc.
-kmam Murask pass # ask for SSH password. Login password, prompting for a SSH password instead of assuming key-based authentication
-- ask-su-pass # ask for su password. Su switch password
-Kremlin MuraskMurask Sudorippass # ask for sudo password. Prompt password to use sudo,sudo to indicate the lifting operation
-- ask-vault-pass # ask for vault password. Suppose we set an encrypted password, then use this option to access
-B SECONDS # background running timeout
-C # simulates the running environment and carries out pre-operation, which can be tested for error checking.
-c CONNECTION # connection type using
-f FORKS # parallel tasks. Default is 5.
-I INVENTORY # specifies the path to the host list. Default is / etc/ansible/hosts
-- list-hosts # to see which host groups are available
-m MODULE_NAME # the name of the execution module. The command module is used by default, so if you only execute a single command, you do not need the-m parameter.
-o # compress the output and try to output all the results in one line, usually for collection tools
-S # use the su command
-R SU_USER # specifies the user of su, which defaults to root user
-s # use the sudo command
-U SUDO_USER # specifies which user sudo goes to. The default is root user.
-T TIMEOUT # specifies the default timeout of ssh, which is 10s by default, and can also be modified in the configuration file
-u REMOTE_USER # remote user, default is root user
-v # View details and support-vvv,-vvvv to view more details
Ansible configuration of public and private keys
As mentioned above, ansible is implemented based on ssh protocol, so it configures public and private keys in the same way as ssh protocol. The specific steps are as follows:
# 1. Generate a private key
[root@server ~] # ssh-keygen
# 2. Distribute the private key to the host
[root@server ~] # ssh-copy-id root@192.168.10.10
[root@server ~] # ssh-copy-id root@192.168.10.20
In this way, we can log in without a password, and our experiment process will be much smoother.
Note that if an error occurs:
-bash: ssh-copy-id: command not found
That proves that we need to install a package:
Yum-y install openssh-clientsansible
Just install the package.
Back to the top.
Common modules of ansible
1) Host connectivity test
We use the ansible web-m ping command to test host connectivity, and the results are as follows:
[root@server] # ansible web-m ping
192.168.10.10 | SUCCESS = > {
"changed": false
"ping": "pong"
}
192.168.10.20 | SUCCESS = > {
"changed": false
"ping": "pong"
}
This shows that our host is connected. The next operation can be carried out normally.
2) command module
This module can execute commands directly on the remote host and return the results to the local host.
Examples are as follows:
[root@server] # ansible web-m command-a'ss-ntl'
192.168.10.10 | SUCCESS | rc=0 > >
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128: 111:
LISTEN 0 5 192.168.122.1:53:
LISTEN 0 128: 22:
LISTEN 0 128 127.0.0.1:631:
LISTEN 0 128: 23000:
LISTEN 0 100 127.0.0.1:25:
LISTEN 0 128: 111:
LISTEN 0 128: 22:
LISTEN 0 128:: 1:631:
LISTEN 0 100:: 1:25: *
192.168.10.20 | SUCCESS | rc=0 > >
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128: 111:
LISTEN 0 128: 22:
LISTEN 0 128 127.0.0.1:631:
LISTEN 0 128: 23000:
LISTEN 0 100 127.0.0.1:25:
LISTEN 0 128: 111:
LISTEN 0 128: 22:
LISTEN 0 128:: 1:631:
LISTEN 0 100:: 1:25: *
The command module accepts the command name, followed by a space-separated list parameter. The given command will be executed on all selected nodes. It will not be processed through shell, such as $HOME and operations such as ","; "," & "work (you need to use the (shell) module to achieve these functions). Note that this command does not support the | pipe command.
Let's take a look at several commands commonly used under this module:
Chdir # change to this directory before executing the command
Executable # switch shell to execute a command, using the absolute path of the command
The Linux instruction to be executed by free_form # is generally replaced by the-a parameter of Ansible.
Creates # A file name. When the file exists, the command is not executed. You can
To make a judgment.
Removes # A file name that does not exist, the command will not be executed
Let's take a look at the execution of these commands:
[root@server ~] # ansible web-m command-a 'chdir=/data/ ls' # first change to the / data/ directory, and then execute the "ls" command
192.168.10.10 | SUCCESS | rc=0 > >
Aaa.jpg
Fastdfs
Mogdata
Tmp
Web
WKgleloeYoCAMLtZAAAWEekAtkc497.jpg
192.168.10.20 | SUCCESS | rc=0 > >
Aaa.jpg
Fastdfs
Mogdata
Tmp
Web
WKgleloeYoCAMLtZAAAWEekAtkc497.jpg
[root@server ~] # ansible web-m command-a 'creates=/data/aaa.jpg ls' # if / data/aaa.jpg exists, do not execute the "ls" command
192.168.10.10 | SUCCESS | rc=0 > >
Skipped, since / data/aaa.jpg exists
192.168.10.20 | SUCCESS | rc=0 > >
Skipped, since / data/aaa.jpg exists
[root@server ~] # ansible web-m command-a 'removes=/data/aaa.jpg cat / data/a' # if / data/aaa.jpg exists, execute the "cat / data/a" command
192.168.10.10 | SUCCESS | rc=0 > >
Hello
192.168.10.20 | SUCCESS | rc=0 > >
Hello
3) shell module
The shell module can call the shell interpreter to run commands on the remote host, supporting various functions of shell, such as pipes and so on.
[root@server ~] # ansible web-m shell-a 'cat / etc/passwd | grep "keer"'
192.168.10.10 | SUCCESS | rc=0 > >
Keer:x:10001:1000:keer:/home/keer:/bin/sh
192.168.10.20 | SUCCESS | rc=0 > >
Keer:x:10001:10001::/home/keer:/bin/sh
As long as it is our shell command, it can be run on the remote host through this module, so there are no examples here.
4) copy module
This module is used to copy files to a remote host while supporting file generation and modification permissions for a given content.
The relevant options are as follows:
Src # is copied to the local file of the remote host. It can be an absolute path or a relative path. If the path is a directory, it is copied recursively, using something similar to "rsync"
Content # is used to replace "src". You can specify the value of the file directly.
Dest # required, absolute path to the remote host to which the source files are copied
Backup # when the contents of the file are changed, back up the source file before overwriting. The backup file contains time information
Directory_mode # Recursively sets the permissions of the directory, which defaults to the default permissions of the system
Force # when the target host contains the file, but the content is different, it is set to "yes" to force overwriting, and set to "no" to indicate that the file does not exist at the target host before copying. Default is "yes"
The options in all others # file modules can be used here
Examples of usage are as follows:
① copy files:
[root@server] # ansible web-m copy-a 'src=~/hello dest=/data/hello'
192.168.10.10 | SUCCESS = > {
"changed": true
"checksum": "22596363b3de40b06f981fb85d82312e8c0ed511"
"dest": "/ data/hello"
"gid": 0
"group": "root"
"md5sum": "6f5902ac237024bdd0c176cb93063dc4"
"mode": "0644"
"owner": "root"
"size": 12
"src": "/ root/.ansible/tmp/ansible-tmp-1512437093.55-228281064292921/source"
"state": "file"
"uid": 0
}
192.168.10.20 | SUCCESS = > {
"changed": true
"checksum": "22596363b3de40b06f981fb85d82312e8c0ed511"
"dest": "/ data/hello"
"gid": 0
"group": "root"
"md5sum": "6f5902ac237024bdd0c176cb93063dc4"
"mode": "0644"
"owner": "root"
"size": 12
"src": "/ root/.ansible/tmp/ansible-tmp-1512437093.74-44694985235189/source"
"state": "file"
"uid": 0
}
② generates files for given content and establishes permissions
[root@server] # ansible web-m copy-a 'content= "I am keer\ n" dest=/data/name mode=666'
192.168.10.10 | SUCCESS = > {
"changed": true
"checksum": "0421570938940ea784f9d8598dab87f07685b968"
"dest": "/ data/name"
"gid": 0
"group": "root"
"md5sum": "497fa8386590a5fc89090725b07f175c"
"mode": "0666"
"owner": "root"
"size": 10
"src": "/ root/.ansible/tmp/ansible-tmp-1512437327.37-199512601767687/source"
"state": "file"
"uid": 0
}
192.168.10.20 | SUCCESS = > {
"changed": true
"checksum": "0421570938940ea784f9d8598dab87f07685b968"
"dest": "/ data/name"
"gid": 0
"group": "root"
"md5sum": "497fa8386590a5fc89090725b07f175c"
"mode": "0666"
"owner": "root"
"size": 10
"src": "/ root/.ansible/tmp/ansible-tmp-1512437327.55-218104039503110/source"
"state": "file"
"uid": 0
}
We can now take a look at the files we generated and their permissions:
[root@server] # ansible web-m shell-a'ls-l / data/'
192.168.10.10 | SUCCESS | rc=0 > >
Total 28
-rw-rw-rw- 1 root root 12 Dec 6 09:45 name
192.168.10.20 | SUCCESS | rc=0 > >
Total 40
-rw-rw-rw- 1 root root 12 Dec 5 09:45 name
You can see that our name file has been generated with permissions of 666.
③ about overlay
We modify the contents of the file, and then choose to overwrite the backup:
[root@server] # ansible web-m copy-a 'content= "I am keerya\ n" backup=yes dest=/data/name mode=666'
192.168.10.10 | SUCCESS = > {
"backup_file": "/ data/name.4394.2017-12-06mm 09purl 46purl 25 ~"
"changed": true
"checksum": "064a68908ab9971ee85dbc08ea038387598e3778"
"dest": "/ data/name"
"gid": 0
"group": "root"
"md5sum": "8ca7c11385856155af52e560f608891c"
"mode": "0666"
"owner": "root"
"size": 12
"src": "/ root/.ansible/tmp/ansible-tmp-1512438383.78-228128616784888/source"
"state": "file"
"uid": 0
}
192.168.10.20 | SUCCESS = > {
"backup_file": "/ data/name.5962.2017-12-05mm 09purl 46purl 24~"
"changed": true
"checksum": "064a68908ab9971ee85dbc08ea038387598e3778"
"dest": "/ data/name"
"gid": 0
"group": "root"
"md5sum": "8ca7c11385856155af52e560f608891c"
"mode": "0666"
"owner": "root"
"size": 12
"src": "/ root/.ansible/tmp/ansible-tmp-1512438384.0-170718946740009/source"
"state": "file"
"uid": 0
}
Now we can check it out:
[root@server] # ansible web-m shell-a'ls-l / data/'
192.168.10.10 | SUCCESS | rc=0 > >
Total 28
-rw-rw-rw- 1 root root 12 Dec 6 09:46 name
-rw-rw-rw- 1 root root 10 Dec 6 09:45 name.4394.2017-12-0634 09purl 4615 ~
192.168.10.20 | SUCCESS | rc=0 > >
Total 40
-rw-rw-rw- 1 root root 12 Dec 5 09:46 name
-rw-rw-rw- 1 root root 10 Dec 5 09:45 name.5962.2017-12-0554 09 purl 46purl 24 ~
You can see that our source files have been backed up, and we can also take a look at the contents of the name file:
[root@server] # ansible web-m shell-a 'cat / data/name'
192.168.10.10 | SUCCESS | rc=0 > >
I am keerya
192.168.10.20 | SUCCESS | rc=0 > >
I am keerya
It proves that this is the content of our newly imported file.
5) file module
This module is mainly used to set the properties of files, such as creating files, creating linked files, deleting files, and so on.
Here are some common commands:
Force # needs to force the creation of soft links in two cases, one is that the source file does not exist but will be established later, and the other is that the destination soft link already exists and you need to cancel the previous soft link and then create a new soft link. There are two options: yes | no
Group # defines the group of files / directories. You can add mode: define the permissions of the file / directory
Owner # defines the owner of the file / directory Must be followed by path: define the path to the file / directory
Recurse # Recursively sets the properties of the file, which is valid only for directories, followed by src: the path to the linked source file, which applies only to state=link
The path to which dest # is linked, only in the case of state=link
State # status, with the following options:
Directory: if the directory does not exist, create the directory
File: even if the file does not exist, it will not be created
Link: creating soft links
Hard: creating hard links
Touch: if the file does not exist, a new file is created, and if the file or directory already exists, its last modification time is updated
Absent: delete directories, files, or unlink files
Examples of usage are as follows:
① create directory:
[root@server] # ansible web-m file-a 'path=/data/app state=directory'
192.168.10.10 | SUCCESS = > {
"changed": true
"gid": 0
"group": "root"
"mode": "0755"
"owner": "root"
"path": "/ data/app"
"size": 6
"state": "directory"
"uid": 0
}
192.168.10.20 | SUCCESS = > {
"changed": true
"gid": 0
"group": "root"
"mode": "0755"
"owner": "root"
"path": "/ data/app"
"size": 4096
"state": "directory"
"uid": 0
}
We can check it out:
[root@server] # ansible web-m shell-a'ls-l / data'
192.168.10.10 | SUCCESS | rc=0 > >
Total 28
Drwxr-xr-x 2 root root 6 Dec 6 10:21 app
192.168.10.20 | SUCCESS | rc=0 > >
Total 44
Drwxr-xr-x 2 root root 4096 Dec 5 10:21 app
As you can see, our directory has been created.
② creates a linked file
[root@server] # ansible web-m file-a 'path=/data/bbb.jpg src=aaa.jpg state=link'
192.168.10.10 | SUCCESS = > {
"changed": true
"dest": "/ data/bbb.jpg"
"gid": 0
"group": "root"
"mode": "0777"
"owner": "root"
"size": 7
"src": "aaa.jpg"
"state": "link"
"uid": 0
}
192.168.10.20 | SUCCESS = > {
"changed": true
"dest": "/ data/bbb.jpg"
"gid": 0
"group": "root"
"mode": "0777"
"owner": "root"
"size": 7
"src": "aaa.jpg"
"state": "link"
"uid": 0
}
We can check it out:
[root@server] # ansible web-m shell-a'ls-l / data'
192.168.10.10 | SUCCESS | rc=0 > >
Total 28
-rw-r--r-- 1 root root 5649 Dec 5 13:49 aaa.jpg
Lrwxrwxrwx 1 root root 7 Dec 6 10:25 bbb.jpg-> aaa.jpg
192.168.10.20 | SUCCESS | rc=0 > >
Total 44
-rw-r--r-- 1 root root 5649 Dec 4 14:44 aaa.jpg
Lrwxrwxrwx 1 root root 7 Dec 5 10:25 bbb.jpg-> aaa.jpg
Our link file has been created successfully.
③ deletes a file
[root@server] # ansible web-m file-a 'path=/data/a state=absent'
192.168.10.10 | SUCCESS = > {
"changed": true
"path": "/ data/a"
"state": "absent"
}
192.168.10.20 | SUCCESS = > {
"changed": true
"path": "/ data/a"
"state": "absent"
}
We can check it out:
[root@server] # ansible web-m shell-a'ls / data/a'
192.168.10.10 | FAILED | rc=2 > >
Ls: cannot access / data/a: No such file or directory
192.168.10.20 | FAILED | rc=2 > >
Ls: cannot access / data/a: No such file or directory
It was found that the file was no longer available.
6) fetch module
This module is used to obtain (copy) files from a remote host to the local.
There are two options:
Dest: the directory used to store files
Src: a file pulled remotely and must be a file, not a directory
Specific examples are as follows:
[root@server] # ansible web-m fetch-a 'src=/data/hello dest=/data'
192.168.10.10 | SUCCESS = > {
"changed": true
"checksum": "22596363b3de40b06f981fb85d82312e8c0ed511"
"dest": "/ data/192.168.10.10/data/hello"
"md5sum": "6f5902ac237024bdd0c176cb93063dc4"
"remote_checksum": "22596363b3de40b06f981fb85d82312e8c0ed511"
"remote_md5sum": null
}
192.168.10.20 | SUCCESS = > {
"changed": true
"checksum": "22596363b3de40b06f981fb85d82312e8c0ed511"
"dest": "/ data/192.168.10.20/data/hello"
"md5sum": "6f5902ac237024bdd0c176cb93063dc4"
"remote_checksum": "22596363b3de40b06f981fb85d82312e8c0ed511"
"remote_md5sum": null
}
We can check whether the file has been copied successfully on this machine. Note that the path to save the file is under the ip directory of the controlled host under the receive directory we set:
[root@server ~] # cd / data/
[root@server data] # ls
1 192.168.10.10 192.168.10.20 fastdfs web
[root@server data] # cd 192.168.10.10
[root@server 192.168.10.10] # ls
Data
[root@server 192.168.10.10] # cd data/
[root@server data] # ls
Hello
[root@server data] # pwd
/ data/192.168.10.10/data
7) cron module
This module is suitable for managing cron scheduled tasks.
It uses the same syntax as in our crontab file, and you can specify the following options:
Work that should be run on day= # (1-31, / 2,)
Hour= # hours (0-23, / 2,)
Minute= # minutes (0-59, / 2,)
Month= June (1-12, *, / 2,)
Weekday= # weeks (0-6 for Sunday-Saturday,)
Job= # indicates what command to run
Name= # scheduled task description
Reboot # task runs on restart and is not recommended. It is recommended to use special_time
Special_time # Special time range, parameters: reboot (on restart), annually (annually), monthly (monthly), weekly (weekly), daily (daily), hourly (hourly)
State # specifies the status. Present means to add a scheduled task, which is also the default setting. Absent means to delete a scheduled task.
User # as which user to execute
Examples are as follows:
① add scheduled tasks
[root@server ~] # ansible web-m cron-a 'name= "ntp update every 5 min" minute=*/5 job= "/ sbin/ntpdate 172.17.0.1 & > / dev/null"'
192.168.10.10 | SUCCESS = > {
"changed": true
"envs": []
"jobs": [
"ntp update every 5 min"
]
}
192.168.10.20 | SUCCESS = > {
"changed": true
"envs": []
"jobs": [
"ntp update every 5 min"
]
}
We can check it out:
[root@server] # ansible web-m shell-a 'crontab-l'
192.168.10.10 | SUCCESS | rc=0 > >
# Ansible: ntp update every 5 min
/ 5 * / sbin/ntpdate 172.17.0.1 & > / dev/null
192.168.10.20 | SUCCESS | rc=0 > >
# Ansible: ntp update every 5 min
/ 5 * / sbin/ntpdate 172.17.0.1 & > / dev/null
It can be seen that our planned task has been set up successfully.
② deletes scheduled tasks
If we add an error to our scheduled task and want to delete it, do the following:
First, let's take a look at the existing planned tasks:
[root@server] # ansible web-m shell-a 'crontab-l'
192.168.10.10 | SUCCESS | rc=0 > >
# Ansible: ntp update every 5 min
/ 5 * / sbin/ntpdate 172.17.0.1 & > / dev/null
# Ansible: df everyday
15 * df-lh > > / tmp/disk_total & > / dev/null
192.168.10.20 | SUCCESS | rc=0 > >
# Ansible: ntp update every 5 min
/ 5 * / sbin/ntpdate 172.17.0.1 & > / dev/null
# Ansible: df everyday
15 * df-lh > > / tmp/disk_total & > / dev/null
Then perform the delete operation:
[root@server] # ansible web-m cron-a 'name= "df everyday" hour=15 job= "df-lh > > / tmp/disk_total & > / dev/null" state=absent'
192.168.10.10 | SUCCESS = > {
"changed": true
"envs": []
"jobs": [
"ntp update every 5 min"
]
}
192.168.10.20 | SUCCESS = > {
"changed": true
"envs": []
"jobs": [
"ntp update every 5 min"
]
}
After the deletion is complete, let's take a look at the existing scheduled tasks to confirm:
[root@server] # ansible web-m shell-a 'crontab-l'
192.168.10.10 | SUCCESS | rc=0 > >
# Ansible: ntp update every 5 min
/ 5 * / sbin/ntpdate 172.17.0.1 & > / dev/null
192.168.10.20 | SUCCESS | rc=0 > >
# Ansible: ntp update every 5 min
/ 5 * / sbin/ntpdate 172.17.0.1 & > / dev/null
Our delete operation has been successful.
8) yum module
As the name implies, this module is mainly used for the installation of software.
The options are as follows:
The name of the package installed in name= #
State= # present--- > install, latest--- > install the latest, absent--- > uninstall the software.
Update_cache # forces yum's cache to be updated
Conf_file # specifies the configuration file that the remote yum installation depends on (installing packages that already exist locally).
Whether disable_pgp_check # disables GPG checking, only for presentor latest.
Disablerepo # temporarily prohibits the use of the yum library. Used only when installing or updating.
Enablerepo # temporary yum library. Used only when installing or updating.
Let's try to install a package:
[root@server] # ansible web-m yum-a 'name=htop state=present'
192.168.10.10 | SUCCESS = > {
"changed": true
"msg":
"rc": 0
"results": [
"Loaded plugins: fastestmirror Langpacks\ nLoading mirror speeds from cached hostfile\ nResolving Dependencies\ nMuyashi-> Running transaction check\ nMuyashi-> Package htop.x86_64 0VOV 2.0.2-1.el7 will be installed\ nWhich-> Finished Dependency Resolution\ n\ nDependencies Resolved\ n\ nMr. 1.el7 epel:\ nInstalling:\ nhtop x86 * 64 2.0.2-1.el7 epel 98 k\ n\ nTransaction Summary\ nMurray =\ nInstall 1 Package\ n\ nTotal download size: 98k\ nInstalled size: 207k\ nDownloading Packages:\ nRunning transaction check\ nRunning transaction test\ nTransaction test succeeded\ nRunning transaction\ nInstalling: htop-2.0.2-1.el7.x86_64 1 Verifying: htop-2.0.2-1.el7.x86_64 1 nInstalled:\ n\ nInstalled:\ n htop.x86_64 0VX 2.0.2-1.el7\ n\ nComplete!\ n "
]
}
192.168.10.20 | SUCCESS = > {
"changed": true
"msg": "Warning: RPMDB altered outside of yum.\ nThe * Found 3 pre-existing rpmdb problem (s) 'yum check' output follows:\ nipa-client-4.4.0-12.el7.centos.x86_64 has installed conflicts freeipa-client: ipa-client-4.4.0-12.el7.centos.x86_64\ nipa-client-common-4.4.0-12.el7.centos.noarch has installed conflicts freeipa-client-common: ipa-client-common-4.4.0-12.el7.centos.noarch\ nipa-common-4.4.0-12.el7.centos.noarch Has installed conflicts freeipa-common: ipa-common-4.4.0-12.el7.centos.noarch\ n "
"rc": 0
"results": [
"Loaded plugins: fastestmirror Langpacks\ nLoading mirror speeds from cached hostfile\ nResolving Dependencies\ nMuyashi-> Running transaction check\ nMuyashi-> Package htop.x86_64 0VOV 2.0.2-1.el7 will be installed\ nWhich-> Finished Dependency Resolution\ n\ nDependencies Resolved\ n\ nMr. 1.el7 epel:\ nInstalling:\ nhtop x86 * 64 2.0.2-1.el7 epel 98 k\ n\ nTransaction Summary\ nMurray =\ nInstall 1 Package\ n\ nTotal download size: 98k\ nInstalled size: 207k\ nDownloading Packages:\ nRunning transaction check\ nRunning transaction test\ nTransaction test succeeded\ nRunning transaction\ nInstalling: htop-2.0.2-1.el7.x86_64 1 Verifying: htop-2.0.2-1.el7.x86_64 1 nInstalled:\ n\ nInstalled:\ n htop.x86_64 0VX 2.0.2-1.el7\ n\ nComplete!\ n "
]
}
Installation succeeded.
9) service module
This module is used for the management of service programs.
The main options are as follows:
The arguments # command line provides additional parameters
Enabled # sets boot up.
Name= # Service name
The boot level of runlevel # is generally not specified.
Sleep # whether to wait while restarting the service. For example, wait 2 seconds after the service is turned off before starting. (defined in the script.)
State # has four states: started--- > start service, stopped--- > stop service, restarted--- > restart service, reloaded--- > reload configuration
Here are some examples:
① starts the service and sets self-startup
[root@server] # ansible web-m service-a 'name=nginx state=started enabled=true'
192.168.10.10 | SUCCESS = > {
"changed": true
"enabled": true
"name": "nginx"
"state": "started"
……
}
192.168.10.20 | SUCCESS = > {
"changed": true
"enabled": true
"name": "nginx"
"state": "started"
……
}
We can check to see if the port is open:
[root@server] # ansible web-m shell-a'ss-ntl'
192.168.10.10 | SUCCESS | rc=0 > >
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128: 80: *
192.168.10.20 | SUCCESS | rc=0 > >
State Recv-Q Send-Q Local Address:Port Peer Address:Port
LISTEN 0 128: 80: *
It can be seen that our port 80 has been opened.
② shuts down the service
We can also use this module to shut down our services:
[root@server] # ansible web-m service-a 'name=nginx state=stopped'
192.168.10.10 | SUCCESS = > {
"changed": true
"name": "nginx"
"state": "stopped"
……
}
192.168.10.20 | SUCCESS = > {
"changed": true
"name": "nginx"
"state": "stopped"
……
}
Again, let's check the port:
[root@server ~] # ansible web-m shell-a'ss-ntl | grep 80'
192.168.10.10 | FAILED | rc=1 > >
192.168.10.20 | FAILED | rc=1 > >
As you can see, we no longer have port 80, which means that our nginx service has been shut down.
10) user module
This module is mainly used to manage user accounts.
The main options are as follows:
Comment # user description information
Createhome # whether to create a home directory
Force # behaves in the same way as userdel-force when using state=absent.
Group # specify the basic group
Groups # specifies additional groups. If specified as (groups=), all groups are deleted.
Home # specify the user's home directory
Move_home # if set to home=, attempt to move the user's home directory to the specified directory
Name # specify user name
Non_unique # this option allows you to change non-unique user ID values
Password # specify user password
Remove # behaves in the same way as userdel-remove when using state=absent
Shell # specifies the default shell
State # sets the account status. It is not specified as creation, and specified as absent indicates deletion
System # when creating a user, set the user to be the system user. This setting cannot change existing users
Uid # specify the uid of the user
Examples are as follows:
① add a user and specify its uid
[root@server] # ansible web-m user-a 'name=keer uid=11111'
192.168.10.10 | SUCCESS = > {
"changed": true
"comment":
"createhome": true
"group": 11111
"home": "/ home/keer"
"name": "keer"
"shell": "/ bin/bash"
"state": "present"
"stderr": "useradd: warning: the home directory already exists.\ nNot copying any file from skel directory into it.\ nCreating mailbox file: File exists\ n"
"system": false
"uid": 11111
}
192.168.10.20 | SUCCESS = > {
"changed": true
"comment":
"createhome": true
"group": 11111
"home": "/ home/keer"
"name": "keer"
"shell": "/ bin/bash"
"state": "present"
"stderr": "useradd: warning: the home directory already exists.\ nNot copying any file from skel directory into it.\ nCreating mailbox file: File exists\ n"
"system": false
"uid": 11111
}
After adding, we can check it out:
[root@server ~] # ansible web-m shell-a 'cat / etc/passwd | grep keer'
192.168.10.10 | SUCCESS | rc=0 > >
Keer:x:11111:11111::/home/keer:/bin/bash
192.168.10.20 | SUCCESS | rc=0 > >
Keer:x:11111:11111::/home/keer:/bin/bash
② Delete user
[root@server] # ansible web-m user-a 'name=keer state=absent'
192.168.10.10 | SUCCESS = > {
"changed": true
"force": false
"name": "keer"
"remove": false
"state": "absent"
}
192.168.10.20 | SUCCESS = > {
"changed": true
"force": false
"name": "keer"
"remove": false
"state": "absent"
}
Again, after deletion, let's take a look:
[root@server ~] # ansible web-m shell-a 'cat / etc/passwd | grep keer'
192.168.10.10 | FAILED | rc=1 > >
192.168.10.20 | FAILED | rc=1 > >
It is found that this user is no longer available.
11) group module
This module is mainly used to add or delete groups.
Common options are as follows:
Gid= # set the GID number of the group
Name= # specify the name of the group
State= # specifies the status of the group. The default is create, and the value is absent to delete.
System= # sets the value to yes, which means that it is created as a system group
Examples are as follows:
① create Group
[root@server] # ansible web-m group-a 'name=sanguo gid=12222'
192.168.10.10 | SUCCESS = > {
"changed": true
"gid": 12222
"name": "sanguo"
"state": "present"
"system": false
}
192.168.10.20 | SUCCESS = > {
"changed": true
"gid": 12222
"name": "sanguo"
"state": "present"
"system": false
}
After creating it, let's take a look at:
[root@server ~] # ansible web-m shell-a 'cat / etc/group | grep 12222'
192.168.10.10 | SUCCESS | rc=0 > >
Sanguo:x:12222:
192.168.10.20 | SUCCESS | rc=0 > >
Sanguo:x:12222:
As you can see, our group has been created successfully.
② delete group
[root@server] # ansible web-m group-a 'name=sanguo state=absent'
192.168.10.10 | SUCCESS = > {
"changed": true
"name": "sanguo"
"state": "absent"
}
192.168.10.20 | SUCCESS = > {
"changed": true
"name": "sanguo"
"state": "absent"
}
Check it out as usual:
[root@server ~] # ansible web-m shell-a 'cat / etc/group | grep 12222'
192.168.10.10 | FAILED | rc=1 > >
192.168.10.20 | FAILED | rc=1 > >
There is no information about this group.
12) script module
This module is used to run local scripts on the machine under management.
The module can directly specify the path of the script. Let's take a look at how to use it through an example:
First, let's write a script and give it execution permission:
[root@server ~] # vim / tmp/df.sh
#! / bin/bash
Date > > / tmp/disk_total.logdf-lh > > / tmp/disk_total.log
[root@server ~] # chmod + x / tmp/df.sh
Then we run the command directly to execute the script on the managed side:
[root@server] # ansible web-m script-a'/ tmp/df.sh'
192.168.10.10 | SUCCESS = > {
"changed": true
"rc": 0
"stderr": "Shared connection to 192.168.10.10 closed.\ r\ n"
"stdout":
"stdout_lines": []
}
192.168.10.20 | SUCCESS = > {
"changed": true
"rc": 0
"stderr": "Shared connection to 192.168.10.20 closed.\ r\ n"
"stdout":
"stdout_lines": []
}
Take a look at the contents of the file as usual:
[root@server] # ansible web-m shell-a 'cat / tmp/disk_total.log'
192.168.10.10 | SUCCESS | rc=0 > >
Tue Dec 5 15:58:21 CST 2017
Filesystem Size Used Avail Use% Mounted on
/ dev/sda2 47G 4.4G 43G 10% /
Devtmpfs 978M 0978M 0% / dev
Tmpfs 993M 84K 993m 1% / dev/shm
Tmpfs 993m 9.1m 984m 1% / run
Tmpfs 993M 0 993M 0% / sys/fs/cgroup
/ dev/sda3 47G 33m 47G 1% / app
/ dev/sda1 950M 153M 798M 17% / boot
Tmpfs 199m 16K 199m 1% / run/user/42
Tmpfs 199m 0 199m 0% / run/user/0
192.168.10.20 | SUCCESS | rc=0 > >
Tue Dec 5 15:58:21 CST 2017
Filesystem Size Used Avail Use% Mounted on
/ dev/sda2 46G 4.1G 40G 10% /
Devtmpfs 898M 0898M 0% / dev
Tmpfs 912M 84K 912m 1% / dev/shm
Tmpfs 912m 9.0m 903m 1% / run
Tmpfs 912M 0912m 0% / sys/fs/cgroup
/ dev/sda3 3.7G 15m 3.4G 1% / app
/ dev/sda1 1.9G 141m 1.6G 9 per cent / boot
Tmpfs 183M 16K 183M 1% / run/user/42
Tmpfs 183M 0 183M 0% / run/user/0
It can be seen that the implementation has been successful.
13) setup module
This module is mainly used to collect information and is implemented by calling facts components.
Facts component is a function of Ansible to collect managed machine equipment information. We can use the setup module to check all the facts information of the machine, and we can use filter to view the specified information. The whole facts information is wrapped in a data structure in JSON format, and ansible_facts is the top value.
Facts is a variable, built-in variable. All kinds of information about each host, such as the number of cpu, memory size, etc. Will exist in one of the variables in facts. After the call, a lot of information about the corresponding host is returned, and different operations can be done according to different information in the following operations. For example, the redhat series uses yum to install, while the debian series uses apt to install software.
① View Information
We can get the value of the variable directly with the command, let's take a look at the example:
[root@server ~] # ansible web-m setup-a 'filter= "mem"' # View memory
192.168.10.10 | SUCCESS = > {
"ansible_facts": {
"ansible_memfree_mb": 1116
"ansible_memory_mb": {
"nocache": {
"free": 1397
"used": 587
}
"real": {
"free": 1116
"total": 1984
Used: 868
}
"swap": {
"cached": 0
"free": 3813
"total": 3813
"used": 0
}
}
"ansible_memtotal_mb": 1984
}
"changed": false
}
192.168.10.20 | SUCCESS = > {
"ansible_facts": {
"ansible_memfree_mb": 1203
"ansible_memory_mb": {
"nocache": {
"free": 1470
"used": 353
}
"real": {
"free": 1203
"total": 1823
"used": 620
}
"swap": {
"cached": 0
"free": 3813
"total": 3813
"used": 0
}
}
"ansible_memtotal_mb": 1823
}
"changed": false
}
We can check the size of the memory with the command to see if it is consistent:
[root@server] # ansible web-m shell-a 'free-m'
192.168.10.10 | SUCCESS | rc=0 > >
Total used free shared buff/cache available
Mem: 1984 404 1122 9 457 1346
Swap: 3813 0 3813
192.168.10.20 | SUCCESS | rc=0 > >
Total used free shared buff/cache available
Mem: 1823 292 1207 9 323 1351
Swap: 3813 0 3813
It can be seen that the information is consistent.
② saves information
Another useful feature of our setup module is that it can save our filtered information to our host, and the file name is the IP of our regulated host, which makes it easy for us to know which machine is the problem.
Let's take a look at an example:
[root@server tmp] # ansible web-m setup-a 'filter= "mem"-- tree / tmp/facts
192.168.10.10 | SUCCESS = > {
"ansible_facts": {
"ansible_memfree_mb": 1115
"ansible_memory_mb": {
"nocache": {
"free": 1396
Used: 588
}
"real": {
"free": 1115
"total": 1984
Used: 869
}
"swap": {
"cached": 0
"free": 3813
"total": 3813
"used": 0
}
}
"ansible_memtotal_mb": 1984
}
"changed": false
}
192.168.10.20 | SUCCESS = > {
"ansible_facts": {
"ansible_memfree_mb": 1199
"ansible_memory_mb": {
"nocache": {
"free": 1467
Used: 356
}
"real": {
"free": 1199
"total": 1823
Used: 624
}
"swap": {
"cached": 0
"free": 3813
"total": 3813
"used": 0
}
}
"ansible_memtotal_mb": 1823
}
"changed": false
}
Then we can check it out:
[root@server ~] # cd / tmp/facts/
[root@server facts] # ls
192.168.10.10 192.168.10.20
[root@server facts] # cat 192.168.10.10
{"ansible_facts": {"ansible_memfree_mb": 1115, "ansible_memory_mb": {"nocache": {"free": 1396, "used": 588}, "real": {"free": 1115, "total": 1984, "used": 1984}, "swap": {"cached": 0, "free": 3813, "total": 3813, "used": 0}, "ansible_memtotal_mb": 1984} "changed": false}
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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.