Ansible安装和使用

任何一台服务器都可以做主控端

1、安装epel源:

2、安装软件包:
# yum install ansible

3、设置SSH免密码登录:
## 生成公钥/私钥
# ssh-keygen -t rsa -P ''
## 写入信任文件(将/root/.ssh/id_rsa_storm1.pub分发到其他服务器,并在所有服务器上执行如下指令):
# cat /root/.ssh/id_rsa_storm1.pub >> /root/.ssh/authorized_keys
# chmod 600 /root/.ssh/authorized_keys

4、配置ansible:
# vim /etc/ansible/ansible.cfg
private_key_file = /root/.ssh/id_rsa_storm1  #指定密钥位置
# vim /etc/ansible/hosts
[storm_cluster]    #指定组名

10.223.55.100
10.223.55.101
linuxtoy.org        #指定执行任务的主机,可以是ip,主机名,支持正则表达式

例如:
[1:3].linuxtoy.org # 等价于
1.linuxtoy.org、2.linuxtoy.org、3.linuxtoy.org  
[a:c].linuxtoy.org # 等价于
a.linuxtoy.org、b.linuxtoy.org、c.linuxtoy.org

5、命令使用:
# ansible -i hosts all -m ping -u www
该命令选项的作用分别为:

- -i:指定 inventory 文件,使用当前目录下的 hosts

- all:针对 hosts 定义的所有主机执行,这里也可以指定组名或模式

- -m:指定所用的模块,我们使用 Ansible 内置的 ping 模块来检查能否正常管理远端机器

- -u:指定远端机器的用户

如果返回如下结果:
linuxtoy.org | success >> {  
"changed": false,  
"ping": "pong"  
}
则说明一切正常。

下面我们再看看远端机器的 uptime:
# ansible vps -a 'uptime'
这将输出:
linuxtoy.org | success | rc=0 >>  
11:23:16 up 177 days, 21:19, 0 users, load average: 0.55, 0.45, 0.39
此处我们省略了 -m,Ansible 默认使用 command 模块;-a 指定模块的参数,即执行 uptime命令。

执行安装软件包:
ansible all -m raw -a 'yum -y install python-simplejson'

简单的ansible playbook的例子:
创建用户toy:
# vim user.yml
- name: create user
  hosts : host
  user: root
  gather_facts : false
  vars:
  -  user: "toy"
  tasks:
  - name: create {{ user }}
    user: name="{{ user }}"
# ansible-playbook user.yml

※ 基本命令:
## 用来查看远程主机的一些基本信息
# ansible storm_cluster -m setup

## 用来测试远程主机的运行状态
# ansible storm_cluster -m ping

## 远程文件信息查看
# ansible storm_cluster -m command -a "ls –al /tmp/resolv.conf"

## 将本地文件“/etc/ansible/ansible.cfg”复制到远程服务器
# ansible storm_cluster -m copy -a "src=/etc/ansible/ansible.cfg dest=/tmp/ansible.cfg owner=root group=root mode=0644"

## 在远程主机上执行命令
# ansible storm_cluster -m command -a "uptime"

## 远程执行shell脚本
# ansible storm_cluster -m shell -a "/tmp/rocketzhang_test.sh"

更多模块可以参考:
#ansible-doc –l
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值