自动化运维工具ansible

ansible安装

ansible命令格式

ansible的配置文件

ansible 的ping模块

ansible的command模块

ansible 的shell模块

ansible的script模块

ansible的copy模块

file模块

ansible 的fetch模块

ansible安装包 yum模块

ansible pip模块

ansible启动 service模块

ansible 定时模块cron

ansible group模块

ansible user模块

ansible template模块

ansible setup模块

ansible playbook

1、playbook规范和一般用法

2、带参执行playbook脚本

3、ansible-playbook tags关键字 任务选择执行

4、ansible-playbook handlers和notify关键字 触发任务,任务绑定执行;以及多tags方法

5、playbook的when关键字 类似判断语句

6、循环执行yml中的命令 with_items

ansible的roles

一、ansible安装

1.epel源配置

yum install -y wget
wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo

2.安装ansible

yum install -y wget

二、ansible命令格式

Usage: ansible <host-pattern> [options]
    -a MODULE_ARGS, --args=MODULE_ARGS # 模块的参数
    -C, --check  # 会去执行,但是不做任何的改变,干跑,白跑
    -f FORKS, --forks=FORKS # 指定进程数,做并发
    --list-hosts #列出主机
    -m MODULE_NAME # 模块名称
    --syntax-check #检查语法
    -k, --ask-pass      ask for connection password #指定密码

三、ansible的配置文件

#三大配置文件
/etc/ansible/ansible.cfg
/etc/ansible/hosts
/etc/ansible/roles

其中hosts文件是用来作主机配置的

修改ansible配置文件 vi /etc/ansible/hosts

分组:

[web]
192.168.182.130
192.168.182.132
[db]
192.168.182.131
192.168.182.132
[cache]
192.168.182.130

 

## www[001:006].example.com
[yuming]
192.168.182.[130:132]

&ansible 的ping模块

ansible 192.168.182.130 -m ping
ansible 192.168.182.131 -m ping
ansible 192.168.182.132 -m ping
ansible all -m ping # 所有机器,hosts文件里面
ansible 192.168.182.131,192.168.182.130 -m ping # 部分机器
## 分组信息
[web]
192.168.182.130
192.168.182.131
[db]
192.168.182.131
192.168.182.132
[cache]
192.168.182.132
## www[001:006].example.com 从www001到www006
ansible web --list-hosts # 用来获取符合条件的主机
ansible web -m ping # 探测组内的机器
ansible web,db -m ping # 获取db和web的并集
ansible 'web:&db' -m ping # 获取db和web的交集
ansible 'web:!db' -m ping # 获取db和web的差集,在web中但是不在db中的
ansible 'web:db' -m ping # 获取db和web的并集

系统自带的ping走的是icmp协议,ansible自带的走的是ssh

&ansible的command模块

远程机器执行命令模块

chdir #切换目录
creates # 如果存在,就不执行,如果不存在,就执行
removes # 如果不存在,就不执行,如果存在,就执行
ansible web -m command -a "pwd" 
ansible web -m command -a "ls /tmp"
ansible web -m command -a "chdir=/tmp pwd" # 切换目录,一般做编译安装
ansible web -m command -a "creates=/tmp pwd" # 不被执行,因为/tmp已经存在,
ansible web -m command -a "creates=/tmp2 pwd" # 被执行,因为/tmp2目录不存在
ansible web -m command -a "creates=/tmp2 mkdir /data" # 会被执行,因为/tmp2目录不存在
ansible web -m command -a "removes=/tmp2 pwd"   # 不被执行,因为/tmp2目录不存在
ansible web -m command -a "removes=/tmp pwd" # 会被执行,因为/tmp已经存在,

&ansible 的shell模块

同command模块类似,也是让远程主机执行命令,不同的是他的命令可以包含"<"',">"', "|"',";"' and `"&"' 等符号

chdir #切换目录
creates # 如果存在,就不执行,如果不存在,就执行
removes # 如果不存在,就不执行,如果存在,就执行
ansible web -m shell -a "echo 'alex'|passwd --stdin alex" # 给用户设置密码
ansible 10.0.0.132 -m shell -a "bash a.sh" # 执行shell脚本
ansible 10.0.0.132 -m shell -a "./a.sh"
ansible 10.0.0.132 -m shell -a "/root/a.sh"
ansible 10.0.0.132 -m shell -a "/root/a.py" # 执行python脚本
ansible 10.0.0.132 -m shell -a "python a.py" 
# shell 脚本
#!/bin/bash
mkdir /alex2sb11
# python脚本
#!/bin/env python 
#coding:utf-8
print "停车坐爱枫林晚,霜叶红于二月花" 

&ansible的script模块

与shell让各远程机执行自己本机上的文件不同,script执行的是控制机器上的脚本

ansible db -m script -a "/root/a.sh" # 执行的是本地的脚本,管控机上的脚本
ansible db -m script -a "creates=/root/a.sh /root/a.sh" # 判断是远程主机是否存在,如果存在,就不执行,如果不存在,就执行
ansible db -m script -a "removes=/root/a.sh /root/a.sh" # 判断的主机是否存在,如果存在,就执行,如果不存在,就不执行

 

&ansible的copy模块

backup # 创建备份文件,以时间戳结尾
content # 直接写内容
dest # 目标地址
group #文件的属组
mode # 文件的权限W 2 R 4  X 1
owner #文件的属主
src # 原文件
 ansible db -m copy -a "src=/root/a.sh dest=/root/a.sh" # 复制文件
 ansible db -m copy -a "src=/root/a.sh dest=/root/a.sh mode=755" # 复制文件,并修改文件的权限
 ansible db -m copy -a "src=/root/a.sh dest=/root/a.sh mode=755 owner=alex"  #复制文件,修改文件的权限,属主,根据md5值来判断
 ansible db -m copy -a "src=/etc/init.d dest=/tmp/" # 复制文件夹
 ansible db -m copy -a "src=/etc/init.d/ dest=/tmp/" # 复制文件夹下面的所有文件
 ansible db -m copy -a "src=/etc/init.d dest=/tmp/ owner=alex " # 复制文件夹,并改变文件夹的属性,文件夹的文件的属性也会跟着改变
 ansible db -m copy -a "content='大弦嘈嘈如急雨,小弦切切如私语' dest=/tmp/a.sh" # 直接写文字,覆盖写入,要慎用
 ansible db -m copy -a "src=/root/a.sh dest=/root/a.sh mode=755 owner=alex backup=yes"  #备份文件,如果远程机器上没有要备份的文件,即使指定了backup=yes 也不会去备份文件

注意:此处备份的是远程主机上的文件

 

&file模块

access_time # 访问时间
group # 属组
mode #权限
owner #属主
path #路径
src # 原文件,link和hard的时候使用
state:
    directory 文件夹
    file
    touch 空文件
    link  软连接
    hard  硬链接
    absent 删除
ansible db -m file -a "path=/tmp/baoyuan state=directory" # 创建一个目录
ansible db -m file -a "path=/tmp/baoyuan state=directory owner=alex mode=644" # 创建一个目录,并制定属主,权限
ansible db -m file -a "path=/tmp/baoyuan.txt state=touch owner=alex mode=644" # 创建一个文件,并制定属主,权限
ansible db -m file -a "path=/tmp/f src=/etc/fstab state=link" # 创建一个软连接
ansible db -m file -a "path=/tmp/f state=absent" # 删除

&ansible 的fetch模块

将远程机器上的文件拉取到本地(控制机),以ip或者主机名生成目录,并保留原来的目录结构

参数:

  dest 目标地址

  src 本地地址

示例:ansible web -m fetch -a "dest=/tmp src=/var/log/cron"

注:tail -f /var/log/cron是查看定时任务的日志

&ansible安装包 yum模块

参数

disable_gpg_check # 是否要检查key
disablerepo # 禁用repo
enablerepo #启用repo
name # 包名
state # 状态 installed removed

示例

ansible web -m yum -a "name=python2-pip" # 安装一个包
ansible web -m yum -a "name='@Development Tools'" # 安装包组
ansible web -m yum -a "name=redis,python2-pip" # 同时安装多个包
ansible web -m yum -a "name=redis state=absent" # 卸载

 

&ansible pip模块

参数

requirements #导出的文件
name # 模块的名称
virtualenv # 虚拟环境
state #

示例

ansible web -m pip -a "name=django==1.11.18" # 安装
ansible web -m pip -a "name=flask 

 

&ansible启动 service模块

系统服务命令回顾(启动、自启):

ps -ef|grep redis # 查看进程
ss -tnlp #查看端口信息
# 启动服务
systemctl start redis  centos7
service redis start    centos6
# 开机自启动
systemctl enable redis centos7
chkconfig redis on centos6

参数

enabled # 设置开机自启动
name # 名称
state
    started
    stopped
    restarted
    reloaded

示例:

ansible web -m service -a "name=redis state=started" # 启动
ansible web -m service -a "name=redis state=stopped" # 关闭
ansible web -m service -a "name=redis state=started enabled=yes" # 启动并设置开机自启动

&ansible 定时模块cron

知识回顾:
定时任务格式(可通过 cat /etc/crontab 查看):
    * * * * * job
    分 时 日 月 周 任务
    1 * * * * job    # 代表每小时的第一个分钟
    2/* * * * * job  # 每隔2分钟执行job
    1 10-19 * * * job  # 代表10到19点的第一分钟
    0-59 0-23 1-31 1-12  0-7 job
    * * * * * tar -zcf /opt/etc.tar.gz /etc
    分钟不要用*,最好是指定时间
    分钟不要用*,最好是指定时间
    分钟不要用*,最好是指定时间
crontab的主要作用:
    收集日志
    备份数据
    同步时间
        ansible all -m shell -a 'date'
        ansible all -m yum -a 'name=ntp'
        ansible all -m yum -a 'name=ntp'
crontab -l # 查看计划任务
crontab -r # 删除所有的计划任务
crontab -e # 编辑计划任务

参数

day #天

hour #时

job #任务

minute #分

month #月

name #名字

state:present||absent

user#执行计划任务的用户

weekday#周

disabled #禁止

示例

ansible web -m cron -a "minute=21 job='touch /tmp/cron.txt' name=touchfile" # 设置计划任务
ansible web -m cron -a "minute=23 job='touch /tmp/cron.txt' name=touchfile4 disabled=yes" # 禁用计划任务,表现为加注释
ansible web -m cron -a "name=touchfile4 state=absent" # 删除计划任务

 

&ansible user模块

参数

group #组 

groups #附加组 

home #家目录

name #用户名

shell #登录shell

remove #删除用户并删除家目录

state #状态

system #系统用户

uid #用户id

应用示例

ansible db -m user -a "name=alex2 shell=/sbin/nologin home=/opt/alex2 uid=2000 group=root" # 创建用户,并指定用户的家目录,登陆shell,uid,组
ansible db -m user -a "name=alex3 system=yes" #创建系统用户
ansible db -m user -a "name=alex3 state=absent" # 删除用户
ansible db -m user -a "name=alex2 state=absent remove=yes" # 删除用户并删除用户的家目录

&ansible group模块

参数

gid #组id

system #系统组

name #组名

state #状态

应用示例

ansible db -m group -a "name=canglaoshi" #创建普通组
ansible db -m group -a "name=wutenglan system=yes" # 创建系统组
ansible db -m group -a "name=wutenglan state=absent" # 删除组

 &ansible template模块

参数:
与copy模块相同,dest、src、owner...
配置文件
mkdir templates
#如更改redis.conf文件,可在templates文件夹中书写:
bind {{ansible_default_ipv4.address}}

 #playbook文件中
 - hosts : web
   tasks :
   - name : install
     yum : name=redis
   - name : copyfile
     template : src=redis.conf dest=/etc/redis.conf
     tags : copyconf
   - name : start
     service : name=redis state=started
   - name : restart
     service : name=redis state=restarted
     tags : copyconf

 &ansible setup模块

获取setup模块收集的数据:
ansible 192.168.182.130 -m setup |more
查看系统版本:
ansible cache -m setup -a "filter=*distribution*"

&ansible playbook

1、playbook规范和一般用法

yaml规范

    字典key:value

    列表[]

    后缀名:yaml、yml
- hosts: web
  remote_user: root
  tasks:
  - name: copyfile
    copy: src=/etc/fstab dest=/tmp/fs  #模块:参数
#多任务 playbook 文件
- hosts: web
  remote_user: root
  tasks:
  - name: copyfile
    copy: src=/etc/fstab dest=/tmp/fs 
  - name: createuser
    user: name=alex11

执行顺序:所有机器先执行第一个任务,都完成后再执行第二个任务

幂等性

不管执行多少次,结果均相同

2、带参执行playbook脚本

方式一

#编写:sec.yml
- hosts: web
  remote_user: root
  tasks:
  - name: copyfile
    copy: src=/etc/fstab dest=/tmp/fs 
  - name: createuser
    user: name=alex11

ansible-playbook -e user=alex11 sec.yml

方式二:

hosts文件传参
[web]
192.168.182.130 user=alex130
192.168.182.132 user=alex132

 ansible-playbook sec.yml

方式三:

hosts文件传参

[web:vars]
user=1315

 ansible-playbook sec.yml

方式四:

yml文件中vars传参

 - hosts : web
   vars :
   - user : alexyvars
   remote_user : root
   tasks:
   - name : echo
     shell : echo {{user}} > /tmp/ansiusertest.txt

方式五:

yml文件中register传参

 - hosts : web
   vars :
   remote_user : root
   tasks:
   - name : sum
     shell : echo 5+6|bc
     register : user 
   - name : echo
     shell : echo {{user.stdout}} > /tmp/ansiusertest.txt

五种传参方式的优先级

-e>playbook的vars>hosts

hosts传参时ip地址后直接传参优先级高于[web:vars],即方法二优先级高于方法三

yml文件中register的优先级好友vars,即方法五高于方法三

3、ansible-playbook tags关键字 任务选择执行

 - hosts : web
   tasks :
   - name : install
     yum : name=redis
   - name : copyfile
     copy : src=/etc/redis.conf dest=/etc/redis.conf
     tags : copyconf
   - name : start
     service : name=redis state=started

单任务执行:

ansible-playbook -t copyconf fourth.yml

4、ansible-playbook handlers和notify关键字 触发任务,任务绑定执行;以及多tags方法

方式一:

- hosts: web
  tasks:
  - name: install
    yum: name=redis
  - name: copyfile
    copy: dest=/etc/redis.conf src=/etc/redis.conf
    tags: copy
    notify: restart
  - name: start
    service: name=redis state=started
  handlers:
  - name: restart
    service: name=redis state=restarted

redis更改配置文件后重启

方式二:

 - hosts : web
   tasks :
   - name : install
     yum : name=redis
   - name : copyfile
     copy : src=/etc/redis.conf dest=/etc/redis.conf
     tags : copyconf
   - name : start
     service : name=redis state=started
   - name : restart
     service : name=redis state=restarted
     tags : copyconf
ansible-playbook -t copyconf thrid.yml

5、playbook的when关键字 类似判断语句

示例代码

 #playbook文件中
- hosts : web
   tasks :
   - name : when1
     shell : echo '大弦嘈嘈如急雨' >/a.txt
     when : cmd=='xr'
   - name : when2
     file : path=/a.txt state=touch
     when : cmd=='cj'
ansible-playbook -e cmd=xr six.yml

示例代码2(根据系统版本做响应操作):

- hosts: web
  tasks:
  - name: file
    copy: content="大弦嘈嘈如急雨" dest=/opt/file
    when: ansible_distribution_major_version=="7"
  - name: file
    copy: content="小弦切切如私语" dest=/opt/file
    when: ansible_distribution_major_version=="6"

6、循环执行yml中的命令 with_items

示例代码:

 #playbook文件中
- hosts : web
   tasks :
   - name : when1
     shell : echo '大弦嘈嘈如急雨{{item}}' >a.txt
     with_items :
     - ju1
     - ju2
     - ju3

示例代码2(多with_items):

- hosts: web
  tasks:
  - name: creategroup
    group: name={{item}}
    with_items:
    - wusir20
    - wusir21
  - name: file
    user: name={{item}}
    with_items:
    - alex22
    - alex23

示例代码3(with_items嵌套):

- hosts: web
  tasks:
  - name: creategroup
    group: name={{item}}
    with_items:
    - wusir22
    - wusir23
  - name: file
    user: name={{item.name}} group={{item.group}}
    with_items:
    - {"name":alex24,"group":wusir22}
    - {"name":alex25,"group":wusir23}

&ansible的roles
- 优点
  目录结构清晰
  可以相互调用

目录结构:./data/roles/nginx 需注意nginx.yml在roles同目录下

#目录结构:./data/roles/nginx 需注意nginx.yml在roles同目录下
roles/
    nginx/
        ├── files  存放静态的文件
        │   └── fstab
                    拷贝文件到该目录
        ├── handlers  存放需要触发的任务,里面必须main.yml文件
        │   └── main.yml
                    - name: restart
                      service: name=nginx state=restarted
        ├── tasks   存放的执行的任务 ,里面必须main.yml文件
        │   ├── copyfile.yml
                    - name: copyfile
                      tempalte: dest=/etc/nginx/nginx.conf
                      tags: copy
                      notify: restart
        │   ├── install.yml
                    - name: installnginx
                      yum: name=nginx
        │   └── start.yml
                    - name: start
                      service: name=nginx state=started
        │   ├── main.yml
                    - import_tasks: install.yml
                    - import_tasks: copyfile.yml
                    - import_tasks: start.yml
        ├── templates 存放的模板文件
        │   ├── centos6.conf
                    拷贝nginx.conf到该目录下并修改
        │   └── nginx.conf
                    拷贝nginx.conf到该目录下并修改
                        修改:worker_processes {{ansible_processor_vcpus*2}}
                             worker_connections 102400
        └── vars 存放的是参数,里面必须main.yml文件
            └── main.yml
                    {port: 90}
    
# 入口文件
nginx.yml:
     - hosts: web
      remote_user: root
      roles:
      - nginx
启动方式:在data目录下

    语法检查:ansible-playbook --syntax-check nginx.yml

    启动:ansible-playbook nginx.yml

查找顺序:

- 先查找当前目录下roles目录里面指定的对应文件夹
- 找tasks目录下面的main.yml文件,如果import_tasks 就导入
- 如果遇到了templates,去找templates文件夹下面的对应文件
- 如果遇到了notify,去找handlers里面的main.yml文件
- 如果遇到了copy,去找files里面的对应文件
- 如果看到了变量,如果是setup收集的变量就去setup,如果不是就去vars里面的main.yml文件查找

 

 

 

 

posted @ 2019-06-02 21:40  海予心  阅读(237)  评论(0编辑  收藏  举报