Getting started with Ansible automated operation and maintenance tools

1. Experimental environment

系统镜像:CentOS-7-x86_64-DVD-1810
VMware虚拟机:VMware® Workstation 16 Pro 16.1.0 build-17198959
Nginx源码包:nginx-1.23.4.tar.gz

Master:192.168.42.100    ##控制服务器
Web1:192.168.42.110    ##终端服务器
Web2:192.168.42.120    ##终端服务器

Two, close the firewall, SELinux

systemctl stop firewalld        ##临时关闭防火墙(重启失效)
systemctl disable firewalld     ##关闭防火墙开机自启
setenforce 0                    ##临时关闭SELINUX
vi /etc/selinux/config        ##配置文件永久关闭SELINUX
SELINUX=disabled
getenforce        ##验证SELINUX状态
Master:192.168.42.100    ##控制服务器
Web1:192.168.42.110    ##终端服务器
Web2:192.168.42.120    ##终端服务器

3. Install Ansible

yum search ansible    ##搜索Ansible安装包
yum -y install centos-release-ansible-29.noarch    ##安装最新版本
yum -y install ansible    ##安装Ansible服务
ansible --version        ##查看Ansible版本

Fourth, the use of Ansible configuration list (inventory)

        1. Configure the operation group "Webs": vim /etc/ansible/hosts    

格式1:
[Webs]    ##自定义群组名"Webs"
192.168.42.110:22	ansible_ssh_user=root	ansible_ssh_pass=redhat    ##ip、账号、密码
192.168.42.120:22	ansible_ssh_user=root	ansible_ssh_pass=redhat    ##ip、账号、密码
格式2:
[Webs]    ##自定义群组名"Webs"
192.168.42.110    ##终端服务器"Webs1"
192.168.42.120    ##终端服务器"Webs2"
[Webs:vars]    ##群组"Webs"的"vars"变量
ansible_ssh_user=root        ##终端服务器的ssh登录账号
ansible_ssh_pass=redhat     ##终端服务器的ssh登录密码
格式3:
[Webs]    ##自定义群组名"Webs"
beta.example.org	##终端服务器的主机域名
192.168.42.1[10:20]	##终端服务器的IP网段

        2. Close the ssh login verification prompt: vim /etc/ansible/ansible.cfg

第5行:#forks=5		##默认并发数为5
第26行:#remote_port = 22		##默认通过ssh服务的22号端口访问终端服务器
第71行:#host_key_checking = False	##关闭ssh登录验证提示
第107行:#remote_user = root    ##默认使用root账号ssh登陆终端服务器

ansible Webs -m ping	##测试连通性	

        3. Configure ssh password-free login

ssh-keygen					##生成密钥对
ssh-copy-id [email protected]	##复制公钥到终端服务器
ssh-copy-id [email protected]	##复制公钥到终端服务器

ansible Webs -m ping	##测试终端服务器的连通性	

5. Common modules of Ansible

        Ansible command format

ansible 群组/主机(Webs/192.168.42.110)	-m 模块(默认为command) -a 模块的参数 -f 并发数(默认为5) -i 清单(默认位置在“/etc/ansible/hosts”)
默认模块:command(可以直接在终端服务器上执行命令,并将结果返回控制服务器
不支持管道,重定向等shell的特性)


ansible-doc -l		##查看Ansible支持的所有模块列表
ansible-doc -s yum	##查看yum模块命令的配置参数信息

1. Ping module: test the connectivity from the control server to the terminal server

ansible Webs -m ping
ansible 192.168.42.110 -m ping

2. Shell module: manage terminal servers to execute shell commands

ansible Webs -m shell -a 'ip a'    ##查看终端服务器的网卡信息
ansible Webs -m shell -a 'ip a s ens32'    ## ##查看终端服务器"ens32"网卡信息
ansible Webs -m shell -a 'ss -ntl | grep 22'    ## ##查看终端服务器22端口号

3. The yum module: manages the yum installation of the terminal server software package

state命令的常用参数:
present、installed、latest    ##安装服务
absent、removed            ##卸载服务
 
ansible Webs -m yum -a 'name=httpd,mariadb,mariadb-server state=installed'    ##安装httpd服务
ansible Webs -m yum -a 'name=httpd state=installed'    ##安装httpd服务
ansible Webs -m yum -a 'name=httpd state=removed'    ##卸载httpd服务

4. systemd/service module: manage the service management of the terminal server


"state"命令的常用参数:
reloaded    重载
restarted    重启
started    启动
stopped    停止

"enabled"命令的常用参数:
yes    开启
no    关闭

ansible Webs -m systemd -a 'name=httpd state=started enabled=yes'    ##开启httpd服务
ansible Webs -m systemd -a 'name=httpd state=restarted enabled=yes'    ##重启httpd服务,并设置开机自启

5. file module: manage the files of the terminal server


state命令的常用参数:
touch    一般文件
directory    目录
link    软链接
hard    硬链接
absent    删除

ansible Webs -m file -a 'path=/root/a.txt state=touch'    ##创建文件"a.txt"
ansible Webs -m file -a 'path=/root/File-1 state=directory'    ##创建目录"File-1"
ansible Webs -m file -a 'path=/root/File-1 state=absent'    ##删除目录"File-1"

6. User module: manage users of terminal servers

openssl passwd    ##加密字符,用于下一步设置账户密码
ansible Webs -m user -a 'name=zhang password=Rkpbuu1AzMLZY'
##创建用户账户"zhang"密码"redhat"(使用明文不生效)

ansible Webs -m user -a 'name=zhang state=absent'    ##删除"zhang"用户

7. group module: manage user groups of terminal servers

gid    设置组的GID号
name    指定组的名称
state    指定组的状态,默认为创建,设置值为absent为删除
system    设置值为yes,表示创建为系统组

ansible Webs -m group -a 'name=Steam gid=1234'    ##创建用户群组"Steam",指定"gid"为"1234"
ansible Webs -m group -a 'name=Steam state=absent'    ##删除用户群组"Steam"

8. copy module: copy files to the terminal server

vim ./index.html
Hello World!

ansible Webs -m copy -a 'src=./index.html dest=/var/www/html/index.html'
##拷贝测试页面到终端服务器

9. get_url module, download files on the terminal server

yum -y install wget    ##安装"wget"网络文件下载服务

wget https://nginx.org/download/nginx-1.23.4.tar.gz    ##下载nginx源码包到本地服务器

ansible Webs -m get_url -a 'url=https://nginx.org/download/nginx-1.23.4.tar.gz dest=/root'
##在终端服务器下载nginx源码包

10. Unarchive module, decompress files to terminal server

ansible Webs -m unarchive -a 'src=./nginx-1.23.4.tar.gz dest=/opt'
##解压nginx服务源码包到终端服务器的"/opt"目录下

11. The fetch module returns the terminal server file to the control server

ansible Webs -m fetch -a 'src=/etc/passwd dest=/root'
##传输终端服务器的用户文件到控制服务器

12. script, execute the script on the terminal server

vim test.sh
#!/bin/bash
echo "This is $HOSTNAME"

ansible Webs -m script -a './test.sh'

13. firewalld module, manage terminal server firewalld service status

port命令常用参数:
80/tcp

state命令常用参数:
enabled    启用
disabled    关闭

ansible Webs -m service -a 'name=firewalld state=started'    ##开启防火墙
ansible Webs -m firewalld -a 'port=80/tcp state=disabled'    ##关闭80端口
ansible Webs -m firewalld -a 'port=80/tcp state=enabled'    ##开启80端口

14. The cron module manages the scheduled tasks of the terminal server

minute    分钟
hour    小时
day    日
month    月
weekday    周
时间表达式    要执行的操作
* * * * *    sh /a.sh

ansible Webs -m cron -a 'name=play-1 weekday=1 hour=12 job=ls'    ##每周一中午12点执行ls任务
ansible Webs -m cron -a 'name=play-1 state=absent'    ##删除play-1计划任务

15. Setup module, view the hardware information of the terminal server

ansible Webs -m setup
ansible Webs -m setup -a 'filter=ansible_processor'    ##查看终端服务器的CPU信息

 Example 1. Use Ansible to automate yum installation of LNMP
1. Install software nginx and PHP software package (yum module)       
2. Configure nginx (copy module, shell module)
3. Start nginx (systemd/service module, shell module)
4. Send test page (copy module)

ansible Webs -m yum -a 'name=epel-release state=installed'    ##安装epel环境
ansible Webs -m yum -a 'name=nginx,php,php-mysql,php-gd,php-fpm,mariadb,mariadb-server state=installed'
##安装nginx,php,php-mysql,php-gd,php-fpm,mariadb,mariadb-server安装包

##配置本地"nginx.conf"配置文件
vim nginx.conf
location / {
            root   /usr/share/nginx/html;    ##修改首页路径
            index  index.php;                ##修改首页页面
        }

#
          location ~ \.php$ {
            root           /usr/share/nginx/html;    ##修改首页路径
            fastcgi_pass   127.0.0.1:9000;
            fastcgi_index  index.php;                ##修改首页页面,"$document_root"参数
            fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
            include        fastcgi_params;
        }


ansible Webs -m copy -a 'src=./nginx.conf dest=/etc/nginx'    ##拷贝"nginx.conf"配置文件
ansible Webs -m service -a 'name=nginx state=started enabled=yes'    ##启动nginx
ansible Webs -m service -a 'name=php-fpm state=started enabled=yes'    ##启动php-fpm
ansible Webs -m service -a 'name=mariadb state=started enabled=yes'    ##启动mariadb

##编辑PHP测试页面
vim ./index.php
<?php
phpinfo();
?>

ansible Webs -m copy -a 'src=./index.php dest=/usr/share/nginx/html'    ##拷贝测试页面
##浏览器访问网页进行测试

Example 2. Using Ansible to automate source code installation of LNMP


ansible webs -m shell -a 'yum install -y gcc pcre-devel zlib-devel'
ansible webs -m shell -a 'cd /opt/nginx-1.20.1 && ./configure && make && make install'
ansible webs -m shell -a '/usr/local/nginx/sbin/nginx '

Example 3: Use the playbook module to automatically install LNMP

vim LNMP.yml/LNMP.yaml    ##后缀格式为".yml"或".yaml"
---
- hosts: Webs   ##自定义执行的清单群组
  tasks: ##需要执行的任务的列表
  - name: '安装epel环境'    ##安装任务描述
    yum: name=epel-release state=installed    ##执行命令
  - name: '安装nginx相关组件'
    yum: name=nginx,php,php-fpm,php-gd,php-mysql,mariadb,mariadb-server state=installed
  - name: '发送nginx配置文件'
    copy: src=./nginx.conf dest=/etc/nginx/nginx.conf
  - name: '启动nginx服务,设置开机自启'
    systemd: name={
   
   { item }} state=started enabled=yes
    with_items:        ##"with_items"变量类似于for循环。("item"为自定义的变量名)
    - nginx
    - php-fpm
    - mariadb
  - name: '发送PHP测试页面到终端服务器'
    copy: src=./index.php dest=/usr/share/nginx/html


ansible-playbook --syntax-check LNMP.yaml	##检测语法格式是否正确
ansible-palybook -C LNMP.yaml    ##测试"LNMP.yaml",不执行安装操作   
ansible-playbook -v LNMP.yaml    ##显示命令执行的详细过程(-v,-vv,-vvv,-vvvv)

Example 4: Install LNMP using the source code of the playbook module

回顾源码安装nginx:
上传nginx包(nginx-1.23.4.tar.gz)
解压到指定路径(源码安装默认安装到“/usr/local/nginx”)
tar -zxvf nginx-1.23.4.tar.gz -C /usr/local/nginx/
cd /usr/local/nginx/nginx-1.23.4/
指定安装路径(--prefix)
./configure --prefix=/usr/local/nginx-1.23.4
安装依赖环境
yum -y install gcc pcre pcre-devel zlib zlib-devel
编译
make
安装
make install
启动
/usr/local/nginx/nginx-1.23.4/sbin/nginx
停止
/usr/local/nginx/nginx-1.23.4/sbin/nginx -s stop
优雅关闭,在退出去完成已经接受的连接请求
/usr/local/nginx/nginx-1.23.4/sbin/nginx -s quit
重新加载配置文件
/usr/local/nginx/nginx-1.23.4/sbin/nginx -s reload
验证80端口
ss -tanp | grep 80

编写playbook安装nginx:
vim yuanma.yml
---
- hosts: webs
  tasks:
  - name: '解压源码包到被管理主机'
    unarchive: src=./nginx-1.20.1.tar.gz dest=/opt
  - name: '安装依赖环境'
    yum: name=gcc,pcre,pcre-devel,zlib,zlib-devel state=installed
  - name: '编译安装源码包'
    shell: cd /opt/nginx-1.20.1/ && ./configure && make && make install
  - name: '关闭防火墙'
    service: name=firewalld state=stopped
  - name: '启动服务'
    shell: /usr/local/nginx/sbin/nginx

ansible-playbook -C yuanma.yml

6. Commonly used variables and loop judgments in Playbook

        1. Define variables and reference variables

vim vars.yml
---
- hosts: Webs    ##指定执行的清单群组
  vars:            ##定义全局变量
    pkg: httpd    ##自定义变量1
    pkd: httpd    ##自定义变量2
    sss: ss -ntl    ##自定义变量3/命令
  tasks:            ##需要执行的任务的列表
  - name: "安装{
   
   { pkg }}"    ##描述
    yum: name={
   
   { pkg }} state=installed
  - name: "启动{
   
   { pkd }}"    ##描述
    systemd: name={
   
   { pkd }} state=started
  - name: '执行{
   
   { sss }}'    ##描述
    shell: "{
   
   { sss }}"    ##命令不能以变量开头,包含其他字符时需要""标注

         2. Two formats of the with_items loop variable:

touch a.txt b.txt

vim user.yml
---
- hosts: Webs
  tasks:
  - name: '创建用户'
    user: name={
   
   { item }}
    with_items:        ##单个变量,采取列表样式设定变量
    - User1            ##自定义变量1
    - User2            ##自定义变量2


  - name: '复制文件'
    copy: src={
   
   { item.sss }} dest={
   
   { item.ddd }}
    with_items:        ##多个变量,采取字典样式设定变量
    - { sss: "./a.txt", ddd: "/opt" }    ##子变量item.sss,item.ddd
    - { sss: "./b.txt", ddd: "/usr" }    ##子变量item.sss,item.ddd

ansible-playbook user.yml

3. Reference variables in the template file

vim mb.yml

---
- hosts: Webs
  vars:
    pkg: httpd
    page: Hello!
  tasks:
  - name: "安装{
   
   { pkg }}"
    yum: name={
   
   { pkg }} state=latest
  - name: "推送测试页面"
    template: src=./index.html dest=/var/www/html

##此处copy无法调用变量"page"到测试页面读取

vim index.html
Hello World!
{
   
   { page }}

ansible-playbook mb.yml

4. Register variables

vim register.yml

---
- hosts: Webs
  tasks:    ##注册变量
  - name: '获取nginx运行状态'
    shell: ss -ntl | grep -wc 80	##"-w"代表精确过滤"80","-c"代表统计包含80的行数
    register: status
    ignore_errors: true		##忽略错误,避免不满足"when"条件,返回报错

  - name: '启动nginx'
    shell: /usr/local/nginx/sbin/nginx
    when: status.stdout == "0"


register    ##将上一条shell命令执行后的得到的三个返回值都储存到后面的status变量中
status        ##自定义的变量名
status.stdout    ##获取标准输出
status.stderr    ##获取错误输出
status.rc    ##命令执行完的返回值/$?


when用于做数值比较,在同name组下执行命令的优先级最高
可以使用的运算符号:
==	等于
>	大于
<	小于
>=	大于等于
<=	小于等于
!=	不等于

5, tags to label the task


vim tags.yml

---
- hosts: Webs   ##指定执行的清单群组  
  tasks: ##需要执行的任务的列表
  - name: '安装epel'    ##描述
    yum: name=epel-release state=installed
    tags: 				##标签命令
    - install_nginx

  - name: '安装nginx'
    yum: name=nginx state=installed
    tags: 				##标签命令
    - install_nginx


  - name: '启动nginx'
    systemd: name=nginx state=started enabled=yes
    tags: 				##标签命令
    - install_nginx
    - cfg_nginx


ansible-playbook nginx.yaml

ansible-playbook -t 标签名(cfg_nginx,install_nginx) nginx.yml
6. Handlers trigger tasks
vim handlers.yml

---
- hosts: Webs
  vars:
    page: This is a test.html
  tasks:
  - name: '安装httpd服务'
    yum: name=httpd state=latest
  - name: '推送测试页面'
    template: src=./index.html dest=/var/www/html/
    notify: restart httpd	##上一步操作"changed"成功,则触发任务

  handlers:	##定义触发任务
  - name: restart httpd	##触发任务名称,建议不要有汉字
    systemd: name=httpd state=restarted

在这里例子中,让任务发送的配置文件有更新时才会执行重启的操作,没有更新是不会执行重启的操作的!

Guess you like

Origin blog.csdn.net/shangyuanzhai/article/details/130346454