ansible entry (a)

A, ansible Profile

ansible is a Python module development paramiko operation and maintenance of automation tools to achieve batch system configuration, batch deployment, command and other functions based on batch run.
ansible not need to install client / agents on the remote host, since it is based on ssh to the remote host and communication.

1.1 ansible properties

  1. Easy to deploy, simply deploy Ansible environment in master, host not need to do anything;
  2. The default SSH protocol using the device management;
  3. A large number of routine operation and maintenance operations module, enabling most of the daily operations;
  4. API support and custom modules can be easily extended by Python;
  5. Write Playbooks to implement a host of commonly used multi-task operation;

1.2 ansible Chart

It does not have the ability to batch management, batch management is truly module ansible running, ansible only provides a framework.
Here Insert Picture Description

  1. Ansible : ansible core connection plugins: plug connection, accountable and monitored end for communication;
  2. For Inventory, Host : Host list is a configuration file; the definition of managed hosts inside. Including host IP, ssh port, account and password; managed hosts may be grouped in a file.
  3. Modules Core : mainly used for a variety of administrative tasks batch
  4. Odules Custom : develop their own core modules feature additions
  5. Playbooks : in the configuration file (written yaml file format), allowing multiple users to perform multiple tasks
  6. Plugins : logging messages by means of the plug is completed and other functions;

1.3 ansible task execution

There are two modes ansible task execution
ad-hoc模式
to use a single module, it is a way to quickly enter the command, without having to save the equivalent of the word shell bash,
playbook模式
subject to prior written yaml file as a script, a collection of multiple tasks in yaml file task invoke multiple modules.

1.4 ansible execution process

  1. Load your own configuration file, the default /etc/ansible/ansible.cfg;
  2. Find the corresponding host configuration file, find the host to the remote execution or group;
  3. Load module file corresponding to itself, such as Command;
  4. Or by ansible command generation module corresponding to py temporary files (Python script), and transfer the file to the remote server;
  5. Corresponding to the execution of the user's home directory .ansible / tmp / XXX / XXX.PY file;
  6. + X execute permissions to the file;
  7. Execution and returns the result; py delete temporary files, sleep 0 exit;

Two, ansible configuration in detail

Recommended epel source yum install

yum install epel-release -y
yum install ansible –y

2.1 configuration files Introduction

/etc/ansible/ansible.cfg
Is ansible main configuration file, the following describes the common configuration parameters

inventory = /etc/ansible/hosts      #这个参数表示资源清单inventory文件(即主机清单)的位置
library = /usr/share/ansible        #指向存放Ansible模块的目录,支持多个目录方式,只要用冒号(:)隔开就可以
forks = 5      #并发操作远程主机的连接数,默认为5
sudo_user = root        #设置默认执行命令的用户
remote_port = 22        #指定连接远程主机的管理端口,默认为22端口,建议修改,能够更加安全
host_key_checking = False       #设置是否检查SSH主机的密钥,值为True/False。关闭后第一次连接不会提示配置实例
timeout = 60        #设置SSH连接的超时时间,单位为秒
log_path = /var/log/ansible.log     #指定一个存储ansible日志的文件(默认不记录日志)

/etc/ansible/hosts
Host configuration settings from the main list of files, you can set the IP address or host name of the remote host in the file, the host group, host ansible set parameters and specific variables.

Host group

[apps]
192.168.80.111
192.168.80.120

[webservers]
www[01:50].jintian.com

[databases]
db-[a:f].jintian.com

#上面指定了从web1到web50,webservers主机组共计50台主机;databases主机组有db-a到db-f共6台主机。

Ansible parameters host
after the host address space to fill out a host cell parameters as common parameters

ansible_ssh_port     
#用于指定连接到被管理主机的ssh端口号,默认是22 

ansible_ssh_user     
#ssh连接时默认使用的用户名 

ansible_ssh_pass     
#ssh连接时的密码 

ansible_sudo_pass     
#使用sudo连接用户时的密码 

ansible_sudo_exec     
#如果sudo命令不在默认路径,需要指定sudo命令路径 

ansible_ssh_private_key_file     
#秘钥文件路径,秘钥文件如果不想使用ssh-agent管理时可以使用此选项 

ansible_shell_type     
#目标系统的shell的类型,默认sh 

ansible_connection     
#SSH 连接的类型: local , ssh , paramiko,在 ansible 1.2 之前默认是 paramiko ,后来智能选择,优先使用基于 ControlPersist 的 ssh (支持的前提) 

Three, ansible series of command

3.1 ansible-doc command

ansible-doc command used to obtain information and how to use help module, generally used as follows:

ansible-doc -l              #获取全部模块的信息
ansible-doc -s MOD_NAME     #获取指定模块的使用帮助

3.2 ansible command

格式:ansible [-f forks] [-m module_name] [-a args]

Host-pattern
Which hosts perform the operation specified; multiple names separated by commas; all means all hosts / etc / ansible / hosts file; the group name in the file, the server name can be called.

-f forks: Forks numerical value indicating how many hosts to complete a batch of operation
-m module: module is the module name, indicating which module to use the ansible
-a args: args parameter specific module, args citation format: key = value; call command module shell and when, args directly fill system commands.

-uSpecifies which user remote host, the default is root
-kto complete the ssh connection authentication password, the absence of dense-free certification
-bspecified remote host using sudo to which users run, the default root
-Kpassword authentication input of the remote host sudo

3.3 ansible common module

ping the host communication tests

We use ansible web -m ping commands to the host communication tests, the following results:

[root@server ~]# ansible web -m ping
192.168.37.122 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.37.133 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

This shows that our host is communicating state. The following operations can be performed normally.

The default command module, used to execute commands

Execute commands directly on the remote host, and returns the results of this host

[root@server ~]# ansible web -a 'ss -ntl'
192.168.37.122 | SUCCESS | rc=0 >>
State      Recv-Q Send-Q Local Address:Port               Peer Address:Port                                        
LISTEN     0      128          *:22                       *:*                               
LISTEN     0      100    127.0.0.1:25                       *:*             
LISTEN     0      128         :::22                      :::*                           
LISTEN     0      100        ::1:25                      :::*                  

192.168.37.133 | SUCCESS | rc=0 >>
State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
LISTEN     0      128          *:22                       *:*                               
LISTEN     0      100    127.0.0.1:25                       *:*             
LISTEN     0      128         :::22                      :::*                           
LISTEN     0      100        ::1:25                      :::*  

注意Given command will be executed on all selected nodes. It is not processed by the shell, such as $ HOME variable references, and operations such as "<", ">", "|", ";", "&", etc., required to achieve these functions module shell.

Let's look at a few commonly used commands in this module:

chdir       # 在执行命令之前,先切换到该目录
executable # 切换shell来执行命令,需要使用命令的绝对路径
free_form   # 要执行的Linux指令,一般使用Ansible的-a参数代替。
creates  # 一个文件名,当这个文件存在,则该命令不执行,可以用来做判断
removes # 一个文件名,这个文件不存在,则该命令不执行

Let us look at the effect of the implementation of these commands:

[root@server ~]# ansible web -m command -a 'chdir=/data/ ls'    #先切换到/data/ 目录,再执行“ls”命令
192.168.37.122 | SUCCESS | rc=0 >>
aaa.jpg
wKgleloeYoCAMLtZAAAWEekAtkc497.jpg

192.168.37.133 | SUCCESS | rc=0 >>
aaa.jpg
wKgleloeYoCAMLtZAAAWEekAtkc497.jpg

[root@server ~]# ansible web -m command -a 'creates=/data/aaa.jpg ls'       #如果/data/aaa.jpg存在,则不执行“ls”命令
192.168.37.122 | SUCCESS | rc=0 >>
skipped, since /data/aaa.jpg exists

192.168.37.133 | SUCCESS | rc=0 >>
skipped, since /data/aaa.jpg exists

[root@server ~]# ansible web -m command -a 'removes=/data/aaa.jpg cat /data/a'      #如果/data/aaa.jpg存在,则执行“cat /data/a”命令
192.168.37.122 | SUCCESS | rc=0 >>
hello
192.168.37.133 | SUCCESS | rc=0 >>
hello

shell

shell module can be invoked on a remote host shell interpreter to run the command, shell support various functions, such as pipelines.

[root@server ~]# ansible web -m shell -a 'cat /etc/passwd |grep "keer"'
192.168.37.122 | SUCCESS | rc=0 >>
keer:x:10001:1000:keer:/home/keer:/bin/sh

192.168.37.133 | SUCCESS | rc=0 >>
keer:x:10001:10001::/home/keer:/bin/sh

注意1: Use the shell module, a remote command executed by / bin / sh; therefore, we are in a variety of command input terminals, can be used;
but we ourselves define the environment variable shell module .bashrc / .bash_profile in the absence of load , it is not recognized; if you need to use a custom environment variables, you need to at the very beginning, from the load statement defines scripts;
注意2: in -a "". If there is need $ escaped, but the playbook is not required. Example:
ansible All the shell -a -m "PS AUX | grep XX | awk '{} Print $ 2'

cron task allocation plan

Commonly used cron module args follows:

 - user			#指定执行该计划任务的用户 		
 - job			#指定计划任务要执行的命令 		
 - name			#为计划任务定义任务名
 - state		#指定计划任务的状态  
 - state=present#表示创建计划任务,默认为此操作
 - state=absent #表示取消计划任务
 - minute		#指定计划任务执行的时间(分) 		
 - hour			#指定计划任务执行的时间(小时)
 - day			#指定计划任务执行的时间(日期,号)
 - month		#指定计划任务执行的时间(日期,月份)
 - weekday		#指定计划任务执行的时间(周几)

If not set, it defaults to *.
Add Scheduled Task

[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.37.122 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "ntp update every 5 min"
    ]
}
192.168.37.133 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "ntp update every 5 min"
    ]
}

[root@server ~]# ansible web -m shell -a 'crontab -l'
192.168.37.122 | SUCCESS | rc=0 >>
#Ansible: ntp update every 5 min
*/5 * * * * /sbin/ntpdate 172.17.0.1 &> /dev/null

Delete Scheduled Tasks

[root@server ~]# ansible web -m cron -a 'name="ntp update every 5 min" state=absent'
192.168.37.122 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": []
}

Copy copy files to a remote host

agrs Copy module are commonly used

 - backup    # 是否让远程主机创建一个备份文件包括时间戳信息,如果重创错了,还可以拿回原始文件 取值yes或no
 - content   # 取代src=,表示直接用此处指定的信息生成为目标文件内容;
 - src       # 指定复制的源文件,可以是相对路径或者绝对路径, 如果给出的源是目录,那么会把目录下的所有都复制过去
 - dest      # 远程节点存放文件的路径,必须是绝对路径
 - force     # 如果目标主机已存在文件,内容不同,如设置为yes,则强制覆盖,如设置为no,则只有当目标主机的目标位置不存在该文件时,才复制。默认为yes 
 - group     # 复制到远程主机后,指定文件或目录的属组
 - owner     # 复制到远程主机后,指定文件或目录属主
 - mode      # 复制到远程主机后,指定文件或目录权限,类似与chmod命令 使用 644
 - directory_mode  # 递归复制,设置目录权限,默认为系统默认权限

Copy files

[root@server ~]# ansible web -m copy -a 'src=~/hello dest=/data/hello' 
192.168.37.122 | 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
}

Given the contents of the file is generated, and to develop rights

[root@server ~]# ansible web -m copy -a 'content="I am keer\n" dest=/data/name mode=666'
192.168.37.122 | 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
}
#我们现在可以去查看一下我们生成的文件及其权限:
[root@server ~]# ansible web -m shell -a 'ls -l /data/'
192.168.37.122 | SUCCESS | rc=0 >>
total 28
-rw-rw-rw-   1 root root   12 Dec  6 09:45 name

192.168.37.133 | SUCCESS | rc=0 >>
total 40
-rw-rw-rw- 1 root     root       12 Dec  5 09:45 name
#可以看出我们的name文件已经生成,并且权限为666。

Cover and back up files

[root@server ~]# ansible web -m copy -a 'content="I am keerya\n" backup=yes dest=/data/name mode=666'
192.168.37.122 | SUCCESS => {
    "backup_file": "/data/name.4394.2017-12-06@09:46: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
}
# 现在我们可以去查看一下:
[root@server ~]# ansible web -m shell -a 'ls -l /data/'
192.168.37.122 | 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-06@09:46:25~

File management on remote host file

args following common file module

 - path			#必选项,定义文件/目录的路径 
 - owner		#定义文件/目录的属主    
 - group		#定义文件/目录的属组    
 - mode		    #定义文件/目录的权限
 - recurse		#递归的设置文件的属性,只对目录有效
 - src			#要被链接的源文件路径,只应用于state=link的情况   
 - dest			#被链接到的路径,只应用于state=link的情况
 - state   #如下几种
              #directory:如果目录不存在,创建目录
              #file:即使文件不存在,也不会被创建
              #link:创建软链接
              #hard:创建硬链接
              #absent:删除目录、文件或者取消链接文件
              #touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间

Create a directory

[root@server ~]# ansible web -m file -a 'path=/data/app state=directory'
192.168.37.122 | SUCCESS => {
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0755", 
    "owner": "root", 
    "path": "/data/app", 
    "size": 6, 
    "state": "directory", 
    "uid": 0
}

Create a link file

[root@server ~]# ansible web -m file -a 'dest=/data/bbb.jpg src=aaa.jpg state=link'
192.168.37.122 | SUCCESS => {
    "changed": true, 
    "dest": "/data/bbb.jpg", 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "size": 7, 
    "src": "aaa.jpg", 
    "state": "link", 
    "uid": 0
}

Delete Files

[root@server ~]# ansible web -m file -a 'path=/data/a state=absent'
192.168.37.122 | SUCCESS => {
    "changed": true, 
    "path": "/data/a", 
    "state": "absent"
}

fetch copy files from a remote host to the local

Commonly used as args

 - dest  #用来存放文件的目录 
 - src   #在远程拉取的文件,并且必须是一个file,不能是目录

注意 Copy the files from the directory stored in the receiver we set in a directory name for the remote host ip in, for example

[root@server ~]# ansible web -m fetch -a 'src=/data/hello dest=/data'  
192.168.37.122 | SUCCESS => {
    "changed": true, 
    "checksum": "22596363b3de40b06f981fb85d82312e8c0ed511", 
    "dest": "/data/192.168.37.122/data/hello", 
    "md5sum": "6f5902ac237024bdd0c176cb93063dc4", 
    "remote_checksum": "22596363b3de40b06f981fb85d82312e8c0ed511", 
    "remote_md5sum": null
}

[root@server ~]# cd /data/
[root@server data]# ls
192.168.37.122
[root@server data]# cd 192.168.37.122
[root@server 192.168.37.122]# ls
data
[root@server 192.168.37.122]# ls data/
hello

yum yum package management remote host

Common parameters are as follows


 - name=  #需要yum管理的包名称 
 - state=  #present--->安装, latest--->安装最新的, absent--->卸载软件。 update_cache  #强制更新yum的缓存
 - conf_file  #指定远程主机yum安装时所依赖的配置文件(安装本地已有的包)。 
 - disable_pgp_check  #是否禁止GPGchecking,只用于presentor latest。 
 - disablerepo  #临时禁止使用yum库。 只用于安装或更新时。
 - enablerepo  #临时使用的yum库。只用于安装或更新时。

yum install htop

[root@server ~]# ansible web -m yum -a 'name=htop state=present'
192.168.37.122 | SUCCESS => {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror, langpacks\nLoading mirror speeds from cached hostfile\nResolving Dependencies\n--> Running transaction check\n---> Package htop.x86_64 0:2.0.2-1.el7 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package         Arch              Version                Repository       Size\n================================================================================\nInstalling:\n htop            x86_64            2.0.2-1.el7            epel             98 k\n\nTransaction Summary\n================================================================================\nInstall  1 Package\n\nTotal download size: 98 k\nInstalled size: 207 k\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : htop-2.0.2-1.el7.x86_64                                      1/1 \n  Verifying  : htop-2.0.2-1.el7.x86_64                                      1/1 \n\nInstalled:\n  htop.x86_64 0:2.0.2-1.el7                                                     \n\nComplete!\n"
    ]
}

systemd systemctl Manager Service

Common parameters are as follows:

 - name: #指定需要管理的服务名,例如crond.service,最好带上后缀.service
 - state: #需要的进行的管理操作,reloaded,restarted, started, stopped 
 - enabled:#指定的服务是否需要开机启动 
 - daemon_reload:#systemd读取配置文件,每次修改了文件,最好都运行一次,确保应用了

Close the application

[root@192-168-80-114 ~]# ansible 192.168.80.134 -m systemd -a "name=nginx state=stopped"
192.168.80.134 | SUCCESS => {
    "changed": true, 
    "name": "nginx", 
    "state": "stopped", 
    "status": {
        "ActiveEnterTimestamp": "四 2019-11-28 16:03:40 CST", 
        "ActiveEnterTimestampMonotonic": "13586518310507", 
        "ActiveExitTimestampMonotonic": "0", 
        "ActiveState": "active", 
        "After": "network.target systemd-journald.socket -.mount nss-lookup.target tmp.mount basic.target system.slice remote-fs.target"...

Copy the script to the script on the remote host, after the deletion

For example

[root@server ~]# vim /tmp/df.sh
    #!/bin/bash
    date >> /tmp/disk_total.log
[root@server ~]# ansible web -m script -a '/tmp/df.sh'
192.168.37.122 | SUCCESS => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.37.122 closed.\r\n", 
    "stdout": "", 
    "stdout_lines": []
}
[root@server ~]# ansible web -m shell -a 'cat /tmp/disk_total.log'
192.168.37.122 | SUCCESS | rc=0 >>
Tue Dec  5 15:58:21 CST 2017

unarchive remote host decompression

Common parameters are as follows

 - copy:  #默认为yes,当copy=yes,那么拷贝的文件是从ansible主机复制到远程主机上的,如果设置为copy=no,那么会在远程主机上寻找src源文件
 - src:   #源路径,可以是ansible主机上的路径,也可以是远程主机上的路径,如果是远程主机上的路径,则需要设置copy=no
 - dest:  #远程主机上的目标路径
 - mode:  #设置解压缩后的文件权限
Published 40 original articles · won praise 2 · Views 2049

Guess you like

Origin blog.csdn.net/weixin_42155272/article/details/103276717