我们用过ansible 工具的人都知道,它是一个批量管理的运维工具,类似于Chef,puppet. 但是相比于其他工作ansible比较简单,也很容易入门
注: 如果使用的是CentOs7版本,那么用本地光盘装的ansble是基于Python2版本的,我们这里用的是python,所以可以选择用pip来直接安装
(python3) [root@yanwj python2]# pip install ansible
我这里在华为云上计时买了两台最小配置的机器用于测试(费用约:¥0.2396/时)
#配置免密登录
(python3) [root@yanwj ~]# ssh-keygen
(python3) [root@yanwj ~]# ssh-copy-id [email protected]
(python3) [root@yanwj ~]# ssh-copy-id [email protected]
(python3) [root@yanwj ~]# vim /etc/hosts
139.9.194.172 node1
139.159.247.199 node2
#创建我自己的项目目录
(python3) [root@yanwj ~]# mkdir /myprojects
(python3) [root@yanwj ~]# cd /myprojects/
#写主机清单
(python3) [root@yanwj myprojects]# vim hosts
[test]
node1
node2
(python3) [root@yanwj myprojects]# vim ansible.cfg
[defaults]
inventory = hosts
remote_user = root
(python3) [root@yanwj myprojects]# ansible test -m ping
node1 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
node2 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
1.3.1 华为云买上服务器之后,默认是有yum的所以我们写playbook来安装一个Apache,并且启动,yaml书写模板可以参照 ansible-doc 工具
我一般都是直接复制粘贴,比较方便
(python3) [root@yanwj myprojects]# vim apache.yaml
---
- hosts: test
tasks:
- name: install Apache
yum:
name: httpd
state: installed
- name: Start service
service:
name: httpd
state: started
(python3) [root@yanwj myprojects]# ansible-playbook apache.yaml
PLAY [test] *****************************************************************************************************************************************
TASK [Gathering Facts] ******************************************************************************************************************************
ok: [node1]
ok: [node2]
TASK [install the latest version of Apache] *********************************************************************************************************
changed: [node2]
changed: [node1]
PLAY RECAP ******************************************************************************************************************************************
node1 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
node2 : ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
启动完之后可以手动去测试是否可以访问
((python3) [root@yanwj myprojects]# curl node1
((python3) [root@yanwj myprojects]# curl node2
我们可以去ansible的官方文档里面找到api文档
步骤: 访问https://docs.ansible.com
点击 ansible Documentation
默认选择最新版本,我这是2.7
搜索 Python api
将搜索到的案例复制到新建的py文件里面,可以执行测试
那么接下来就该修改该文件了,我这里将修改完毕的贴出来供大家参考
里面包括一些解释
playbook转Python请看下章
((python3) [root@yanwj ~]#vim
import shutil
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars.manager import VariableManager
from ansible.inventory.manager import InventoryManager
from ansible.playbook.play import Play
from ansible.executor.task_queue_manager import TaskQueueManager
import ansible.constants as C
def adhoc(sources, hosts, module, args):
Options = namedtuple('Options', ['connection', 'module_path', 'forks', 'become', 'become_method', 'become_user', 'check', 'diff'])
# connection是连接方式,共三种 1.local:本地执行指令 2.ssh: 通过ssh连接 3.smart:自动判断
# forks 进程数,同时对n台机器执行
# become连接远程主机的时候要不要切换身份
options = Options(connection='smart', module_path=['/to/mymodules'], forks=10, become=None, become_method=None, become_user=None, check=False, diff=False)
#DataLoader可以自动将文件转成python数据类型
loader = DataLoader() # Takes care of finding and reading yaml, json and ini files
#存储加密密码
passwords = dict(vault_pass='secret')
# 主机清单,有两种形式.一种是用逗号将所有主机分割的字符串,另一种是使用列表将主机清单文件位置包含
inventory = InventoryManager(loader=loader, sources=sources)
# 用于保存变量的管理器
variable_manager = VariableManager(loader=loader, inventory=inventory)
#创建代表play的数据结构
play_source=dict(
name="Ansible Play",
hosts=hosts, # 在哪些主机上执行任务
gather_facts='no',
tasks=[
dict(action=dict(module=module, args=args), register='shell_out'),
dict(action=dict(module='debug', args=dict(msg='{
{shell_out.stdout}}')))
]
)
# 创建一个play对象
play = Play().load(play_source, variable_manager=variable_manager, loader=loader)
# 创建队列任务管理器,用于调度执行play
tqm = None
try:
tqm = TaskQueueManager(
inventory=inventory,
variable_manager=variable_manager,
loader=loader,
options=options,
passwords=passwords,
)
result = tqm.run(play) # most interesting data for a play is actually sent to the callback's methods
finally:
if tqm is not None:
tqm.cleanup()
shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)
if __name__ == '__main__':
adhoc(sources=['/myprojects/hosts'], hosts='test', module='shell', args='id root')
python myansible.py