CentOS 7 x86_64 Minimal

配置网络:

vi /etc/sysconfig/network-scripts/ifcfg-eth0
NAME=eth0
TYPE=Ethernet
ONBOOT=yes
BOOTPROTO=static
IPADDR=172.16.4.243
GATEWAY=172.16.4.254
NETMASK=255.255.255.0
DNS1=114.114.114.114
systemctl restart network

安装 ansible:

easy_install simplejson
easy_install pip
yum install gcc python-devel
easy_install ansible
pip list

自动把远程主机的公钥加入known_hosts:

vi /etc/ssh/ssh_config
StrictHostKeyChecking no
systemctl reload sshd

设置无密码ssh访问远程主机:

ssh-keygen -t rsa
ssh-copy-id -i ~/.ssh/id_rsa.pub root@172.16.4.247

编辑远程主机列表:

主机列表可以是静态配置文件,也可以通过external inventory scripts动态获取,通过 -i 选项指定。

vi ~/hosts
# hosts
[test]
172.16.4.247

测试远程主机的运行状态:

ansible all -i ~/hosts -m ping

YUM安装软件:

ansible all -i ~/hosts -m yum -a 'name=libselinux-python state=present'

复制文件到远程主机并执行:

ansible all -i ~/hosts -m copy -a 'src=test.sh dest=/root'
ansible all -i ~/hosts -a 'bash test.sh'

ansible api example:

#!/usr/bin/python
import ansible.runner
import sys
# construct the ansible runner and execute on all hosts
results = ansible.runner.Runner(
    host_list='/root/hosts',
    pattern='*', forks=10,
    module_name='command', module_args='which systemctl',
).run()
if results is None:
   print "No hosts found"
   sys.exit(1)
print "\033[32mUP ***********\033[0m"
for (hostname, result) in results['contacted'].items():
    if not 'failed' in result:
        if len(result['stdout']):
            print "%s >>>stdout: %s" % (hostname, result['stdout'])
        if len(result['stderr']):
            print "%s >>>stderr: %s" % (hostname, result['stderr'])
print "\033[31mFAILED *******\033[0m"
for (hostname, result) in results['contacted'].items():
    if 'failed' in result:
        print "%s >>> %s" % (hostname, result['msg'])
print "\033[33mDOWN *********\033[0m"
for (hostname, result) in results['dark'].items():
    print "%s >>> %s" % (hostname, result)