1- import type { Resource } from "../mir" ;
21import _ from "lodash" ;
32import * as hclTools from "@cdktf/hcl-tools" ;
43import * as iam from "../../common/iam" ;
54import * as prettier from "prettier" ;
5+ import { TerraformParams } from "../params" ;
6+ import { Resource } from "../mir" ;
67
78async function literal ( value : unknown ) : Promise < string > {
89 const json = JSON . stringify ( value , null , 2 ) ;
10+
911 const pretty = await prettier . format ( json , { parser : "json" } ) ;
1012 return pretty . trim ( ) ;
1113}
@@ -18,21 +20,35 @@ function policyDocument(statements: iam.PolicyStatement[]) {
1820 return {
1921 Version : "2012-10-17" ,
2022 Statement : statements . map ( ( statement ) => ( {
21- ...statement ,
2223 Effect : statement . Effect ?? "Allow" ,
24+ ...statement ,
2325 } ) ) ,
2426 } ;
2527}
2628
27- export async function generate ( resources : Record < string , Resource > ) {
28- const parts = [ ] ;
29+ export type TerraformParams = typeof TerraformParams . inferOut ;
30+
31+ export interface TerraformProject {
32+ files : Record < string , string > ;
33+ }
34+
35+ export async function generate (
36+ resources : Record < string , Resource > ,
37+ params : TerraformParams ,
38+ ) : Promise < TerraformProject > {
39+ const parts = [
40+ `locals {
41+ tags = ${ await literal ( params . tags ) }
42+ }` ,
43+ ] ;
2944
3045 for ( const [ id , resource ] of Object . entries ( resources ) ) {
3146 switch ( resource . type ) {
3247 case "aws_iam_role" : {
3348 parts . push (
34- `resource "aws_iam_role" "${ id } " {
35- name = "${ resource . name } "
49+ `resource "aws_iam_role" ${ literal ( id ) } {
50+ name = ${ literal ( resource . name ) }
51+ tags = local.tags
3652 assume_role_policy = ${ await jsonencode ( policyDocument ( [ resource . assumeRolePolicy ] ) ) }
3753 }` ,
3854 ) ;
@@ -49,7 +65,7 @@ export async function generate(resources: Record<string, Resource>) {
4965 ) ;
5066
5167 parts . push (
52- `resource "aws_iam_role_policy" " ${ id } " {
68+ `resource "aws_iam_role_policy" ${ literal ( id ) } {
5369 role = aws_iam_role.${ id } .name
5470 name = each.key
5571 policy = jsonencode(
@@ -79,9 +95,13 @@ export async function generate(resources: Record<string, Resource>) {
7995 . replaceAll ( "{{account_id}}" , "${local.account_id}" )
8096 . replaceAll ( / \{ \{ ( .* ) \} \} / g, "${$1}" ) ;
8197
82- console . log ( await hclTools . format ( content ) ) ;
83- }
98+ const formatted = ( await hclTools . format ( content ) ) . trim ( ) ;
99+
100+ console . log ( formatted ) ;
84101
85- function camelCaseToSnakeCase ( str : string ) : string {
86- return str . replace ( / ( [ a - z ] ) ( [ A - Z ] ) / g, "$1_$2" ) . toLowerCase ( ) ;
102+ return {
103+ files : {
104+ "main.tf" : formatted ,
105+ } ,
106+ } ;
87107}
0 commit comments