gpt4 book ai didi

python - Ansible Inventory 模块覆盖 Python 中的组变量

转载 作者:太空宇宙 更新时间:2023-11-03 17:30:53 25 4
gpt4 key购买 nike

我正在使用 Python 中的 Playbook 和 Inventory 模块运行 Ansible Paybook。例如

import ansible.inventory as ai

inventory = make_inventory(hosts,basedir="ansible")
playbook = PlayBook(
playbook = "ansible/site.yml",
private_key_file = "key.pem",
remote_user = "ec2-user",
remote_pass = None,
become = True,
callbacks = playbook_cb,
runner_callbacks = runner_cb,
stats = stats,
inventory = inventory,
check=False
)
playbook.run()

def make_inventory(hosts,basedir):
inventory = ai.Inventory()
myGroup = ai.group.Group(name="mygroup")
allGroup = inventory.get_group("all")
for h in hosts:
host = ai.host.Host(name=h.ip_address,port=22)
mygroup.add_host(host)
allGroup.add_host(host)
inventory.add_group(mygroup)
inventory.set_playbook_basedir(basedir)
return inventory

此代码从 ansible 目录中的 group_vars 构建一个 Inventory 模块,但我想在将其传递到 Playbook 之前覆盖 Inventory 中的一些变量。我怎样才能做到这一点?

最佳答案

以下内容对我有用:

class TestInventory(ai.Inventory):
def __init__(self,*args,**kwargs):
self.usecache = False
super(self.__class__, self).__init__(*args,**kwargs)

def get_group_variables(self, groupname, update_cached=False, vault_password=None):
if not self.usecache:
super(self.__class__, self).get_group_variables(groupname,update_cached=True)
return self._vars_per_group.get(groupname,{})

def get_group_vars(self, group, new_pb_basedir=False):
if not self.usecache:
return super(self.__class__, self).get_group_vars(group, new_pb_basedir=new_pb_basedir)
return self._vars_per_group.get(group.name,{})

def make_inventory(hosts,basedir):
inventory = TestInventory()
myGroup = ai.group.Group(name="mygroup")
allGroup = inventory.get_group("all")
for h in hosts:
host = ai.host.Host(name=h.ip_address,port=22)
mygroup.add_host(host)
allGroup.add_host(host)
inventory.add_group(mygroup)
inventory.set_playbook_basedir(basedir)
update_vars(inventory)
return inventory

def update_vars(inventory):
# Load variables into the cache
inventory.get_group_variables("mygroup")
inventory.get_group_variables("all")

# Update the group vars in the cache
av = inventory._vars_per_group['all']
av['somevar'] = "something"
av['password'] = "qaz"
mv = inventory._vars_per_group['mygroup']
mv['groupvar'] = "foo"

inventory.usecache = True # dont reload vars from file from now on
basedir = inventory._playbook_basedir
inventory._playbook_basedir = "" # trick set_playbook_basedir into action
inventory.set_playbook_basedir(basedir) # repopulate groups vars from cache

关于python - Ansible Inventory 模块覆盖 Python 中的组变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31868262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com