3

这是我所拥有的,我知道这无需加密即可运行,我可以运行

ansible-vault 编辑 common.yml

ANSIBLE_VAULT_PASSWORD_FILE=~/.vault_pass.txt

在环境中设置。

from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.playbook import Playbook
from ansible.executor.playbook_executor import PlaybookExecutor

variable_manager = VariableManager()
loader = DataLoader()

inventory = Inventory(loader=loader, variable_manager=variable_manager,  host_list='playbooks/hosts')
playbook_path = 'playbooks/' + PROJECT + '.yml'

Options = namedtuple('Options', ['connection',  'forks', 'become', 'become_method', 'become_user', 'check', 'listhosts', 'listtasks', 'listtags', 'syntax', 'module_path', 'vault_password_file'])
options = Options(connection='ssh', forks=5, become=None, become_method=None, become_user=None, check=False, listhosts=False, listtasks=False, listtags=False, syntax=False, module_path="", vault_password_file=os.environ['ANSIBLE_VAULT_PASSWORD_FILE'])

variable_manager.extra_vars = {'CAP_VERSION': CAP_VERSION, 'cluster': PROJECT + '-' + ENVIRONMENT, 'environ': ENVIRONMENT, 'rpm': rpmSource, 'VRSN': ARTI_BRANCH }

passwords = {}

pbex = PlaybookExecutor(playbooks=[playbook_path], inventory=inventory, variable_manager=variable_manager, loader=loader, options=options, passwords=passwords)
results = pbex.run()

无法解密 common.yml

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/ansible/ansible/lib/ansible/executor/playbook_executor.py", line 125, in run
    all_vars = self._variable_manager.get_vars(loader=self._loader, play=play)
  File "/opt/ansible/ansible/lib/ansible/vars/__init__.py", line 304, in get_vars
    data = preprocess_vars(loader.load_from_file(vars_file))
  File "/opt/ansible/ansible/lib/ansible/parsing/dataloader.py", line 119, in load_from_file
(file_data, show_content) = self._get_file_contents(file_name)
  File "/opt/ansible/ansible/lib/ansible/parsing/dataloader.py", line 178, in _get_file_contents
    data = self._vault.decrypt(data, filename=b_file_name)
  File "/opt/ansible/ansible/lib/ansible/parsing/vault/__init__.py", line 264, in decrypt
raise AnsibleError(msg)
ansible.errors.AnsibleError: Decryption failed on /ansible/playbooks/vars/common.yml
4

1 回答 1

2

在 ansible 2.2.2 中(不确定其他版本,因为 API 可以经常更改):

您可以像这样在 python 脚本中手动设置密码:

loader = DataLoader()
loader.set_vault_password('mypass')

或者您可以从您的保管库密码文件中加载密码:

import os
loader = DataLoader()
with open('{}/.vault_pass.txt'.format(os.path.expanduser('~')), 'r') as file:
    loader.set_vault_password(file.read().splitlines()[0])

您可以跳过导入操作系统,只需输入 .vault_pass.txt 文件的绝对路径即可。

如果您确定您的 ANSIBLE_VAULT_PASSWORD_FILE 已在 env 中设置:

import os
loader = DataLoader()
with open(os.environ['ANSIBLE_VAULT_PASSWORD_FILE'], 'r') as file:
    loader.set_vault_password(file.read().splitlines()[0])
于 2017-04-19T22:34:43.437 回答