Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 19 additions & 11 deletions blastradius/handlers/terraform.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,36 @@
import io
import os
import re
import json

# 3rd party libraries
import hcl # hashicorp configuration language (.tf)
# hcl2json convert hcl to json
import subprocess
from pkg_resources import resource_filename

class Terraform:
"""Finds terraform/hcl files (*.tf) in CWD or a supplied directory, parses
them with pyhcl, and exposes the configuration via self.config."""

def __init__(self, directory=None, settings=None):
self.settings = settings if settings else {}

# handle the root module first...
self.directory = directory if directory else os.getcwd()
#print(self.directory)
self.config_str = ''
self.config_str:str = ''
iterator = iglob( self.directory + '/*.tf')
data = {}

for fname in iterator:
with open(fname, 'r', encoding='utf-8') as f:
self.config_str += f.read() + ' '
config_io = io.StringIO(self.config_str)
self.config = hcl.load(config_io)
out=subprocess.getoutput(["hcl2json {}".format(fname)])
file_data = json.loads(out)
for key in file_data:
if not key in data.keys():
data.update(file_data)
else:
for k,v in file_data[key].items():
data[key][k]=v

self.config = data

# then any submodules it may contain, skipping any remote modules for
# the time being.
Expand Down Expand Up @@ -66,7 +75,6 @@ def __init__(self, directory=None, settings=None):
# fixme path join. eek.
self.modules[name] = Terraform(directory=self.directory+'/'+source, settings=mod)


def get_def(self, node, module_depth=0):

# FIXME 'data' resources (incorrectly) handled as modules, necessitating
Expand All @@ -89,10 +97,10 @@ def get_def(self, node, module_depth=0):
'' : lambda x: '' }
if node.type in types:
return types[node.type](node)

# resources are a little different _many_ possible types,
# nested within the 'resource' field.
else:
return self.config['resource'][node.type][node.resource_name]
except:
return ''
return ''
Loading