Ansible介绍、安装、远程执行命令、拷贝文件或者目录、远程执行脚本,ansible执行命令


Ansible介绍

不需要安装客户端,通过sshd去通信
基于模块工作,模块可以由任何语言开发
不仅支持命令行使用模块,也支持编写yaml格式的playbook,易于编写和阅读
安装十分简单,centos上可直接yum安装
有提供UI(浏览器图形化)www.ansible.com/tower,收费的
官方文档 http://docs.ansible.com/ansible/latest/index.html
ansible已经被redhat公司收购,它在github上是一个非常受欢迎的开源软件,github地址https://github.com/ansible/ansible
一本不错的入门电子书 https://ansible-book.gitbooks.io/ansible-first-book/

Ansible安装

准备两台机器

test-01 192.168.1.48
test-02 192.168.1.67

只需要在test-01上安装ansible,然后再做ssh密钥认证,使得在test-01 ssh(无密码登录)test-02,也要ssh(无密码登录)test-01
yum install -y ansible

验证:
[root@test-01 ~]# rpm -qa ansible
ansible-2.6.0-1.el7.noarch

vi /etc/ansible/hosts
[testhost]
test-01 #可以写ip地址,这里是写的主机名,但是得写入/etc/hosts
test-02

vi /etc/hosts
192.168.1.48 test-01
192.168.1.67 test-02

Ansible远程执行命令

ansible  testhost -m command -a 'w'
解析:testhost:主机组
-m :后面接模块方法
-a :后面是命令

Ansible拷贝文件或者目录

对testhost 组拷贝文件,目标中的tt不存在时就会创建,存在时就会覆盖原来的内容,写入新的内容
ansible testhost -m copy -a "src=/root/tt.log dest=/tmp/tt owner=root group=root mode=0755"

复制目录,定义所属组,权限为755,当test-02不存在时就会创建,并把shell 传入到/tmp/test-02/下
ansible test-02 -m copy -a "src=/root/shell dest=/tmp/test-02/ owner=root group=root mode=0755"

Ansible远程执行脚本

首先创建一个shell脚本
[root@test-01 opt]# cat /opt/test.sh 
#!/bin/bash
echo date > /tmp/ansible_test.txt

然后把该脚本分发到各个机器上
ansible testhost -m copy -a "src=/opt/test.sh dest=/opt/test.sh mode=0755"

最后是批量执行该shell脚本
ansible testhost -m shell -a "/opt/test.sh"

shell模块,还支持远程执行命令并且带管道
ansible testhost -m shell -a "cat /etc/passwd|wc -l "

相关内容

    暂无相关文章