ansible学习之基础篇【ad-hoc&ansible-playbook基础操作】

1.ad-hoc

  • ansible.cfg文件打开ssh key check参数:
    ansible test -m yum -a "name=bind state=present"
  • 一般ansible远程连接机器执行命令时都是提前先将master与机器之间配置无密码登陆,但是其实hosts主机文件中也是可以设置携带密码进行远程主机操作的,如下:
    [test]
    192.168.1.4 ansible_ssh_pass=123456
  • 远程执行命令
  • ansible中存在一个名为ping的模块,该模块并不是测试服务器的网络是否连接,而是尝试建立ssh连接,以便验证用户的ssh是否已经正确配置。
  • command是ansible的默认模块,当我们省略-m参数时,默认使用command模块
ansible test -m command -a "hostname"
ansible test -m ping
  • 远程主机文件拷贝
ansible test -m copy -a "src=/tmp/sunwei dest=/etc/"
  • 修改文件的所有者和权限
ansible test -m copy -a "src=/tmp/sunwei dest=/etc/"
  • 远程主机安装&卸载软件
ansible test -m yum -a "name=bind state=present"
ansible test -m yum -a "name=bind state=absent"
  • 服务的停止、启动、重启、重新加载
ansible all -m service -a "name=httpd state=started"  #启动
ansible all -m service -a "name=httpd state=stopped"  #停止
ansible all -m service -a "name=httpd state=restarted"  #重启
ansible all -m service -a "name=httpd state=reloaded"  #重新加载

2.ansible-playbook

将ad-hoc方式所编写的命令写入一个yaml文件中,使用ansible-playbllk执行文件被称为ansible-playbook

  • 一个简单的小例子
cat playbook.yaml
---
- hosts: test
  tasks:
  #拷贝文件
  - name: copy file
    copy: src=/tmp/sunwei dest=/tmp/

  #拷贝文件
  - name: install softeare
    #使用变量
    yum: name={{item}} state=absent
    with_items:
    - bind
    - httpd
#执行命令
ansible-playbool playbook.yaml

3.灵活定义hosts内容

下面举几个小例子,解释一般如何定义hosts文件内容

  • 范例1 直接将ip或者主机名写入
cat /etc/asnible/hosts
192.168.1.1
192.168.1.2
test1.example.com
test2.example.com
执行ad-hoc命令时用法:
- ansible 192.168.1.* -m ping
- ansible * -m ping
- ansible all  -m ping
- ansible test*.example.com
  • 范例2 将主机进行分组
[webserver]
192.168.1.1
192.168.1.2
192.168.1.3
[dbserver]
192.168.1.4
192.168.1.5
192.168.1.6
执行ad-hoc命令时用法:
- ansible webserver -m ping
- ansible dbserver -m ping
- ansible all -m ping 
  • 远程服务器匹配规则如下表
规则含义
192.168.0.1或web.example.com匹配目标ip地址或者服务器主机名,如果有多个ip,使用:分隔
webserver匹配目标组为webserver,多个使用:分隔
*或者all匹配所有服务器
webserver:!dbserver匹配在webserver中,不在dbserver中
webserver:&dbserver同时匹配在webserver中和在dbserver中
.example.com或192.168.1.使用通配符进行匹配
webserver[0],webserver[1:]使用索引或者切片进行匹配
~(web竖线db).*.example.com以~开头的匹配,表示使用正则表达式匹配

未完待续…

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值