-
Notifications
You must be signed in to change notification settings - Fork 3
/
generate_docs_pyhcl.py
181 lines (149 loc) · 7.07 KB
/
generate_docs_pyhcl.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
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
176
177
178
179
180
181
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import os.path
import hcl
import hcl2
from lib.color import Bgcolor
from lib.parser import ColoredArgParser
class TFGenerator(object):
TF_HEADER = """# Work with AWS {0} via terraform
A terraform module for making {0}.
## Usage
----------------------
Import the module and retrieve with ```terraform get``` or \
```terraform get --update```. Adding a module resource to your template, e.g. \
`main.tf`:
"""
INPUT_HEADER = "## Module Input Variables\n----------------------"
OUTPUT_HEADER = "\n## Module Output Variables\n----------------------"
AUTHORS = """
## Authors
Created and maintained by [Vitaliy Natarov](https://github.com/SebastianUA). \
An email: [[email protected]]([email protected]).
## License
Apache 2 Licensed. See [LICENSE]\
(https://github.com/SebastianUA/terraform/blob/master/LICENSE) for full details."""
def __init__(self, m_dir, e_dir, hcl_version=1):
self.m_dir, self.e_dir = m_dir, e_dir
self.hcl_version = hcl_version
self.parent_dir = self.get_parent_dir(m_dir)
self.file_out = 'OUTPUT_{}.md'.format(self.parent_dir)
@classmethod
def get_parent_dir(cls, path):
return path.strip().split('/')[-1]
def put_header(self):
examples_file = os.path.join(self.e_dir, "main.tf")
headers = self.TF_HEADER.format(self.parent_dir.upper())
with open(self.file_out, 'w+') as f_out:
f_out.write(headers + "\n")
f_out.write("```\n")
f_main = open(examples_file)
f_out.writelines(f_main.readlines())
f_out.write("```\n\n")
def generate_inputs(self):
tf_file_variables = os.path.join(self.m_dir, 'variables.tf')
if not os.path.isfile(tf_file_variables):
print(Bgcolor.fail('File doesnt exist! Check PATH to module!'))
print(Bgcolor.fail("You're trying to use [{}]".format(self.m_dir)))
raise ValueError()
with open(self.file_out, 'a') as f_out:
f_out.write(self.INPUT_HEADER + "\n")
with open(tf_file_variables) as fp_in:
try:
if self.hcl_version == 1:
obj = hcl.load(fp_in)
for variable in obj['variable']:
description = obj['variable'][variable]['description'] or '""'
default = obj['variable'][variable]['default'] or '""'
if default == None:
default = 'null'
elif default == "":
default = '""'
line = '- `{}` - {} (`default = {}`)\n'.format(variable,
description,
default)
with open(self.file_out, 'a') as f_out:
f_out.write(line)
else:
obj = hcl2.load(fp_in)
for section in obj['variable']:
# Dict contains only a single key, just take it
variable = next(iter(section))
description = section[variable]['description'][0] or '""'
default = section[variable]['default'][0]
if default == None:
default = 'null'
elif default == "":
default = '""'
line = '- `{}` - {} (`default = {}`)\n'.format(variable,
description,
default)
with open(self.file_out, 'a') as f_out:
f_out.write(line)
except ValueError as err:
print(Bgcolor.fail(err))
def generate_outputs(self):
tf_file_output = os.path.join(self.m_dir, 'outputs.tf')
if os.path.isfile(tf_file_output):
with open(self.file_out, 'a') as f_out:
f_out.write(self.OUTPUT_HEADER + "\n")
with open(tf_file_output) as fp_out:
try:
if self.hcl_version == 1:
obj = hcl.load(fp_out)
for output in obj['output']:
description = obj['output'][output]['description'] or '""'
line = '- `{}` - {}'.format(output, description)
with open(self.file_out, 'a') as f_out:
f_out.write(line + '\n')
else:
obj = hcl2.load(fp_out)
for section in obj['output']:
# Dict contains only a single key, just take it
output = next(iter(section))
description = section[output]['description'][0] or '""'
line = '- `{}` - {}'.format(output, description)
with open(self.file_out, 'a') as f_out:
f_out.write(line + '\n')
except ValueError as err:
print(Bgcolor.fail(err))
def put_footer(self):
with open(self.file_out, 'a') as f_out:
f_out.write(self.AUTHORS + "\n")
print('"{0}" file has been created: {1}'.format(self.file_out, os.getcwd()))
def generate(self):
self.put_header()
self.generate_inputs()
self.generate_outputs()
self.put_footer()
def main():
def dir_path(path):
if os.path.isdir(path):
return path
raise ValueError("{} not a directory".format(path))
parser = ColoredArgParser(prog='python3 script_name.py -h',
usage='python3 script_name.py {ARGS}',
add_help=True,
prefix_chars='--/',
epilog='''created by Vitalii Natarov''')
parser.add_argument('--version', action='version', version='v1.0.0')
parser.add_argument('-m', '--modules', dest='m_directory',
help='Set the directory where module exists',
metavar='DIR', type=dir_path, required=True)
parser.add_argument('-e', '--examples', dest='e_directory',
help='Set the directory where example exists',
metavar='DIR', type=dir_path, required=True)
parser.add_argument('--hcl-version', dest='hcl_version',
help='Set version of hcl to use for parsing terraform',
metavar='HCL VERSION', type=int, default=2, choices=[1, 2])
args = parser.parse_args()
tf_generator = TFGenerator(args.m_directory,
args.e_directory,
args.hcl_version)
tf_generator.generate()
print(Bgcolor.green("=" * 60))
print(Bgcolor.green("=" * 25 + " FINISHED " + "=" * 25))
print(Bgcolor.green("=" * 60))
if __name__ == '__main__':
main()