ansible 自动化运维,ansible自动化


简介

Ansible 是一个配置管理和应用部署工具,默认通过 SSH 协议管理机器,所以 Ansible 不需要安装客户端程序在服务器上。您只需要将 Ansible 安装在一台服务器,在 Ansible 安装完后,您就可以去管理控制其它服务器。不需要为它配置数据库,Ansible 不会以 daemons 方式来启动或保持运行状态。

安装

为了方便ansible更新,我们使用git安装。

#安装依赖
pip install paramiko PyYAML Jinja2 httplib2 six
git clone git://github.com/ansible/ansible.git --recursive
cd ansible
#加载环境变量,每次关闭终端后需要运行此命令
source ./hacking/env-setup
#创建默认配置文件目录
mkdir /etc/ansible
#拷贝配置文件及inventory文件
cp ansible/examples/ansible.cfg /etc/ansible
cp ansible/examples/hosts /etc/ansible

若有新版本,可按以下更新

git pull --rebase
git submodule update --init --recursive

运行

1.配置文件

vim /etc/ansible/ansible.cfg
#以下为默认配置文件,可根据实际情况更改
[defaults]
#inventory      = /etc/ansible/hosts
#library        = /usr/share/my_modules/
#module_utils   = /usr/share/my_module_utils/
#remote_tmp     = ~/.ansible/tmp
#local_tmp      = ~/.ansible/tmp
#forks          = 5
#poll_interval  = 15
#sudo_user      = root
#ask_sudo_pass = True
#每次提示输入密码
ask_pass      = True
#transport      = smart
#remote_port    = 22
#module_lang    = C
#module_set_locale = False
#打印日志
log_path = /etc/ansible/log/ansible.log
......

第一次运行会要求输入yes来保存指纹,可通过设置ssh_args来避免,如下:

ssh_args = -o ControlMaster=auto -o ControlPersist=60s -o StrictHostKeyChecking=no

2.配置inventory

vim /etc/ansible/hosts
[test]
10.10.1.11 ansible_ssh_user=test ansible_ssh_port=22
10.10.1.12 ansible_ssh_user=test ansible_ssh_port=22

每次输入密码麻烦,可以通过ansible_ssh_user=user 、ansible_ssh_pass=passwd参数来添加用户名密码。

3.运行

#普通用户
ansible test -a "whoami"
SSH password: 
10.10.1.11 | SUCCESS | rc=0 >>
test

10.10.1.12 | SUCCESS | rc=0 >>
test
#su切换用户,先普通用户登录,然后su切换成root
ansible test -b --become-method=su -K -a "ls /root"
SSH password: 
SU password[defaults to SSH password]: 
10.10.1.11 | SUCCESS | rc=0 >>
anaconda-ks.cfg

10.10.1.12 | SUCCESS | rc=0 >>
anaconda-ks.cfg

4.问题解决
(1)Aborting, target uses selinux but python bindings (libselinux-python) aren’t installed!
解决:yum install libselinux-python -y

(2)import simplejson as json,ImportError: No module named simplejson
原因:python版本太低为2.4,需要版本至少2.6以上
解决:

wget  https://www.python.org/ftp/python/2.7.11/Python-2.7.11.tgz
tar -zxvf Python-2.7.11.tgz
cd Python-2.7.11
./configure
make
make install
#删除原来的python2.4软连接
rm -rf /usr/bin/python
rm -rf /usr/bin/python2
#软连接到python2.7
ln -s /usr/local/bin/python2 /usr/bin/python
#由于yum使用python2.4,因此需要按一下更改
vim /usr/bin/yum
#!/usr/bin/python
改为
#!/usr/bin/python2.4

相关内容

    暂无相关文章