-
Notifications
You must be signed in to change notification settings - Fork 0
/
kv-cli-summon-provider
executable file
·175 lines (157 loc) · 5.68 KB
/
kv-cli-summon-provider
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from os.path import isfile, join
from os import listdir
from urllib.parse import urlparse
import argparse
import yaml
import json
import inspect
import sys
import os
import glob
import re
import gnupg
gpg = gnupg.GPG()
class KVCli():
def _read_file(self, path, **kwargs):
with open(path, 'r') as myfile:
try:
data = myfile.read()
except:
data = "!!Error reading {0}".format(path)
return data
def get_value(self, path, **kwargs):
result = []
o = urlparse(path)
if o.scheme == 'file':
path = '/' + o.netloc + o.path
if os.path.exists(path) and os.path.isfile(path):
name = path
if kwargs.get('strip', True):
name = path.split('/')[-1]
item = {
"Name": name,
"Value": self._read_file(path)
}
result.append(item)
else:
for filename in glob.iglob(path, recursive=True):
if filename != path:
sub_result = self.get_value(path="file:/"+filename, **kwargs)
if isinstance(sub_result, list):
result = result + sub_result
else:
result.append(sub_result)
if o.scheme == 'gpg':
path = '/' + o.netloc + o.path
if os.path.exists(path) and os.path.isfile(path):
name = path
if kwargs.get('strip', True):
name = path.split('/')[-1]
decrypted = gpg.decrypt(self._read_file(path))
item = {
"Name": name,
"Value": str(decrypted)
}
result.append(item)
if o.scheme == 'ssm':
import boto3
ssm = boto3.client('ssm')
path = '/' + o.netloc + o.path
try:
ssm_parameter = ssm.get_parameter(Name=path,WithDecryption=True)
name = ssm_parameter['Parameter']['Name']
if kwargs.get('strip', True):
name = name.split('/')[-1]
result.append({
"Name": name,
"Value": ssm_parameter['Parameter']['Value']
})
except:
pass
try:
ssm_parameters = ssm.get_parameters_by_path(Path=path,Recursive=True,WithDecryption=True)
for parameter in ssm_parameters['Parameters']:
name = parameter['Name']
if kwargs.get('strip', True):
name = name.split('/')[-1]
result.append({
"Name": name,
"Value": parameter['Value']
})
except:
pass
return result
def set_value(self, path, value, **kwargs):
result = []
o = urlparse(path)
if o.scheme == 'file':
path = '/' + o.netloc + o.path
encrypted_ascii_data = gpg.encrypt(value, [kwargs.get('recipient')])
f = open(path, "w")
f.write(str(encrypted_ascii_data))
f.close()
item = {
"Name": path
}
result.append(item)
if o.scheme == 'ssm':
import boto3
ssm = boto3.client('ssm')
path = '/' + o.netloc + o.path
try:
ssm.put_parameter(Name=path,Value=value,Type='SecureString')
result.append({
"Name": path
})
except:
pass
return result
def parse(self):
parser = argparse.ArgumentParser(description='kv-cli')
actions = parser.add_subparsers(
title="action",
description="action desc",
prog="prog",
dest="action",
help="action help"
)
get_action = actions.add_parser("get")
get_action.add_argument("--strip", action="store_true")
get_action.add_argument('-p', '--path', required=True)
get_action.set_defaults(func=self.get_value)
set_action = actions.add_parser("set")
set_action.add_argument('-p', '--path', required=True)
set_action.add_argument('--value', required=True)
set_action.add_argument('--recipient', required=False)
set_action.set_defaults(func=self.set_value)
args = parser.parse_args(sys.argv[1:])
if args.action == None:
parser.print_help()
exit(1)
argspec = inspect.getfullargspec(args.func)
if argspec.varkw or argspec.defaults or argspec.kwonlyargs or argspec.kwonlydefaults:
# convert args to a dictionary
args_for_func = vars(args)
else:
# get a subset of the dictionary containing just the arguments of func
args_for_func = {k: getattr(args, k) for k in argspec.args}
result = args.func(**args_for_func)
if result != None:
print(json.dumps(result))
def write_and_flush(pipe, message):
pipe.write(message)
pipe.flush()
if __name__ == '__main__':
ctl = KVCli()
if len(sys.argv) <= 1:
write_and_flush(sys.stderr, 'No variable was provided.')
sys.exit(1)
variable = sys.argv[1]
result = ctl.get_value(variable)
value = result[0].get('Value')
if value is None:
write_and_flush(sys.stderr, '{} could not be retrieved'.format(variable))
sys.exit(1)
write_and_flush(sys.stdout, value)