>  기사  >  백엔드 개발  >  Ansible이 Python 모듈 라이브러리로 사용하는 메소드의 예

Ansible이 Python 모듈 라이브러리로 사용하는 메소드의 예

高洛峰
高洛峰원래의
2017-02-21 10:29:431790검색

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

머리말

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

주로 포함됩니다:

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

(2) 호스트 인벤토리: 지정된 운영; 호스트는 구성 파일에 정의된 모니터링 호스트입니다.

(3) 다양한 모듈 핵심 모듈, 명령 모듈, 사용자 정의 모듈

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

(5) 플레이북: 스크립트가 여러 작업을 수행할 때 필요한 경우 노드는 한 번에 여러 작업을 실행할 수 있습니다.

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

첫 번째 예를 살펴보세요.

#!/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=(',', ': '))

Ansible을 Python 모듈 라이브러리로 사용하는 방법에 대한 자세한 관련 기사는 PHP 중국어를 참고하세요. 웹사이트!

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