>  기사  >  백엔드 개발  >  Python 모듈 라이브러리로 Ansible을 사용하는 방법

Python 모듈 라이브러리로 Ansible을 사용하는 방법

不言
不言원래의
2018-06-02 15:43:482024검색

ansible은 완전한 압축 풀기 및 재생 소프트웨어인 Python 패키지입니다. 클라이언트의 유일한 요구 사항은 SSH와 Python이 있어야 하며, Python-simplejson 패키지가 설치되어 있습니다. 다음 글에서는 ansible을 파이썬 모듈 라이브러리로 활용하는 방법의 예시를 주로 소개합니다. 도움이 필요한 친구들이 참고할 수 있습니다.

머리말

ansible은 Python을 기반으로 개발되었으며 많은 운영 및 유지 관리 도구(puppet, cfengine, Chef, func, fabric)의 장점을 통합하여 배치 시스템을 구현하는 새로운 자동화 운영 및 유지 관리 도구입니다. 구성, 배치 프로그램 배포, 명령 일괄 실행 등의 기능. Ansible은 모듈을 기반으로 작동하며 일괄 배포 기능이 없습니다. 실제로 배치 배포가 가능한 것은 ansible에 의해 실행되는 모듈이며, ansible은 프레임워크만 제공합니다.

주로 포함되는 것:

(1) 연결 플러그인: 모니터링되는 끝과의 통신을 담당합니다.

(2) 호스트 인벤토리: 지정된 작업의 호스트는 구성 파일에서 모니터링을 위해 정의된 호스트입니다.
(3), 다양한 모듈 핵심 모듈, 명령 모듈, 사용자 정의 모듈


(4), 플러그인을 사용하여 로그 이메일 기록과 같은 기능 완료


(5), 플레이북: 작업 시 여러 스크립트 실행 , 필요하지 않은 경우 노드가 한 번에 여러 작업을 실행하도록 할 수 있습니다.

Ansible은 운영 및 유지 관리 도구 중에서 매우 좋은 도구입니다. 개인적으로 마음에 듭니다. 클라이언트를 설치할 필요가 없기 때문에 필요에 따라 yml 파일을 유연하게 구성할 수 있습니다. 어떤 경우에는 Python의 라이브러리 구성 요소로 Ansible을 자신의 스크립트에 작성해야 할 수도 있습니다. 오늘의 스크립트는 Python 스크립트와 Ansible을 결합하는 방법, 즉 Python 스크립트에서 Ansible을 사용하는 방법을 보여줍니다. .차근차근 풀어나가겠습니다.

먼저 첫 번째 예를 살펴보겠습니다.

#!/usr/bin/python 
import ansible.runner
import ansible.playbook
import ansible.inventory
from ansible import callbacks
from ansible import utils
import json
 
# the fastest way to set up the inventory
 
# hosts list
hosts = ["10.11.12.66"]
# set up the inventory, if no group is defined then 'all' group is used by default
example_inventory = ansible.inventory.Inventory(hosts)
 
pm = ansible.runner.Runner(
 module_name = 'command',
 module_args = 'uname -a',
 timeout = 5,
 inventory = example_inventory,
 subset = 'all' # name of the hosts group 
 )
 
out = pm.run()
 
print json.dumps(out, sort_keys=True, indent=4, separators=(',', ': '))

이 예는 Python 스크립트에서 ansible을 통해 시스템 명령을 실행하는 방법을 보여줍니다. 다음으로 yml 파일 도킹을 사용하여 두 번째 예를 살펴보겠습니다. .

간단한 yml 파일의 내용은 다음과 같습니다.

- hosts: sample_group_name
 tasks:
 - name: just an uname
 command: uname -a

플레이북을 호출하는 Python 스크립트는 다음과 같습니다.

#!/usr/bin/python 
import ansible.runner
import ansible.playbook
import ansible.inventory
from ansible import callbacks
from ansible import utils
import json
 
### setting up the inventory
 
## first of all, set up a host (or more)
example_host = ansible.inventory.host.Host(
 name = '10.11.12.66',
 port = 22
 )
# with its variables to modify the playbook
example_host.set_variable( 'var', 'foo')
 
## secondly set up the group where the host(s) has to be added
example_group = ansible.inventory.group.Group(
 name = 'sample_group_name'
 )
example_group.add_host(example_host)
 
## the last step is set up the invetory itself
example_inventory = ansible.inventory.Inventory()
example_inventory.add_group(example_group)
example_inventory.subset('sample_group_name')
 
# setting callbacks
stats = callbacks.AggregateStats()
playbook_cb = callbacks.PlaybookCallbacks(verbose=utils.VERBOSITY)
runner_cb = callbacks.PlaybookRunnerCallbacks(stats, verbose=utils.VERBOSITY)
 
# creating the playbook instance to run, based on "test.yml" file
pb = ansible.playbook.PlayBook(
 playbook = "test.yml",
 stats = stats,
 callbacks = playbook_cb,
 runner_callbacks = runner_cb,
 inventory = example_inventory,
 check=True
 )
 
# running the playbook
pr = pb.run() 
 
# print the summary of results for each host
print json.dumps(pr, sort_keys=True, indent=4, separators=(',', ': '))

위 내용은 Python 모듈 라이브러리로 Ansible을 사용하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.