ansible的配置及常用命令 刘鑫的博客 2019-04-19 16:32:26 3486 收藏 4 分类专栏: linux ansible 文章标签: linux运维 ansible 版权

一、ansible是一款IT自动化和DevOps软件,能实现批量操作系统配置、批量程序部署和批量运行命令等功能。 1、主要功能: 1)自动化部署App 2)自动化管理配置项 3)自动化持续交付 4)自动化(AWS)云服务管理 2、ansible优点 1)只需要SSH和Python即可使用 2)无客户端 3)模块丰富,功能强大 4)上手容易,门槛低 5)基于Python开发,做二次开发更容易 6)使用公司比较多,社区活跃 3、ansible特性 1)模块化设计 2)基于Python语言实现(paramiko、PyYAML半结构化语言、jinja2) 3)其模块支持JSON等标准输出格式,可以采用任何编程语言重写 4)部署简单,易于使用 5)主从模式工作 6)支持自定义模块 7)支持多层部署、支持异构IT环境 二、安装ansible 1、创建6台虚拟机 ip 主机名 192.168.1.30 ansible 192.168.1.31 web1 192.168.1.32 web2 192.168.1.33 db1 192.168.1.34 db2 192.168.1.35 cache

2、创建ansible的yum源 a.准备ansible的rpm安装包及相关依赖包

[root@room9pc01 桌面]# ls /var/ftp/ansible ansible-2.4.2.0-2.el7.noarch.rpm python2-jmespath-0.9.0-3.el7.noarch.rpm python-httplib2-0.9.2-1.el7.noarch.rpm python-paramiko-2.1.1-4.el7.noarch.rpm python-passlib-1.6.5-2.el7.noarch.rpm sshpass-1.06-2.el7.x86_64.rpm

b.创建yum仓库

[root@room9pc01 桌面]#createrepo /var/ftp/ansible [root@room9pc01 桌面]#createrepo --update /var/ftp/ansible

c.搭建yum源

[root@room9pc01 桌面]#vim /etc/yum.repos.d/ansible.repo [ansible] name=ansible baseurl=ftp://192.168.1.254/ansible enabled=1 gpgcheck=0 [rhel7] name=rhel7 baseurl=ftp://192.168.1.254/rhel7 enabled=1 gpgcheck=0

d.将以上创建的ansible的yum文件拷贝至6台虚拟机的/etc/yum.repos.d/目录下

[root@room9pc01 桌面]scp /etc/yum.repos.d/ansible.repo 192.168.1.30:/etc/yum.repos.d/

注:同样操作拷贝文件至其余虚拟机 3、在ansible(192.168.1.30)主机上安装ansible

[root@ansible ~]yum -y install ansible [root@ansible ~]ansible --version //查看ansible版本

4、ansible配置及应用 a.修改/etc/hosts域名解析配置文件

[root@ansible ~]# vim /etc/hosts 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 192.168.1.30 ansible 192.168.1.31 web1 192.168.1.32 web2 192.168.1.33 db1 192.168.1.34 db2 192.168.1.35 cache

注:其余虚拟机执行相同配置 b.修改/etc/ansible/hosts,定义分组

[root@ansible ~]#vim /etc/ansible/hosts [web] //定义的web组 web[1:2]

[db] //定义的db组 db1 db2

[other] //定义的other组 cache

[app:children] //指定子分组(app可改,children不能改),web、db是提前分好的组 web db other

[app:vars] //定义子分组的变量 ansible_ssh_user="root" //定义登陆用户名 ansible_ssh_pass="123456" //定义登陆密码(虚拟机登陆密码)

c.列出定义分组包含的主机

[root@ansible ~]#ansible web --list-host [root@ansible ~]#ansible db --list-host [root@ansible ~]#ansible other --list-host [root@ansible ~]#ansible all --list-host //列出定义的所有主机

d.ansible主机测试ping其他主机

[root@ansible ~]# ansible all -m ping -k //第一次ping需要输入登陆密码(-k) [root@ansible ~]# ansible all -m ping //由于第一次ping成功时,生成了相应的缓存文件(存放在/root/.ansible/cp目录),再次ping则不需要输入密码

e.修改ansible主配置文件/ [root@ansible ~]# vim /etc/ansible/ansible.cfg

[defaults] inventory = /etc/ansible/hosts host_key_checking = False //跳过 ssh 首次连接提示验证

f.ansible多路径,只对当前路径有效

[root@ansible ~]# cd /var/hh //cd到创建任意路径 [root@ansible hh]# vim ansible.cfg //创建主配置文件 [defaults] inventory = myhosts //定义hosts文件路径(本例放在当前,也可以放在其他路径) host_key_checking = False [root@ansible hh]# vim myhosts //创建并定义hosts文件,该文件要放在主配置文件(ansible.cfg)指定的路径 [web] web11 web22 web33 [db] db11 db22 [root@ansible hh]# ansible all --list-host //查看当前路径主配置文件调用hosts文件是否成功

g.批量执行 ansible命令基础:ansible <主机或定义的分组> [选项] -M 指定模块路径 -m 使用模块,默认command模块 -a 模块参数 -i inventory文件路径或可执行脚本 -k 使用交互式登陆密码 -e 定义变量vim -v 详细信息,-vvvv开启debug模式 (1) 简单批量执行命令

[root@ansible ~]#ansible all -m ping [root@ansible ~]#ansible web -m command -a 'free' //批量查看web组主机的内存使用情况 [root@ansible ~]#ansible web -m command -a 'uptime' //批量查看web组主机的cpu负载 [root@ansible ~]#ansible web -m command -a 'df -h' //批量查看磁盘挂载情况

(2) 给所有主机批量部署公钥

[root@ansible ~]#cd /root/.ssh/ [root@ansible .ssh]#ssh-keygen -t rsa -b 2048 -N '' //创建密钥 [root@ansible .ssh]#ansible all -m authorized_key -a "user=root exclusive=true manage_dir=true key='$(< /root/.ssh/id_rsa.pub)'" -k //批量部署密钥,需要输入密码 [root@ansible .ssh]#ansible all -m ping //成功ping通 [root@ansible .ssh]#ansible web -m command -a 'pwd' //无需输入密码即可执行 [root@ansible .ssh]#ssh web1 //免密登陆

(3)批量配置管理 a.常用模块

ansible-doc模块和ping模块
ansible-doc相当于shell的man帮助命令,很重要

[root@ansible ~]#ansible-doc -l //列出所有模块 [root@ansible ~]#ansible-doc 模块名 //查看模块帮助文档 [root@ansible ~]#ansible all -m ping //批量测试连通性

command模块
默认模块,远程执行命令
该模块通过-a跟上要执行的命令可以直接执行,若命令中有如下字符则执行不成功:“<”、">"、"|"、"&"
该模块不启动shell直接在ssh进程中执行,所有使用到shell的命令执行都会失败

[root@ansible ~]#ansible web -m command -a 'ls' [root@ansible ~]#ansible web -m command -a 'top' [root@ansible ~]#ansible web -m command -a 'pwd'

shell和raw模块
shell模块基本用法和command一样,区别是shell模块是通过/bin/sh进行执行命令,可以执行任意命令
raw模块,用法和shell模块一样,可以执行任意命令,区别是raw没有chdir、creates、removes参数

[root@ansible ~]#ansible web -m command -a 'chdir=/tmp touch f1' [root@ansible ~]#ansible web -m shell -a 'chdir=/tmp touch f2' [root@ansible ~]#ansible web -m raw -a 'chdir=/tmp touch f3' //执行出错

script模块
命令比较复杂时,可以通过编写脚本,然后使用script模块批量执行
脚本示例:web1和db2上存在z3用户,要求在所有主机上创建li4用户并设置密码123456,但是z3和li4用户不能同时存在同一台主机上

[root@ansible ~]#vim useradd.sh //创建脚本 id z3 if [ $? != 0 ];then useradd li4 echo 123456 | passwd --stdin li4 fi [root@ansible ~]#ansible all -m script -a './useradd.sh' //批量执行脚本

copy模块
复制文件到远程主机
-src 复制本地文件到远程主机,路径为目录时会递归复制,路径以“/”结尾,只复制目录里的内容,若不以“/”结尾,则复制包含目录在内的整个内容

[root@ansible ~]# mkdir -p /tmp/liu/xx/ [root@ansible ~]# vim /tmp/liu/xx/resolv.conf [root@ansible ~]# ansible all -m copy -a 'src=/tmp/liu/xx/resolv.conf dest=/tmp' //复制本地文件/tmp/liu/xx/resolv.conf至所有主机的/tmp目录下 [root@ansible ~]# ansible all -m copy -a 'src=/tmp/liu dest=/tmp' //复制本地目录tmp/liu及其子文件至所有主机的/tmp目录下

yum模块和service模块
使用yum模块来管理软件包
使用service模块对管理服务的启动、停止、重启和重新加载等操作

[root@ansible ~]#ansible db -m yum -a 'state=installed name=mariadb-server' //给db组主机批量安装mariadb-server相同配置 [root@ansible ~]#ansible db -m yum -a 'state=latest name=httpd' //给db组批量安装最新的apache [root@ansible ~]#ansible db -m yum -a 'state=absent name=httpd' //db组批量卸载apache [root@ansible ~]#ansible db -m service -a 'state=started name=mariadb.service enable=yes' //启动mariadb.sevice并设置开机自启

lineinfile模块和replace模块
类似于sed的一种行编辑替换模块
-path 目的文件
-regexp 正则表达式进行匹配co
-line 替换后结果
-replace 替换后的字符串

[root@ansible ~]#ansible cache -m lineinfile -a 'path=/etc/sysconfig/network-scripts/ifcfg-eth0 regexp="^GATEWAY" line="GATEWAY=192.168.1.1"' //匹配后修改对应行 [root@ansible ~]#ansible cache -m replace -a 'path=/etc/sysconfig/network-scripts/ifcfg-eth0 regexp=".1.1" replace=".1.254"' //匹配后修改对应字符串

b.ansible-playbook是日常应用中使用频率最高的命令、工作机制,通过读取先编写好的playbook文件实现批量管理,可以理解为按一定条件组成的ansible任务集 (1)YAML是一个可读性高,用来表达数据序列的格式,playbook由YAML语言编写。 YAML基础语法:

YAML的结构通过空格来展示
数组使用“- ”来表示(注,-后面有空格)
键值对使用“: ”来表示(注,:后面有空格)
YAML使用一个固定的缩进风格(不能使用Tab)来表示数据层级结构关系
示例1:编写playbook脚本,检测所有主机的连通性

[root@ansible ~]# vim ping.yml //编写playbook的ping检测脚本

  • hosts: all remote_user: root tasks:
    • ping: [root@ansible ~]# ansible-playbook ping.ym //执行playbook的ping检测

示例2:编写playbook脚本,给web组安装apache并修改监听端口为8080,修改ServerName配置,执行apachectl -t命令不报错,设置默认主页hello world,启动服务并开机自启

[root@ansible ~]# vim http.yml //编写脚本

  • hosts: web remote_user: root tasks:
    • name: install Apache //注释说明 yum: //可通过ansible-doc yum查询使用方法,下同 name: httpd state: latest
    • lineinfile: path: /etc/httpd/conf/httpd.conf regexp: '^Listen' line: 'Listen 8080'
    • lineinfile: path: /etc/httpd/conf/httpd.conf regexp: '^#ServerName' line: 'ServerName localhost'
    • copy: src: /root/index.html dest: /var/www/html/index.html owner: apache group: apache mode: 0644
    • service: name: httpd state: started enabled: yes [root@ansible ~]# echo "hello world" > index.html [root@ansible ~]# ansible-playbook http.yml //执行脚本

(2)变量使用 示例3:给所有主机添加z3用户,设置默认密码123456,要求第一次登陆修改密码

[root@ansible ~]# vim user.yml

  • hosts: all remote_user: root vars: user: z3 //定义变量 tasks:
    • name: creat user user: name: "{{user}}"
    • shell: echo 123456 | passwd --stdin "{{user}}"
    • shell: chage -d 0 "{{user}}" //设置用户密码有效期为0 [root@ansible ~]# ansible-playbook user.yml

以上脚本也可以通过传递变量的方式实现,如下:

[root@ansible ~]# vim user.yml

  • hosts: cache remote_user: root vars: tasks:
    • name: creat user user: name: "{{user}}"
    • shell: echo 123456 | passwd --stdin "{{user}}"
    • shell: chage -d 0 "{{user}}" [root@ansible ~]# ansible-playbook plj.yml -e '{"user": "z3"}' //-e表示传递变量

(3)tags标签 给指定的任务定义一个调用标示,表明执行playbook脚本的结束位置 示例4:配置apache配置文件,修改完成后直接结束任务

[root@ansible ~]# vim httpdconf.yml

  • hosts: web remote_user: root tasks:
    • copy: src: httpd.conf dest: /etc/httpd/conf/httpd.conf owner: root group: root mode: 0644 tags: end //定义标签,即脚本结束位置
    • name: reloadhttp service: name: httpd state: restarted [root@ansible ~]# ansible-playbook httpdconf.yml --tags=end

(4)handlers触发操作

当关注的资源发生变化时采取的操作
notify可用于在每个play的最后被触发,在所有的变化完成后一次性地执行指定操作
notify中列出的操作称为handler,即notify调用handler中name定义的操作
多个tasks触发同一个notify的时候,同一个服务只会触发一次
案例5:拷贝apache配置文件,若配置文件内容发生修改则重启服务使其生效

[root@ansible ~]# vim httpdconf.yml

  • hosts: web remote_user: root tasks:
    • copy: src: httpd.conf dest: /etc/httpd/conf/httpd.conf owner: root group: root mode: 0644 notify: reloadhttp //定义handler触发操作的监控字符串 handlers: //定义handler操作任务
    • name: reloadhttp service: name: httpd state: restarted [root@ansible ~]# ansible-playbook httpdconf.yml

(5)when条件判断和register变量 when:满足特定条件后触发某一项操作或终止某个行为 register:判断前一个命令的执行结果进行保存,以此做出相应的相应处理 示例6:当系统负载超过0.7时,则关掉httpd

[root@ansible ~]# vim load.yml

  • hosts: web remote_user: root tasks:
    • shell: uptime |awk '{printf("%.2f",$(NF-2))}' register: result
    • service: name: httpd state: stopped when: result.stdout|float > 0.7 [root@ansible ~]# ansible-playbook load.yml

(6)with_items是playbook标准循环,可用于迭代一个列表或字典,通过{{item}}获取每次迭代的值 示例7:创建多个用户,并为不同用户定义不同的组

[root@ansible ~]# vim usersadd.yml

  • hosts: web remote_user: root tasks:
    • user: name: "{{item.name}}" group: "{{item.group}}" password: "{{item.password|password_hash('sha512')}}" with_items:
      • name: nb group: jj password: jj123456
      • name: dd group: hh password: hh654123
      • name: xx group: yy password: yy654321 [root@ansible ~]# ansible-playbook usersadd.yml