CentOS 7 x86_64 Minimal
配置网络:
1
|
vi
/etc/sysconfig/network-scripts/ifcfg-eth0
|
1
2
3
4
5
6
7
8
|
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
|
1
|
systemctl restart network
|
安装 ansible:
1
2
3
4
5
|
easy_install simplejson
easy_install pip
yum
install
gcc python-devel
easy_install ansible
pip list
|
自动把远程主机的公钥加入known_hosts:
1
|
vi
/etc/ssh/ssh_config
|
1
|
StrictHostKeyChecking no
|
1
|
systemctl reload sshd
|
设置无密码ssh访问远程主机:
1
2
|
ssh
-keygen -t rsa
ssh
-copy-
id
-i ~/.
ssh
/id_rsa
.pub root@172.16.4.247
|
编辑远程主机列表:
主机列表可以是静态配置文件,也可以通过external inventory scripts动态获取,通过 -i 选项指定。
1
|
vi
~
/hosts
|
1
2
3
|
# hosts
[test]
172.16.4.247
|
测试远程主机的运行状态:
1
|
ansible all -i ~
/hosts
-m
ping
|
YUM安装软件:
1
|
ansible all -i ~
/hosts
-m yum -a
'name=libselinux-python state=present'
|
复制文件到远程主机并执行:
1
2
|
ansible all -i ~
/hosts
-m copy -a
'src=test.sh dest=/root'
ansible all -i ~
/hosts
-a
'bash test.sh'
|
ansible api example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
#!/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)
|
版权声明:原创作品,如需转载,请与作者联系。否则将追究法律责任
本文转自 张斌_青岛 51CTO博客,原文链接:http://blog.51cto.com/qicheng0211/1614369