Skip to content

Instantly share code, notes, and snippets.

@endzyme
Created July 11, 2017 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save endzyme/15ed7de9b2cb4949e2dc5e7d7b1a2a92 to your computer and use it in GitHub Desktop.
Save endzyme/15ed7de9b2cb4949e2dc5e7d7b1a2a92 to your computer and use it in GitHub Desktop.
iam to terraform policy document converter
#!/usr/bin/env python3
import json,sys
json_files = sys.argv[1:]
if len(json_files) < 1:
print("Usage: <script>.py <jsonfile1> <jsonfile2>...")
exit(1)
for json_file in json_files:
with open(json_file) as data_file:
data = json.load(data_file)
print('''
data "aws_iam_policy_document" "%s" {
''' % json_file)
for statement in data['Statement']:
if 'Resource' in statement.keys():
resource_name = 'resources'
resource_key = 'Resource'
elif 'NotResource' in statement.keys():
resource_name = 'not_resources'
resource_key = 'NotResource'
if 'Action' in statement.keys():
action_name = 'actions'
action_key = 'Action'
elif 'NotAction' in statement.keys():
action_name = 'not_actions'
action_key = 'NotAction'
if 'Sid' in statement.keys():
sid_name = statement['Sid']
else:
sid_name = ''
if type(statement[action_key]) is list:
actions_output = ','.join([ '"%s"' % (_) for _ in statement[action_key]])
elif type(statement[action_key]) is str:
actions_output = '"%s"' % (statement[action_key])
if type(statement[resource_key]) is list:
resources_output = ','.join([ '"%s"' % (_) for _ in statement[resource_key]])
elif type(statement[resource_key]) is str:
resources_output = '"%s"' % (statement[resource_key])
print('''
statement {
sid = "%s"
effect = "%s"
%s = [%s]
%s = [%s]
''' % (
sid_name,
statement['Effect'],
action_name,
actions_output,
resource_name,
resources_output))
if 'Condition' in statement.keys():
for (cond_key, cond_values) in statement['Condition'].items():
condition_test = cond_key
for (cond_key_filter, cond_key_values) in cond_values.items():
condition_variable = cond_key_filter
if type(cond_key_values) is str:
condition_values = '"%s"' % (cond_key_values)
elif type(cond_key_values) is list:
condition_values = ', '.join(['"%s"' % (_) for _ in cond_key_values])
print('''
condition {
test = "%s"
variable = "%s"
values = [%s]
}''' % (condition_test, condition_variable, condition_values)
)
print(' }\n')
print('''
}
''')
@endzyme
Copy link
Author

endzyme commented Jul 11, 2017

hacked script to make life just a little easier (converting from bespoke iam policies to terraform HCL)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment