blueice 发表于 2018-7-30 11:12:43

linux ansible 自动化部署工具

  1. 安装epel
  Centos5: rpm -ivh http://mirrors.sohu.com/fedora-epel/5/x86_64/epel-release-5-4.noarch.rpm
  Centos6: rpm -ivh http://mirrors.sohu.com/fedora-epel/6/x86_64/epel-release-6-8.noarch.rpm
  route add defaultgw 192.168.4.1
  2. 安装Ansible
  yum安装 :   yum install ansible -y
  源码安装:   git clone https://github.com/ansible/ansible.git
  3. ansible 配置及测试
  3.1配置linux主机ssh无密码访问
  主控制端: 1. ssh-keygen -t rsa , 又询问直接按回车即可,将在/root/.ssh 下生成秘钥,其中id_rsa 为私钥,id_rsa.pub为公钥(需要下发到被控主机用户.ssh目录,同时要求重命名成authorized_keys文件)
  2.ssh-copy-id -i /root/.ssh/id_rsa.pub root@192.168.4.34
  3.运行ssh 192.168.4.34 检测, 登录成功, 及秘钥配置ok
  3.2cat /etc/ansible/hosts
     定义主机组
  192.168.4.34    主机可以用域名、ip、别名进行标识
  192.168.4.35
  4. 匹配目标
  ansible <pattern_goes_here> -m <module_name> -a <arguments>
  ansibleqing   -m service -a "name=httpd state=restart"
  <pattern_goes_here> 参数的用法
  192.168.4.34 或www.qing.com匹配目标地址或主机名,多个IP或主机名使用‘:’号分隔
  qing                         匹配目标组为qing, 多个组使用用":" 分隔
  all 或 "*"                   匹配目标所有主机
  ~(web|db).*\.example\.com 或 192.168.1.*   支持正则表达式匹配主机或ip地址
  qing:!192.168.4.34         匹配目标组qing 但是配置192.168.4.34的主机IP
  qing:&ming                  匹配qing和ming 两个群组的交集
  qing:!`excluded`:&`required`支持变量匹配方式
  5. ansible 常用模块及API
  0. 默认模块名为command 所以 -m command 可以省略例: ansible qing -a 'ls /tmp'
  1. ansible qing -m ping   检测主机状态
  2. 模块默认存储目录:/usr/share/ansible/
  3. ansible-doc command可以查看模块使用帮助
  4. 常用模块介绍:
  1. 远程命令模块
  1.1 功能command 作为ansible的默认模块,可以运行远程权限范围内的所有shell命令   ansible qing -m command -a 'free -m'
  script 功能是在远程主机执行主控端存储的shell脚本文件,相当于scp+shell 组合   ansible qing -m script -a '/tmp/qing.sh'
  shell执行远程主机的shell脚本文件    ansible qing -m shell -a '/tmp/ming.sh'
  2. copy模块
  ansible qing -m copy -a 'src=/tmp/fanqing.txt dest=/qing/ owner=root group=root mode=0755'
  copy 控制主机下/tmp/fanqing.txt 到目标主机/qing/下 并改变用户、组、权限
  3. state模块
  ansible qing -m stat -a 'path=/qing/fanqing.txt'
  获取文件状态信息
  4. get_url模块
  ansible qing -m get_url -a 'url=http://www.baidu.com dest=/qing/index.html mode=0440 force=yes'
  5. yum模块
  ansible 192.168.4.34 -m yum -a 'name=httpd state=latest'
  yum安装软件包
  6. cron模块
  ansible 192.168.4.34 -m cron -a "name='check dirs' hour='5,2' job='ls -alh > /dev/null'"
  结果:#Ansible: check dirs
  * 5,2 * * * ls -alh > /dev/null
  7. mount
  ansible 192.168.4.34 -m mount -a 'name=/mnt/data src=/dev/sd0 fstype=ext3 opts=ro state=present'
  8. service 模块
  ansible qing -m service -a 'name=httpd state=started'
  state参数:started,stopped,restarted,reloaded
  9. user模块
  ansible qing -m service -a 'name=qing shell=/bin/bash groups=admins,developers append=yes'
  6. playbook
  handlers
  tasks
  templates
页: [1]
查看完整版本: linux ansible 自动化部署工具