CentOS 7.3 Python2.7 下ansible的安装、配置及简单的例子

本文介绍了在Python环境下使用Ansible进行运维开发的相关内容。包括使用Python2.7安装Ansible的两种方式,生成密钥对、配置Ansible、安装sshpass,还给出了测试方法,最后介绍了Ansible的copy模块使用以及远程分发并执行脚本的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.安装
ansible支持python2.7, python3现在支持的不是很好,所以用python2.7安装ansible
a)配置epel源
wget http://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
rpm -ivh epel-release-latest-7.noarch.rpm
yum -y install ansible

b)源码安装:
yum install gcc -y
yum install gcc-c++ -y
yum install autoconf -y                
yum install python-devel -y        
yum install libffi-devel -y                        
yum install openssl-devel -y                

下载ansible-2.3.1.0.tar.gz
tar xf ansible-2.3.1.0.tar.gz
安装ansible:
cd ansible-2.3.1.0
python setup.py install 

查看ansible:
ansible --version 
    
2.生成密钥对(免秘钥交互)

#生成秘钥
ssh-keygen -t rsa -p ''
    
#拷贝秘钥到客户组
ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.4.2
ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.4.2
ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.4.4
    
主机:
cat  ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys  
chmod 600 ~/.ssh/authorized_keys
    

3.ansible配置:
a)拷贝ansible源码examples/ansible.cfg, examples/ansible.cfg到/etc/ansible/目录下:
cp -rf examples/ansible.cfg /etc/ansible/
cp -rf examples/ansible.cfg /etc/ansible/

vim ansible.cfg
host_key_checking = False
inventory      = /etc/ansible/hosts

vim /etc/ansible/hosts
[targets]
localhost              ansible_connection=local
#other1.example.com     ansible_connection=ssh        ansible_user=mpdehaan
#other2.example.com     ansible_connection=ssh        ansible_user=mdehaa
192.168.4.2             ansible_connection=ssh    ansible_port=22    ansible_user=root    ansible_ssh_pass=aaa
192.168.4.3             ansible_connection=ssh    ansible_port=22    ansible_user=root    ansible_ssh_pass=aaa
192.168.4.4             ansible_connection=ssh    ansible_port=22    ansible_user=root    ansible_ssh_pass=aaa

4.sshpass安装
tar xvzf sshpass-1.06.tar.gz
cd sshpass-1.06
./configure
make
make install

4.测试
ansible all -m ping 
ansible targets -a 'uptime'
ansible targets  -m command -a  'w'
ansible targets  -a 'pwd'

5.ansible的使用
a)copy模块
使用copy模块,可以将本地文件一键复制到远程服务器; -a后跟上参数,参数中指定本地文件和远端路径;
ansible targets -m copy -a "src=~/ansible-2.3.1.0.tar.gz dest=~/ansible-2.3.1.0.tar.gz"

b)ansible远程分发并执行脚本
首次按创建一个简单的脚本:
vim  /tmp/test.sh

#!/bin/bash
echo  `date` > /tmp/ansible_test.txt

然后,将脚本分发到各个服务器:
ansible targets -m copy -a "src=~/test.sh dest=~/test.sh" 
执行脚本:
ansible targets -m command -a "sh ~/test.sh"
ansible targets -m shell -a "sh ~/test.sh"

转载于:https://my.oschina.net/michaelshu/blog/1334887

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值