Ansible安装及简单使用备注
1、安装epel源;
rpm -ivh https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm
2、安装:
yum install ansible -y
完成后执行:ansible --version
ansible 2.3.1.0
config file = /etc/ansible/ansible.cfg
configured module search path = Default w/o overrides
python version = 2.7.5 (default, Nov 6 2016, 00:28:07) [GCC 4.8.5 20150623 (Red Hat 4.8.5-11)]
3、生成节点用的秘钥:
ssh-keygen
拷贝秘钥至节点服务器:
ssh-copy-id -i root@115.XXX.XXX.XXX
4、修改/etc/ansible/hosts文件,增加被控节点的IP地址, [test-nodes]为用户组
[test-nodes]
115.XXX.XXX.XXX
测试环境:
ansible -m ping 'test-nodes'
返回:
115.XXX.XXX.XXX | SUCCESS => {
"changed": false,
"ping": "pong"
}
5、常用命令:
5.0 概述
ansible -m MOD_NAME -a MOD_ARGS
MOD_NAME 代表模块名称 MOD_ARGS 代表传入模块的参数
5.1 执行命令
备注:shell支持管道,command不支持
ansible 'test-nodes' -m command -a 'ifconfig'
ansible 'test-nodes' -m shell -a 'ifconfig|grep eth0'
5.2 拷贝文件
ansible 'test-nodes' -m copy -a 'src=./node.yaml dest=/home mode=664 backup=yes'
备注:backup代表拷贝前将原文件备份
5.3 定时操作
ansible 'test-nodes' -m cron -a 'name="make dir" minute="3" hour="11" job="mkdir /home/test01 > /dev/null"'
备注:11:03分时执行一个名为make dir的任务,执行任务为:mkdir /home/test01
5.4 服务管理
ansible 'test-nodes' -m service -a 'name=tomcat state=restart enabled=no'
5.5 rsync命令
ansible 'test-nodes' -m synchronize -a ' src=/home dest=/home'
6、ansible-palybook
- hosts: test-nodes
remote_user: root
tasks:
- name: install nginx
yum: name=nginx state=latest
tags: install
执行命令:ansible-playbook test.yml,目标机器将安装nginx,playbook支持的语法能够满足较复杂运维需求,如下发配置文件等,本文不做赘述。