ansible--待完善

126 阅读9分钟

1.安装

#1.安装
    #centos7.9
        yum -y install ansible
        ansible --version
   	#ubuntu1804-安装最新版
        apt update
        apt install software-properties-common
        apt-add-repository --yes --update ppa:ansible/ansible
        apt install ansible
        ansible --version

2.配置文件

#2.配置文件
	#修改主配置文件
    vim /etc/ansible/ansible.cfg #主配置文件,配置ansible工作特性,也可以在项目的目录中创建此文件, 当前目录下如果也有ansible.cfg,则此文件优先生效,建议每个项目目录下,创建独有的ansible.cfg文 件
        #remote_port   = 22          #目标主机SSH端口,可以在这边修改
        host_key_checking = False     #检查对应服务器的host_key,建议取消此行注释,实现第一次连 接自动信任目标主机
        module_name = shell	   #默认模块,可以修改为shell模块
        log_path = /var/log/ansible.log #开启日志
	#修改主机清单
	 vim /etc/ansible/hosts
        10.0.0.170 ansible_connection=local
        
        [test]  #分类
        10.0.0.171
        10.0.0.173
     #查看主机清单
     [root@centos7 ~]# ansible test --list

3.基于Key验证

#3.基于Key验证
	[root@centos7 ~]# vim ssh_key.sh 
        #!/bin/bash
        IPLIST="
        10.0.0.171
        10.0.0.173"

        rpm -q sshpass &> /dev/null || yum -y install sshpass
        [ -f /root/.ssh/id_rsa ] || ssh-keygen -f /root/.ssh/id_rsa -P ''
        export SSHPASS=shichong
        for IP in $IPLIST;do
         { sshpass -e ssh-copy-id -o StrictHostKeyChecking=no $IP; } &
        done
        wait

4.测试连通

#4.测试连通
   [root@centos7 ~]# ansible all -m ping

5.学习模块

#all执行所有
    [root@centos7 ~]# ansible all -a "chdir=/tmp cremove=/etc/issue  pwd"
    10.0.0.170 | CHANGED | rc=0 >>
    /tmp
    10.0.0.173 | CHANGED | rc=0 >>
    /tmp
    10.0.0.171 | CHANGED | rc=0 >>
    /tmp
    #执行单个
    [root@centos7 ~]# ansible 10.0.0.173 -a "chdir=/tmp pwd"
    10.0.0.173 | CHANGED | rc=0 >>
    /tmp
    #执行分组
    [root@centos7 ~]# ansible test -a "chdir=/tmp pwd"
    10.0.0.170 | CHANGED | rc=0 >>
    /tmp
    10.0.0.171 | CHANGED | rc=0 >>
    /tmp
script 在远程主机上执行本地的脚本
#script 在远程主机上执行本地的脚本   
    [root@centos7 ~]# ansible all -m script -a  "1.sh"

copy把ansible服务器的文件复制到远程主机
#copy   把ansible服务器的文件复制到远程主机   
        #src=本地文件  dest=远程主机路径  backup=yes如果有此文件先备份 
        #owner=shi所有者(远程机器上必须有shi账号)  mode=600权限
    	[root@centos7 ~]# ansible all -m copy -a "src=/root/1.sh dest=/data/ backup=yes"

        [root@centos71 ~]# ll /data/
        total 4
        -rw-r--r-- 1 root root 448 Sep 26 20:33 1.sh
        [root@centos73 ~]# ll /data/
        total 4
        -rw-r--r-- 1 root root 448 Sep 26 20:33 1.sh
fetch 远程主机的文件提取
#fetch  远程主机的文件提取到ansible服务器 不能直接提取文件夹,可以先用archive模块把文件夹打包然后再提取
        [root@centos7 ~]# ansible all -m fetch -a "src=/etc/redhat-release  dest=/data/os"
        [root@centos7 ~]# tree /data/
        /data/
        ├── 1.sh
        └── os
            ├── 10.0.0.170
            │   └── etc
            │       └── redhat-release
            ├── 10.0.0.171
            │   └── etc
            │       └── redhat-release
            └── 10.0.0.173
                └── etc
                    └── redhat-release

file 设置文件属性
#file  设置文件属性  state=touch创建文件  state=absent删  state=directory创建文件夹  state=link软连接
            #创建文件
            [root@centos7 ~]# ansible test -m file -a "path=/data/test.txt state=touch owner=wang mode=755"
            [root@centos7 ~]# ansible test -a "tree /data"
            10.0.0.173 | CHANGED | rc=0 >>
            /data
            ├── 1.sh
            └── test.txt

            0 directories, 2 files
            10.0.0.171 | CHANGED | rc=0 >>
            /data
            ├── 1.sh
            └── test.txt
            #创建文件夹
            [root@centos7 ~]# ansible test -m file -a "path=/data/test state=directory" 
            [root@centos7 ~]# ansible test -a "tree /data"
            10.0.0.173 | CHANGED | rc=0 >>
            /data
            ├── 1.sh
            └── test

            1 directory, 1 file
            10.0.0.171 | CHANGED | rc=0 >>
            /data
            ├── 1.sh
            └── test
            #递归修改目录属性,但不递归至子目录
            ansible all -m file -a "path=/data/mysql state=directory owner=mysql group=mysql"
            #递归修改目录及子目录的属性
            ansible all -m file -a "path=/data/mysql state=directory owner=mysql group=mysql recurse=yes"
            #创建软连接
            [root@centos7 ~]# ansible test -m file -a "src=/data/1.sh path|dest|name=/data/1-link state=link"
            [root@centos7 ~]# ansible test -a "tree /data"
            10.0.0.173 | CHANGED | rc=0 >>
            /data
            ├── 1-link -> /data/1.sh
            ├── 1.sh
            └── test

            1 directory, 2 files
            10.0.0.171 | CHANGED | rc=0 >>
            /data
            ├── 1-link -> /data/1.sh
            ├── 1.sh
            └── test
unarchive 解压缩
#unarchive 解压缩
    #实现有两种用法:
    #1、将ansible主机上的压缩包传到远程主机后解压缩至特定目录,设置copy=yes
    #2、将远程主机上的某个压缩包解压缩到指定路径下,设置copy=no 
        #常见参数
        #copy:默认为yes,当copy=yes,拷贝的文件是从ansible主机复制到远程主机上,如果设置为copy=no,会在远程主机上寻找src源文件
        #remote_src:和copy功能一样且互斥,yes表示在远程主机,不在ansible主机,no表示文件在ansible主机上
        #src:源路径,可以是ansible主机上的路径,也可以是远程主机(被管理端或者第三方主机)上的路径,如果是远程主机上的路径,则需要设置copy=no
        #dest:远程主机上的目标路径
        #mode:设置解压缩后的文件权限

        #理解,copy=yes是默认,copy=yes 时 src=ansible服务器内路径 。copy=no 时 src=远程主机路径
            ansible all -m unarchive -a 'src=/data/foo.tgz dest=/var/lib/foo owner=wang group=bin'
            ansible all -m unarchive -a 'src=/tmp/foo.zip dest=/data copy=no mode=0777'
            ansible all -m unarchive -a 'src=https://example.com/example.zip dest=/data copy=no' 
archive 压缩
#archive 压缩 把远程主机 选择参数:owner=wang mode=0600
       [root@centos7 ~]# ansible test -m archive -a "path=/data/2.txt dest=/data/2.tar.bz2 format=bz2 "
       [root@centos7 ~]# ansible test -a "tree /data"
       10.0.0.171 | CHANGED | rc=0 >>
       /data
       ├── 1-link -> /data/1.sh
       ├── 1.sh
       ├── 2.tar.bz2
       └── 2.txt

       0 directories, 4 files
       10.0.0.173 | CHANGED | rc=0 >>
       /data
       ├── 1-link -> /data/1.sh
       ├── 1.sh
       ├── 2.tar.bz2
       └── 2.txt 
hostname 不建议直接使用
#hostname 不建议直接使用,主机名不能相同 可以用判断条件批量修改主机名
        ansible test -m hostname -a 'name=node18.magedu.com'
cron 计划任务
#cron 计划任务 支持时间:month月,day日,hour时,minute分,weekday周
       #创建任务
       ansible 10.0.0.8 -m cron -a 'hour=2 minute=30 weekday=1-5 name="backup mysql" job=/root/mysql_backup.sh'
       ansible websrvs   -m cron -a "minute=*/5 job='/usr/sbin/ntpdate ntp.aliyun.com &>/dev/null' name=Synctime"
       #禁用计划任务
       ansible websrvs   -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1  &>/dev/null' name=Synctime disabled=yes"
       #启用计划任务
       ansible websrvs   -m cron -a "minute=*/5 job='/usr/sbin/ntpdate 172.20.0.1 &>/dev/null' name=Synctime disabled=no"
       #删除任务
       ansible websrvs -m cron -a "name='backup mysql' state=absent"
       ansible websrvs -m cron -a 'state=absent name=Synctime' 
yum 和 apt
#yum 和 apt
       ansible websrvs -m yum -a 'name=httpd,dd,sl state=present'  #安装
       ansible websrvs -m yum -a 'name=httpd,dd,sl state=absent'   #删除

       ansible websrvs -m apt -a 'name=httpd,dd,sl state=present'  #安装
       ansible websrvs -m apt -a 'name=httpd,dd,sl state=absent'   #删除

       #查看包
       ansible localhost -m yum -a "list=tree"
service 管理服务
#service 管理服务
        #启动服务  state=started启动 state=stopped停止 state=restarted重新启动   enabled=yes开机自启  
        [root@centos7 ~]# ansible test -m service -a "name=httpd state=started"        
user 模块
#user 模块        
       #创建用户
       ansible all -m user -a 'name=user1 comment="test user" uid=2048 home=/app/user1 group=root'
       ansible all -m user -a 'name=nginx comment=nginx uid=88 group=nginx groups="root,daemon" shell=/sbin/nologin system=yes create_home=no home=/data/nginx non_unique=yes'
       #remove=yes表示删除用户及家目录等数据,默认remove=no
       ansible all -m user -a 'name=nginx state=absent remove=yes'       
group 模块
#group 模块
        #创建组
        ansible websrvs -m group  -a 'name=nginx gid=88 system=yes'
        #删除组
        ansible websrvs -m group  -a 'name=nginx state=absent'  
Lineinfile 模块
Replace 模块
Setup 模块
#功能: setup 模块来收集主机的系统信息,这些 facts 信息可以直接以变量的形式使用,但是如果主机较多,
#会影响执行速度,可以使用 gather_facts: no 来禁止 Ansible 收集 facts 信息
debug 模块

6.Playbook

需知:

Playbook 文件时采用YAML语言编写的
YAML 官方网站:www.yaml.org

YAML 语言特性
-     YAML的可读性好
-     YAML和脚本语言的交互性好
-     YAML使用实现语言的数据类型
-     YAML有一个一致的信息模型
-     YAML易于实现
-     YAML可以基于流来处理
-     YAML表达能力强,扩展性好
    
YAML 语法
-     在单一文件第一行,用连续三个连字号“-”开始,还有选择性的连续三个点号(...)用来表示文件的结尾
-     次行开始正常写Playbook的内容,一般建议写明该Playbook的功能
-     使用#号注释代码
-     缩进必须统一,不能空格和tab混用
-     缩进的级别也必须一致,同样的缩进代表同样的级别,程序判别配置的级别是通过缩进结合换行来实现的
-     YAML文件内容是区别大小写的,key/value的值均需大小写敏感
-     多个key/value可同行写也可换行写,同行使用","分隔
-     key后面冒号要加一个空格 如: key: value
-     value可是个字符串,也可是另一个列表
-     YAML文件扩展名通常为yml或yaml
    
YAML 常用数据类型
    scalar 标量
        key对应value
        name: "失忆石"
        age: "不到3岁"
        
    Dictionary 字典
        多个标量组成,用","隔开
        两种写法
            1.account:
                  name: "失忆石"
                  age: "不到3岁"
            2.account: {name: "失忆石", age: "不到3岁"}
    List 列表
        两种写法
            1.account:
                - name: "失忆石"
                - age: "不到3岁"
                - {name: "失忆石", age: "不到3岁"}
            2.account:
                [name: "失忆石", age: "不到3岁", {name: "失忆石", age: "不到3岁"}]
Playbook 核心组件
一个playbook中由多个组件组成,其中所用到的常用组件类型如下:
    Hosts 执行的远程主机列表
    Tasks 任务集,由多个task的元素组成的列表实现,每个task是一个字典
    Variables 内置或自定义变量在playbook中调用
    Templates 模板,可替换模板文件中的变量并实现一些简单逻辑的文件
    Handlers 和 notify 结合使用,由特定条件触发的操作,满足条件方才执行,否则不执行
    tags 标签 指定某条任务执行,用于选择运行playbook中的部分代码。ansible具有幂等性,因此 会自动跳过没有变化的部分,即便如此,有些代码为测试其确实没有发生变化的时间依然会非常地 长。此时,如果确信其没有变化,就可以通过tags跳过此些代码片断
    一个完整的代码块功能需最少元素需包括 name 和 task,一个name只能包括一个task

注:
    hosts组件
            用于指定要执行指定任务的主机,须事先定义在主机清单中
            写法:
                one.shi.com 
                one.shi.com:two.shi.com 
                192.168.1.50 
                192.168.1.* 
                shi:test      #或者,两个组的并集 (shi和test中去重后所有的主机,)
                shi:&test     #与,两个组的交集 (shi与test中相同的主机)
                shi:!test     #在shi组,但不在test组
             案例:
                 -hosts: shi:test
         
   remote_user 组件
            可指定用户,不写默认为root
   
Playbook 命令
ansible-playbook 

--syntax-check      #语法检查,可缩写成--syntax, 相当于bash -n 
-C --check          #模拟执行,只检测可能会发生的改变,但不真正执行操作 
--list-hosts        #列出运行任务的主机 
--list-tags         #列出tag 
--list-tasks        #列出task 
--limit 主机列表     #只针对主机列表中的特定主机执行 
-i INVENTORY        #指定主机清单文件 
-v -vv  -vvv        #显示过程

#只检测可能会发生的改变,但不真正执行操作
ansible-playbook -C hello.yml 
ansible-playbook --limit 10.0.0.171 hello.yml
例:
[root@centos7 data]# cat hello.yml 
---
- hosts: test
  remote_user: root
  #不收集系统信息,提高执行效率,setup模块
  gather_facts: no

  tasks:
   - name: 测试连通ping
     ping:
   - name: hello world
     command: wall "hello world!"

[root@centos7 data]# ansible-playbook  hello.yml 

PLAY [test] ********************************************************************

TASK [测试连通ping] ****************************************************************
ok: [10.0.0.171]
ok: [10.0.0.173]

TASK [hello world] *************************************************************
changed: [10.0.0.171]
changed: [10.0.0.173]

PLAY RECAP *********************************************************************
10.0.0.171                 : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
10.0.0.173                 : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0