ansible
2018-01-17 本文已影响296人
AEGQ
参考
示例:
- 配置免密登陆
第一步:
生成密匙对ssh-keygen -t rsa 直接默认值
第二步:
ssh-copy-id -i ~/.ssh/id_rsa.pub root@10.****
- 添加节点(参考)
# IP地址或主机名
$ vim /etc/ansible/hosts
[test]
10.***
10.***
- 获取模块列表:
$ ansible-doc -l
- 获取指定模块的使用帮助:
$ ansible-doc -s ping
- ping 模块: 测试主机联通性
# all 或者 * 表示所有主机
$ ansible all -m ping
基本模块
- command 模块: 在远程主机执行命令(不支持管道命令)
$ ansible test -m command -a hostname
或
$ ansible test -a hostname
- shell模块: 调用shell解释器,支持各种shell命令,例如管道等
注:command和shell模块的核心参数直接为命令本身;而其它模块的参数通常为“key=value”格式;
$ ansible test -m shell -a 'ls -al ~|grep ssh'
- copy模块:复制文件到远程主机
# 注: 远程目录可以不存在
$ ansible test -m copy -a "src=/root/get-pip.py dest=/tm/test/test/"
- file模块:设置文件的属性
# 修改文件的权限
$ ansible test -m file -a "path=/tm/test/test/get-pip.py mode=666"
# 创建文件的软连接
$ ansible test -m file -a "src=/tm/test/test/get-pip.py path=/tm/test/test/get-pip.py.link state=link"
# 删除文件
$ ansible test -m file -a "path=/tm/test/test/get-pip.py state=absent"
- fetch模块:从远程主机拿文件
$ ansible 10.**** -m fetch -a "src=/tmp/test/test/get-pip.py dest=/root/ansible"
- cron模块:管理计划任务条目
# 增加计划任务
$ ansible test -m cron -a "minute='*/5' job='/usr/sbin/ntpdate 10.**** &>/dev/null' name='sync time' "
# 删除计划任务
$ ansible test -m cron -a "name='sync time' state=absent"
- hostname模块:管理主机名
# 获取主机名
$ ansible test -a "hostname"
#修改主机名
$ ansible 10.**** -m hostname -a "name=ubuntu"
- yum模块:使用yum命令完成程序包管理
# 安装
$ ansible all -m yum -a "name=samba"
# 卸载
$ ansible all -m yum -a "name=samba state=absent"
- service模块:服务管理
# 开启httpd服务,并且设置为开机启动
$ ansible test -m service -a "name=httpd state=started enabled=true
PlayBook
核心元素:
Tasks:任务,由模块定义的操作的列表;
Variables:变量
Templates:模板,即使用了模板语法的文本文件;
Handlers:由特定条件触发的Tasks;
Roles:角色;
playbook的基础组件:
Hosts:运行指定任务的目标主机;
remote_user:在远程主机以哪个用户身份执行;
sudo_user:非管理员需要拥有sudo权限;
tasks:任务列表
模块,模块参数:
格式:
1) action: module arguments
2) module: arguments
运行playbook,使用ansible-playbook命令
1) 检测语法
ansible-playbook --syntax-check /path/to/playbook.yaml
2) 测试运行 (-C表示仅测试跑一边,但是不会实际操作)
ansible-playbook -C /path/to/playbook.yaml --list-hosts -list-tasks --list-tags
3) 运行
ansible-playbook /path/to/playbook.yaml -t TAGS, --tags=TAGS --skip-tags=SKIP_TAGS --start-at-task=START_AT