-
Notifications
You must be signed in to change notification settings - Fork 5
/
hashi_vault_file.py
68 lines (51 loc) · 1.81 KB
/
hashi_vault_file.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/python
# -*- coding: utf-8 -*-
# [..] various imports
# this line must be written exactly that way,
# as Ansible will replace it with the "imported" code
from ansible.module_utils.basic import *
ANSIBLE_HASHI_VAULT_ADDR = 'http://127.0.0.1:8200'
if os.getenv('VAULT_ADDR') is not None:
ANSIBLE_HASHI_VAULT_ADDR = os.environ['VAULT_ADDR']
class HashiVaultFile:
def __init__(self, **kwargs):
try:
import hvac
except ImportError:
raise Exception("Please pip install hvac to use this module")
self.url = kwargs.pop('url')
self.secret = kwargs.pop('secret')
self.token = kwargs.pop('token')
self.client = hvac.Client(url=self.url, token=self.token)
if self.client.is_authenticated():
pass
else:
raise Exception("Invalid Hashicorp Vault Token Specified")
def get(self):
data = self.client.read(self.secret)
if data is None:
raise Exception("The secret %s doesn't seem to exist" % self.secret)
else:
return data['data']['value']
if __name__ == '__main__':
global module
module = AnsibleModule(
argument_spec={
'secret': {'required': True, 'type': 'str'},
'dest': {'required': True, 'type': 'str'},
'token': {'required': False, 'type': 'str'},
},
supports_check_mode=False
)
args = module.params
args['url'] = ANSIBLE_HASHI_VAULT_ADDR
try:
vault_conn = HashiVaultFile(**args)
value = vault_conn.get()
dest_file = os.path.abspath(args['dest'])
text_file = open(dest_file, "w")
text_file.write(value)
text_file.close()
module.exit_json(changed=True, file=dest_file)
except Exception, e:
module.fail_json(msg=str(e))