Ansible automated installation and operation and maintenance of the common interpretation module

(I. Introduction:

Ansible is this year more and more fire operation and maintenance of an open source automation tools, operation and maintenance of automation can be achieved by Ansible, operation and maintenance engineers to improve efficiency, reduce human error. Ansible can achieve a variety of administrative tasks by itself is very rich integrated module, the module that comes with more than a thousand. More importantly, it is simple, but offers functionality and very rich, operation and maintenance in the field, can do almost anything.

Ansible since 2012 published soon in the global epidemic, which is characterized as follows:

  • Ansible Python-based development, operation and maintenance engineers for its second development is relatively easy;
  • Ansible a wealth of built-in modules, meet almost all the requirements;
  • Management is very simple, a command can affect thousands of hosts;
  • No client mode, communication via SSH bottom;

Ansible working set:
Ansible working set contains inventory, Modules, Plugins and API, which, inventory (inventory) used to manage the list of devices can be achieved by grouping, calling all hosts in the group a direct impact on the group; modules that perform a variety of module, almost all administrative tasks are performed by the module; plugins provide a variety of additional functions; API provides an interface for the programmer, you can do this based on secondary development Ansible.

Ansible can be controlled and changes to multiple hosts through a single command or configuration file from the following installation and configuration in order to write about.

(Ii) Ansible Installation and Configuration

The environment by a simple configuration and installation Ansible written down, the environment is as follows:
Ansible automated installation and operation and maintenance of the common interpretation module

The final result: may be controlled by the server 1 and server 2 Ansible server.

First, the pre-deployment work:

1, the use of local yum repository installed, download my offer local yum repository , extraction code: buqy, I offer a Ansible 2.3.1.0 version.
2, if the machine with Internet access, you can point directly to the warehouse yum Internet, you can install Ansible 2.4.xx version.
3, using the default TCP 22 were communicating with the client, subject to change, the need to set up a firewall on their own, I am here for the convenience, directly off the firewall.

Second, the installation Ansible (to choose one):

1, the use of the Internet yum repository installation:

[root@ansible ~]# yum clean all         #清除yum缓存
[root@ansible ~]# yum -y install ansible             #安装Ansible
[root@ansible ~]# ansible --version                  #可以查看到此信息,说明安装成功
ansible 2.4.2.0
  config file = /etc/ansible/ansible.cfg
         .............................

2, the use of local yum repository installation I offer:

[root@ansible yum.repos.d]# mount /dev/cdrom /media         #挂载我提供的ISO文件
mount: /dev/sr0 写保护,将以只读方式挂载
[root@ansible yum.repos.d]# cat /etc/yum.repos.d/a.repo       
#删除或移动原有yum配置文件,并编写本地yum文件:
[fd]
baseurl=file:///media
gpgcheck=0
[root@ansible yum.repos.d]# yum clean all          #清除yum缓存
[[email protected]]# yum -y install ansible             #安装Ansible
[root@ansible yum.repos.d]# ansible --version              #可以查看到此信息,说明安装成功
ansible 2.3.1.0
  config file = /etc/ansible/ansible.cfg
           .....................

I am here using the Internet to install yum repository that ansible 2.4.2.0.

Installation has been completed, but to normal use Ansible, also need to address a problem that multiple hosts in control, to execute a command or script each have to enter a password to end, then, it is very tasteless, so it SSH need to create free interactive logon, as follows:

The following operations are carried out in Ansible server:

[root@ansible ~]# ssh-keygen -t rsa             #在Ansible服务器生成密钥对,执行后默认一直按回车即可
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):         #默认按回车
Enter passphrase (empty for no passphrase):             #默认按回车
Enter same passphrase again:                        #默认按回车
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:                                           #默认按回车
SHA256:zhd2++KvByxFPE4ZKmDdmTHp6cjsuIEz5M26QrkBfes root@ansible
The key's randomart image is:                     #默认按回车
+---[RSA 2048]----+
|      o. .o*.o   |
|     . .. =o*    |
| .      ...= .   |
|. . .    .o o    |
| . o.. oSooo.    |
|  +o.+ o+.ooo.   |
| . += +oo ....   |
|  o E+....  ...  |
|   .o...   .o=o  |
+----[SHA256]-----+
#至此密钥对已经生成了,隐藏存在当前用户的宿主目录下。
[root@ansible ~]# ls -a | grep ssh        #查看
.ssh
[root@ansible ~]# cd .ssh
[root@ansible .ssh]# ls       #查看.ssh目录下的文件,有公钥和私钥
id_rsa  id_rsa.pub  known_hosts
[root@ansible ~]# ssh-copy-id [email protected]            #复制公钥到主机192.168.1.2
[email protected]'s password:              #输入主机1.2的root用户密码
[root@ansible ~]# ssh-copy-id [email protected]            #复制公钥到主机192.168.1.3
[email protected]'s password:                 #输入主机1.3的root用户密码
#在实际生产环境中,不会使用root身份,更改一下复制公钥时指定的用户即可。
[root@ansible ~]# ssh 192.168.1.2           #测试是否可以免密码登录
Last login: Tue Jul 23 08:11:39 2019 from 192.168.1.88
[root@server1 ~]# exit              #退出192.168.1.2的shell环境
[root@ansible ~]# ssh 192.168.1.3                #测试是否可以免密码登录
Last login: Tue Jul 23 08:43:16 2019 from 192.168.1.88
[root@server 2 ~]# exit           #退出192.168.1.3的shell环境

Three, Ansible configuration:

Ansible inventory management host configuration file information, corresponding to the hosts file system function, the default stored in / etc / ansible / hosts, the hosts file, organized by grouping apparatus, grouping and Ansible defined by the host inventory, if use the default / etc / ansible / hosts, through new inventory ansible -i to specify the inventory path, directly using the default path I have here.

1, in packets need to add a host of management:

It is management before, you must first write hosts file, because Ansible add hosts file in packets through the list of devices to achieve the management of the equipment. hosts file, [] contains the group name, the list of devices supported by domain name and IP address, by default, by accessing the port 22 (SSH) to manage the device, if the target host uses a non-default SSH port, you can also host after using the name of the colon and the port number indicated, to conduct separate units, also supports wildcards.

[root@ansible ~]# vim /etc/ansible/hosts            #编辑清单文件,在文件末尾写入以下内容
                .....................             #省略部分内容   
[web]              #定义一个名为web的分组,下面是web组中的主机
192.168.1.2
192.168.1.3
[test01]            #定义一个名为test01的分组,下面是test01组中的主机
www.warrent.com:222         #若目标主机使用了非默认的SSH端口,可以在域名后面加端口号来指定
ljz[2:5].test.com       #[2:5]表示2~5之间的所有数字,如ljz2.test.com、ljz3.test.com .......的所有主机
192.168.1.4:66               #IP地址后面也可以指定非默认的端口号
#将需要管理的主机写入后,保存退出即可。注意,该文件中包含一个隐含的分组“all”,表示所有主机。

Once configured, may be defined for a group of remote hosts operation, the operation may be one or more for a certain host group specified as follows:

[root@ansible ~]# ansible web -m command -a "systemctl status httpd" --limit "192.168.1.2"
#查看web组中的192.168.1.2主机httpd服务的状态
192.168.1.2 | FAILED | rc=3 >>
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled)
   Active: inactive (dead)
     Docs: man:httpd(8)
           man:apachectl(8)non-zero return code
#也可以这样:
[root@ansible ~]# ansible 192.168.1.2 -m command -a "systemctl status httpd"
192.168.1.2 | FAILED | rc=3 >>
● httpd.service - The Apache HTTP Server
   Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor 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"
#查询192.168.1.0这个网段所有主机的httpd服务状态
192.168.1.2 | FAILED | rc=3 >>
     .................
192.168.1.3 | FAILED | rc=3 >>
     .................

Four, Ansible command:

[root@ansible ~]# ansible   #输入ansible后,连续按两下tab键,可以查看ansible所有相关命令
ansible               ansible-doc           ansible-playbook-2
ansible-2             ansible-doc-2         ansible-playbook-2.7
ansible-2.7           ansible-doc-2.7       ansible-pull
                ..........................

Command 1, ansible:

ansible production environment is one of very frequent use of the command, mainly used in the following scenarios:

  • Temporary maintenance, there is no law, temporary need to do the task, also known as non-curable demand.
  • Temporary one-time operation.
  • Secondary development interface calls.

ansible following options are available:

  • -v: detailed implementation procedure information output can be obtained all the information execution.
  • -i PATH: Specifies the inventory information, the default is / etc / ansible / hosts.
  • -f: the number of concurrent threads, the default is 5 threads.
  • --private-key = PRIVATE_KEY_FILE: Specifies the key file.
  • -m: Specifies the execution module.
  • -M: block storage path specified, the default is / usr / share / ansible, may be set by default path ANSIBLE_LIBRARY.
  • -a: Specifies the module parameters.
  • -u: Specifies the remote host to which user is running the command.
  • -l: restrictions run the host, equivalent to "--limit".
  • --list-hosts: listed in the list of eligible host, does not execute any commands.

Usage Example 1 (in advance / etc / ansible / hosts file group defined web):


[root@ansible ~]# ansible all -f 5 -m ping          <!--检查所有主机是否存活-->
192.168.1.3 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.1.2 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
<!--其中192.168.1.3和1.2是执行主机,SUCCESS表示命令执行成功,“=> {”表示返回的
结果。“changed”:false表示没有对主机做出更改,“ping”:“pong”表示执行了ping命令的
返回结果。命令中“all”关键字在前面提到过,代表了/etc/ansible/hosts文件中的所有主机,
不需要在hosts文件中定义,系统中默认存在的-->

Usage Example 2:

[root@ansible ~]# ansible web --list                        #列出web组所有的主机列表
  hosts (2): 
    192.168.1.2
    192.168.1.3
#以上表示web中包含两个主机,分别是1.2和1.3

Usage Example 3:

[root@ansible ~]# ansible web -m command -a "df -hT"        #显示web组中主机的磁盘使用情况
192.168.1.2 | SUCCESS | rc=0 >>
文件系统                类型      容量  已用  可用 已用% 挂载点
/dev/mapper/centos-root xfs        50G  5.8G   45G   12% /
devtmpfs                devtmpfs  895M     0  895M    0% /dev
                          ............................            #省略部分

192.168.1.3 | SUCCESS | rc=0 >>
文件系统            类型      容量  已用  可用 已用% 挂载点
/dev/mapper/cl-root xfs        17G  5.5G   12G   33% /
devtmpfs            devtmpfs  897M     0  897M    0% /dev
tmpfs               tmpfs     912M   84K  912M    1% /dev/shm
                          ............................            #省略部分

ansible results returned very friendly, usually with three colors to indicate the results: red, green and orange ×××. Red means the execution of which there is an abnormality; orange represents ××× command execution status change objectives; green indicates a successful execution and did not make changes to the target host.

Command 2, ansible-doc:

ansible-doc module for querying instructions ansible document, similar to the man command for each module has detailed instructions and application case introduction.

[root@ansible ~]# ansible-doc -l                  #列出支持的模块
1378               #支持的模块有1378个
[root@ansible ~]# ansible-doc ping             #查询ping模块的说明信息
> PING    (/usr/lib/python2.7/site-packages/ansible/modules/system/ping.py)

        A trivial test module, this module always returns `pong' on
        successful contact. It does not make sense in playbooks, but
        it is useful from `/usr/bin/ansible' to verify the ability to
                             ................#省略部分内容

Command 3, ansible-PlayBook:
ansible-daily application PlayBook is the highest command usage, similar to the Linux source or sh commands used to perform a series of tasks. Its working mechanisms are: writing good playbook for centralized document processing tasks by reading in advance. ansible-playbook playbook command followed by the file format yml, playbook file storage tasks are to be executed, use the following command (playbook.yml documents to be prepared in advance, it is best to specify the absolute path playbook.yml):

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

Command 4, ansible-console:
an interactive tool that ansible to ansible-console us, similar to the Windows and Linux cmd in the shell. The same can be used on ansible-console out of the virtual terminal like shell command ansible variety of built-in, which provides a good experience for users accustomed to shell interactive mode, all operating with a similar shell, and tab-completion . Specific operation is as follows:

[root@ansible ~]# ansible-console          #连接交互式工具
Vault password:         #ansible 2.4.2.0会提示输入一个密码,随便输入后按回车即可,不允许空值
Welcome to the ansible console.
Type help or ? to list commands.

root@all (2)[f:5]$ cd web         #切换到web组
root@web (2)[f:5]$ list     #列出组中主机
192.168.1.2
192.168.1.3
root@web (2)[f:5]$ ifconfig ens33         #查询每个主机的网卡信息
root@web (2)[f:5]$ exit           #退出ansible-console环境

Five, ansible modules:

1, command module:

command module performs the remote host command does not support the pipe shell characteristics, redirection, and the remaining shell similar to the following common parameters:

  • chdir: on the remote host before running the command needs to advance into the directory.
  • creates: Create a file in order to run, if the file already exists, create the task will not be performed.
  • removes: remove a file in the command is run, if the file does not exist, remove the task will not be performed.
  • executeble: specify shell commands to run.
[root@ansible ~]# ansible all -m command -a "chdir=/home ls ./"
#在所有主机上运行“ls ./”命令,运行前切换至/home目录下。

2, shell module (equivalent to universal module, you can perform most commands):

shell command module performs the remote host, the equivalent shell process calls the remote host, and then open a sub-shell to run commands at the shell. And command module of the difference is that it supports the shell characteristics, such as a pipe break, and redirection.

[root@ansible ~]# ansible web -m shell -a 'echo "hello world" >> /tmp/hello.txt'
#在web组的主机上编写一个txt文件
192.168.1.2 | SUCCESS | rc=0 >>

192.168.1.3 | SUCCESS | rc=0 >>

[root@ansible ~]# ansible web -m shell -a ' cat /tmp/hello.txt'        #查看编写的文件
192.168.1.3 | SUCCESS | rc=0 >>
hello world

192.168.1.2 | SUCCESS | rc=0 >>
hello world

3, copy module:

Copy means for copying the position of the specified host file to a remote host, the common parameters are as follows:

  • src: source pointed out that the file path, you can use relative and absolute paths. Direct support specified directory, if the source is a directory, the target must be a directory.
  • dest: that the destination directory files to be copied, using an absolute path, directly support the specified directory. If the source is a directory, the target must be a directory, if the target already exists, it will cover the original content.
  • mode: When copying pointed out, permission for the target file, optional.
  • owner: Copy pointed out, is the main target file, optional.
  • group: Copy pointed out, is a set of target files, optional.
  • content: point out the content copied to the target host, it can not be used with src, equivalent to copy data specified content to the target file.
[root@ansible ~]# ansible web -m copy -a "src=/etc/hosts dest=/tmp/ mode=777 owner=nobody group=root"
#将本机的/etc/hosts文件复制到web组中的主机,并指定权限为777,属主为nobody,属组为root。

4, hostname module:

means for managing hostname host name, the following common parameters:

  • name: Name of the host name.
[root@ansible ~]# ansible 192.168.1.2 -m hostname -a "name=web1"
#将主机1.2的主机名改为web1
192.168.1.2 | SUCCESS => {
    ansible_facts: {
        ansible_domain: , 
        ansible_fqdn: web1, 
        ansible_hostname web1 
        ansible_nodename: web1
    }, 
    changed: true
    name: web1
}
[root@server1 ~]# hostname       #在192.168.1.2主机上查看
web1
[root@server1 ~]# cat /etc/hostname                  #在192.168.1.2主机上查看
web1
#更改主机名后需重启才可使新的主机名生效。

5, yum module:

yum yum mechanism module based on the remote host management package, the following common parameters:

  • name: the name of the package, you can bring the version number. If not specified version, the default install the latest version.
  • state = present | latest | absent: indicates the operation of the package performs, present indicates that the installer package, latest represent the latest version of the package, absent express uninstaller package.
  • disablerepo: When installing with yum, temporarily disable a warehouse ID.
  • enablerepo: When installing with yum, a warehouse of temporary ID is enabled.
  • conf_file: yum runtime configuration file, instead of using the default configuration file.
  • diable_gpg_check = yes | no: integrity check function is enabled.
[root@ansible ~]# ansible web -m yum -a "name=httpd state=present"       
<!--在web组中的主机上安装httpd服务,需要注意的是,管理端只是发送yum指令到被
管理端,被管理端要存在可用的yum仓库才可以成功安装。-->

6, Service Module:

Service module is used to manage the service on the remote host module, common parameters are as follows:

  • name: the name of the managed service.
  • state = started | stopped | restarted | reloaded: action includes startup, shutdown, reboot and reload the configuration file.
  • enabled = yes | no: Indicates whether the service was set boot from the start.
  • runlevel: If you set enabled boot from the start, will have to start the defined objectives in those running automatically, such as 2/3/4/5.
[root@ansible ~]# ansible web -m service -a "name=httpd state=started enabled=yes"
#启动httpd服务,并设置为开机自启动。

7, user modules:

user module for user account management on the remote host, common parameters are as follows:

  • name: the parameters must, account name.
  • state = present | absent: create or delete an account, present represents the creation, absent express deleted.
  • system = yes | no: Does the system account.
  • uid: User UID.
  • group: Basic user group.
  • groups: additional set of users.
  • shell: the default shell used.
  • home: the user's home directory.
  • move_home = yes | no: If you set the home directory already exists, the existing home directory move.
  • password: password of the user.
  • comment: Notes user information.
  • remove = yes | no: when the state = absent, whether you want to delete the user's home directory.
[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"'
#创建一个名为user1的用户
[root@ansible ~]# ansible web -m user -a "name=user1 remove=yes state=absent"
#删除刚才创建的user1用户

8, group module:

means for group management group, create or delete a group, the following common parameters:

  • gid specified group: gid
  • name: Specifies the group name
  • state = present | absent: create or delete
  • system = yes | no: Does the system group
[root@ansible ~]#  ansible web -m group -a 'name=test gid=300 state=present system=yes'
#创建gid为300,组名为test的系统组。
[root@ansible ~]#  ansible web -m group -a 'name=test gid=300 state=absent system=yes'
#删除刚刚创建的组。

9, mount modules:

mount means for mount a file system, the following common parameters:

  • src: To mount the device or file system
  • name: Specifies the mount point
  • fstype: Specifies the file system type
  • ots = w | r | o: set the file type of reader, can be used in combination.
  • state = present | absent | mounted | unmounted: present represents only modify the fstab configuration file does not automatically create a mount point, and do not mount; absent means to delete the mount point, modify the fstab file; mounted: automatically create a mount point and mount, adding to automatically mount (fstab); unmounted: just uninstall, do not delete the mount point, does not modify the fstab file.
[root@ansible ~]# ansible web -m mount -a 'name=/warrent src=/dev/cdrom fstype=iso9660 state=mounted'
#挂载iso镜像到/warrent目录下,并设置开机自动挂载。
[root@ansible ~]#  ansible web -m mount -a 'name=/warrent state=absent'
#卸载ISO镜像,并删除挂载点,删除开机自动挂载。
[root@ansible ~]# ansible web -m mount -a "path=/mnt/data src=/dev/sdb1 fstype=xfs ots=wr state=mounted"
#注:mount已经使用path代替了原来的name参数,但是name参数还是可以使用的。

10, cron module:

cron module used to manage scheduled tasks, commonly used parameters are as follows:

  • name: Specifies the scheduled task description, Required
  • job: tasks to be performed
  • user: the user running the Job
  • Execution time:
    minute: 0-59, default is *
    hour: 0-23, default is *
    Day: 1-31, default is *
    month The: 1-12, default is *
    WEEKDAY: 1-7, default is *
  • state = present | absent: present expressed Add Scheduled Task; absent means to delete the scheduled task.
[root@ansible ~]# ansible web -m cron -a 'name=test user=root minute=*/2 job="echo test >> /tmp/warrent.txt" state=present'
#添加一个计划任务测试一下
[root@ansible ~]# ansible web -m shell -a "crontab -l"                #查看创建的任务计划
192.168.1.2 | SUCCESS | rc=0 >>
#Ansible: test
*/2 * * * * echo test >> /tmp/warrent.txt

192.168.1.3 | SUCCESS | rc=0 >>
#Ansible: test
*/2 * * * * echo test >> /tmp/warrent.txt

11, script module:

Function: Perform master script on the remote host, equivalent to scp + shell combination.

Usage is as follows:

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

Module to write so many examples of it, in order to avoid paper clutter, using a configuration file on playbook two days I will update to another blog post recently.

playbook configuration file using the YAML syntax, with concise, clear structure and so on. playbook profile similar to the shell script is a YAML formatted file to save the task list for specific needs. ansible command described above although you can complete various tasks, but when configuring a number of complex tasks, enter one by one it is a highly inefficient. More effective program is placed in the playbook configuration file all of the task code by ansible-playbook command to execute the file, you can automate the operation and maintenance. YAML file extension is usually .yaml or .yml.

Guess you like

Origin blog.51cto.com/14154700/2422724