###linux ansible动态清单案例
文章目录
使用动态清单模板,修改其内容,要求如下:
(1)node1是test主机组的成员,其中test主机组可以使用变量:
aa=11
bb=22
(2)node2和node3是prod主机组的成员,其中prod主机组可以使用的变量:
cc=33
dd=44
(3)node1还可以使用的变量:nodevar=xxx1
(4)node2还可以使用的变量:nodevar=xxx2
(5)node3还可以使用的变量:nodevar=xxx3
(6)撰写一个test.yml的playbook,要求所有的受控主机输出变量nodevar的值
[student@ansible ansible]$ vim inventory.py
#!/usr/bin/env python3
'''
Example custom dynamic inventory script for Ansible, in Python.
'''
import os
import sys
import argparse
import json
class ExampleInventory(object):
def __init__(self):
self.inventory = {}
self.read_cli_args()
# Called with `--list`.
if self.args.list:
self.inventory = self.example_inventory()
# Called with `--host [hostname]`.
elif self.args.host:
# Not implemented, since we return _meta info `--list`.
self.inventory = self.empty_inventory()
# If no groups or vars are present, return empty inventory.
else:
self.inventory = self.empty_inventory()
print(json.dumps(self.inventory));
# Example inventory for testing.
def example_inventory(self):
return {
'test': {
'hosts': ['node1'],
'vars': {
'aa': '11',
'bb': '22',
}
},
'prod': {
'hosts': ['node2','node3'],
'vars': {
'cc': '33',
'dd': '44'
}
},
'_meta': {
'hostvars': {
'node1': {
'nodevar': 'hmy1'
},
'node2': {
'nodevar': 'hmy2'
},
'node3': {
'nodevar': 'hmy3'
}
}
}
}
# Empty inventory for testing.
def empty_inventory(self):
return {'_meta': {'hostvars': {}}}
# Read the command line args passed to the script.
def read_cli_args(self):
parser = argparse.ArgumentParser()
parser.add_argument('--list', action = 'store_true')
parser.add_argument('--host', action = 'store')
self.args = parser.parse_args()
# Get the inventory.
ExampleInventory()
[student@ansible ansible]$ chmod +x inventory.py
[student@ansible ansible]$ vim test.yml
---
- name: test1 debug
hosts: all
tasks:
- name: debug
debug:
msg: "{{ nodevar }}"
[student@ansible ansible]$ ansible-playbook test.yml -i inventory.py
效果
[student@ansible ansible]$ ansible-playbook test.yml -i inventory.py
PLAY [test1 debug] ***********************************************************************
TASK [Gathering Facts] *******************************************************************
ok: [node3]
ok: [node2]
ok: [node1]
TASK [debug] *****************************************************************************
ok: [node1] => {
"msg": "hmy1"
}
ok: [node2] => {
"msg": "hmy2"
}
ok: [node3] => {
"msg": "hmy3"
}
PLAY RECAP *******************************************************************************
node1 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
node2 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
node3 : ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0