1 ansible
ansible test_back -m shell -a "ls /"
ansible test_back -s -m copy -a "src=/www/s.jar dest=/www/"
ansible test_back -s -m copy -a "src=/www/s.jar dest=/www/ owner=www group=www mode=0755"
1.1 command模块
ansible test -m command -a "free -m"
command模块执行的目录不支持管道符
1.2 shell模块
ansible test -m shell -a "ps aux | grep test | grep -v grep | awk '{print \$2}'"
执行远程目录,支持管道符
1.3 script模块
ansible test -m script -a "/data/test.sh"
将本地脚本拷到目标机器上运行
1.4 stat模块
ansible test -m stat -a "path=/etc/sysctl.conf"
查看远程服务器上对应文件的权限、修改时间、md5值等
1.5 copy模块
ansible test -m copy -a "src=/data/tmp dest=/usr/local/src/" #拷贝整个目录
ansible test -m copy -a "src=/data/a.log dest=/usr/local/src/ " #拷贝单个文件
ansible test -m copy -a "src=/data/a.log dest=/usr/local/src/ backup=yes"
ansible test -s -m copy -a "src=/data/a.log dest=/usr/local/src/ owner=www group=www mode=0755"
拷贝本地文件到目标机器上
1.6 fetch模块
ansible test -m fetch -a "src=/data/md5_command/check_command.sh dest=/tmp/tmp"
拷贝远程文件到本机,并以主机名/绝对路径的方式存放到dest目录下。
1.7 ping模块
ansible test -m ping
查看主机icmp探测存活情况
2 ansible/hosts
指定客户端的ssh服务器IP
ansible_ssh_host=1.1.1.1
指定客户端的ssh端口
ansible_ssh_port=22
指定SSH连接的用户名
ansible_ssh_user=test
指定SSH连接使用的私钥文件
ansible_ssh_private_key_file=/home/test/.ssh/id_rsa
指定客户端使用的python版本
ansible_python_interpreter=/usr/bin/python2.7
3 ansible.cfg
inventory = /etc/ansible/hosts #读取的资源主机配置文件路径
forks = 10 #子进程数
sudo_user = root #默认ssh连接的用户名
remote_port = 22 #默认ssh连接的端口号
timeout = 10 #SSH连接超时时间
4 ansible-playbook
4.1 拷贝远程文件到本地
vim test.yml
- hosts: test
remote_user: root
tasks:
- name: fetch file from test
fetch:
src: /data/top/top.sh
dest: /tmp/tmp
5 故障排查
报错1:"Aborting, target uses selinux but python bindings (libselinux-python) aren't installed!"
解决方法:yum -y install libselinux-python
报错2:"Error: ansible requires a json module, nonefound!",
解决方法:升级python到2.6以上或安装python-simplejson模块
报错3:" File "/root/.ansible/tmp/ansible-tmp-1525327539.64-115053760778831/command", line 746\n except OSError, e:\n ^\nSyntaxError: invalid syntax"
python版本不兼容,修改/etc/ansible/hosts,如下,指定调用客户端指定版本的python
192.168.1.1 ansible_python_interpreter=/usr/bin/python2.7
报错3:{'msg': 'failed to transfer file to /home/manage/.ansible/tmp/ansible-tmp-1547540507.02-52047814599088/college_host_info.py:\n\nConnecting to 192.168.1.2...\nConnection closed\r\n'
/etc/ansible/ansible.cfg
在[ssh_connection]下面添加如下2个参数
pipelining = True
scp_if_ssh = True
6 ansible api
6.1 api 1.x
#-*- coding=utf-8 -*-
#-*- encoding:utf-8 -*-
import ansible.runner
def run_ansible_cmd(
hosts = "",
module = "shell",
command = ""):
"""
call ansible API
"""
run1 = ansible.runner.Runner(
pattern = hosts,
module_name = module,
module_args = command,
#become = True,
#become_user = 'root',
forks = 10)
rs = run1.run()
if rs.has_key("contacted") and rs['contacted']:
return rs['contacted']
else:
return False
6.2 api 2.x
#-*- coding=utf-8 -*-
#-*- encoding:utf-8 -*-
import shutil
from ansible.module_utils.common.collections import ImmutableDict
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
from ansible.plugins.callback import CallbackBase
from ansible import context
import ansible.constants as C
class ResultCallback(CallbackBase):
def __init__(self):
self.rs = {}
def v2_runner_on_ok(self, result, **kwargs):
self.rs[result._host] = result._result
def v2_runner_on_unreachable(self, result):
self.rs[result._host] = result._result
def v2_runner_on_failed(self, result, ignore_errors=False):
self.rs[result._host] = result._result
def get_rs(self):
return self.rs
def run_ansible_cmd(hosts = "", module = "shell", command = ""):
context.CLIARGS = ImmutableDict(
connection = 'local',
forks = 10,
become = None,
become_method = None,
become_user = None,
check = False,
diff = False)
loader = DataLoader()
inventory = InventoryManager(loader, sources = "/etc/ansible/hosts")
variable_manager = VariableManager(
loader = loader,
inventory = inventory
)
play_source = dict(
name = "Ansible Runner",
hosts = hosts,
gather_facts = 'no',
tasks = [
dict(
action = dict(module = module, args = command),
register = 'shell_out'
)
]
)
play = Play().load(
play_source,
variable_manager = variable_manager,
loader = loader
)
tqm = None
results_callback = ResultCallback()
try:
tqm = TaskQueueManager(
inventory = inventory,
variable_manager = variable_manager,
loader = loader,
passwords = {},
stdout_callback = results_callback
)
result = tqm.run(play)
finally:
if tqm is not None:
tqm.cleanup()
shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)
return results_callback.get_rs()
网友评论