├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md └── workflows │ └── nodejs.yml ├── src ├── utils │ ├── types.ts │ ├── constants.ts │ ├── index.ts │ ├── TerraformElement.ts │ └── Util.ts ├── arguments │ ├── index.ts │ ├── Map.ts │ ├── Heredoc.ts │ ├── Attribute.ts │ ├── List.ts │ ├── Function.ts │ └── Argument.ts ├── blocks │ ├── index.ts │ ├── Locals.ts │ ├── Backend.ts │ ├── Moved.ts │ ├── Comment.ts │ ├── Import.ts │ ├── Removed.ts │ ├── Data.ts │ ├── Provider.ts │ ├── Module.ts │ ├── Output.ts │ ├── Variable.ts │ ├── Provisioner.ts │ ├── Resource.ts │ └── Block.ts ├── index.ts └── TerraformGenerator.ts ├── .gitignore ├── test ├── arguments │ ├── __snapshots__ │ │ ├── Attribute.test.ts.snap │ │ ├── Heredoc.test.ts.snap │ │ ├── Argument.test.ts.snap │ │ └── Function.test.ts.snap │ ├── Map.test.ts │ ├── Heredoc.test.ts │ ├── Attribute.test.ts │ ├── Argument.test.ts │ ├── List.test.ts │ └── Function.test.ts ├── blocks │ ├── __snapshots__ │ │ ├── Output.test.ts.snap │ │ ├── Import.test.ts.snap │ │ ├── Removed.test.ts.snap │ │ ├── Comment.test.ts.snap │ │ ├── Provisioner.test.ts.snap │ │ ├── Moved.test.ts.snap │ │ ├── Variable.test.ts.snap │ │ ├── Block.test.ts.snap │ │ ├── Locals.test.ts.snap │ │ ├── Backend.test.ts.snap │ │ └── Data.test.ts.snap │ ├── Output.test.ts │ ├── Backend.test.ts │ ├── Data.test.ts │ ├── Locals.test.ts │ ├── Module.test.ts │ ├── Removed.test.ts │ ├── Variable.test.ts │ ├── Provisioner.test.ts │ ├── Import.test.ts │ ├── Comment.test.ts │ ├── Provider.test.ts │ ├── Moved.test.ts │ ├── Block.test.ts │ └── Resource.test.ts ├── index.ts └── tfg │ ├── Others.test.ts │ ├── __snapshots__ │ └── Others.test.ts.snap │ └── Base.test.ts ├── jest.config.json ├── typedoc.json ├── tsconfig.json ├── .vscode └── settings.json ├── LICENSE ├── package.json ├── .eslintrc.json └── README.md /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: ahzhezhe 2 | -------------------------------------------------------------------------------- /src/utils/types.ts: -------------------------------------------------------------------------------- 1 | export type TerraformArgs = Record; 2 | -------------------------------------------------------------------------------- /src/utils/constants.ts: -------------------------------------------------------------------------------- 1 | export const IDENTIFIER_REGEX = /^[a-zA-Z_\-]{1}[0-9a-zA-Z_\-]*$/; 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | test/__coverage__ 4 | test/__output__ 5 | docs 6 | tryout.ts 7 | tryout.tf 8 | tryout.tfvars 9 | -------------------------------------------------------------------------------- /src/utils/index.ts: -------------------------------------------------------------------------------- 1 | export * from './constants'; 2 | export * from './types'; 3 | export * from './TerraformElement'; 4 | export * from './Util'; 5 | -------------------------------------------------------------------------------- /src/utils/TerraformElement.ts: -------------------------------------------------------------------------------- 1 | export abstract class TerraformElement { 2 | 3 | /** 4 | * To Terraform representation. 5 | */ 6 | abstract toTerraform(): string; 7 | 8 | } 9 | -------------------------------------------------------------------------------- /test/arguments/__snapshots__/Attribute.test.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`Attribute 1`] = `"type.name.x"`; 4 | 5 | exports[`attr 1`] = `"type.name.x"`; 6 | -------------------------------------------------------------------------------- /src/arguments/index.ts: -------------------------------------------------------------------------------- 1 | export * from './Argument'; 2 | export * from './Attribute'; 3 | export * from './Function'; 4 | export * from './Heredoc'; 5 | export * from './List'; 6 | export * from './Map'; 7 | -------------------------------------------------------------------------------- /test/blocks/__snapshots__/Output.test.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`Output 1`] = ` 4 | "output &tfgquot;name&tfgquot;{ 5 | value = &tfgquot;value&tfgquot; 6 | } 7 | 8 | " 9 | `; 10 | -------------------------------------------------------------------------------- /test/blocks/__snapshots__/Import.test.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`Import 1`] = ` 4 | "import{ 5 | to = type.name 6 | id = &tfgquot;id&tfgquot; 7 | provider = arg 8 | } 9 | 10 | " 11 | `; 12 | -------------------------------------------------------------------------------- /test/blocks/__snapshots__/Removed.test.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`Removed 1`] = ` 4 | "removed{ 5 | from = resource.a 6 | lifecycle { 7 | destroy = false 8 | } 9 | } 10 | 11 | " 12 | `; 13 | -------------------------------------------------------------------------------- /test/blocks/__snapshots__/Comment.test.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`Comment 1`] = ` 4 | "# line1 5 | 6 | " 7 | `; 8 | 9 | exports[`Comment multiline 1`] = ` 10 | "# line1 11 | # line2 12 | 13 | # line3 14 | # line4 15 | 16 | " 17 | `; 18 | -------------------------------------------------------------------------------- /test/blocks/__snapshots__/Provisioner.test.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`Provisioner 1`] = ` 4 | "provisioner &tfgquot;local-exec&tfgquot;{ 5 | command = &tfgquot;cmd&tfgquot; 6 | when = destroy 7 | on_failure = fail 8 | } 9 | 10 | " 11 | `; 12 | -------------------------------------------------------------------------------- /jest.config.json: -------------------------------------------------------------------------------- 1 | { 2 | "transform": { 3 | "^.+\\.ts$": "ts-jest" 4 | }, 5 | "testRegex": "test\\.ts$", 6 | "collectCoverage": true, 7 | "coverageDirectory": "./test/__coverage__", 8 | "coveragePathIgnorePatterns": [ 9 | "node_modules", 10 | "test" 11 | ] 12 | } 13 | -------------------------------------------------------------------------------- /test/arguments/Map.test.ts: -------------------------------------------------------------------------------- 1 | import { arg4 } from '..'; 2 | import { Map, map } from '../../src/arguments'; 3 | 4 | test('Map', () => { 5 | expect(new Map(arg4).toTerraform()).toMatchSnapshot(); 6 | }); 7 | 8 | test('list', () => { 9 | expect(map(arg4).toTerraform()).toMatchSnapshot(); 10 | }); 11 | -------------------------------------------------------------------------------- /test/blocks/Output.test.ts: -------------------------------------------------------------------------------- 1 | import { Output } from '../../src/blocks'; 2 | 3 | test('Output', () => { 4 | const output = new Output('name', { value: 'value' }); 5 | expect(output.toTerraform()).toMatchSnapshot(); 6 | expect(() => output.asArgument()).toThrow(); 7 | expect(() => output.attr('attr')).toThrow(); 8 | }); 9 | -------------------------------------------------------------------------------- /test/blocks/__snapshots__/Moved.test.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`To argument 1`] = ` 4 | "moved{ 5 | from = resource.a 6 | to = resource.b 7 | } 8 | 9 | " 10 | `; 11 | 12 | exports[`To resource 1`] = ` 13 | "moved{ 14 | from = resource.a 15 | to = resource.b 16 | } 17 | 18 | " 19 | `; 20 | -------------------------------------------------------------------------------- /test/blocks/__snapshots__/Variable.test.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`Variable 1`] = ` 4 | "variable &tfgquot;name&tfgquot;{ 5 | type = string 6 | default = &tfgquot;value&tfgquot; 7 | } 8 | 9 | " 10 | `; 11 | 12 | exports[`Variable 2`] = `"var.name"`; 13 | 14 | exports[`Variable 3`] = `"var.name.attr"`; 15 | -------------------------------------------------------------------------------- /test/blocks/Backend.test.ts: -------------------------------------------------------------------------------- 1 | import { arg4 } from '..'; 2 | import { Backend } from '../../src/blocks'; 3 | 4 | test('Backend', () => { 5 | const backend = new Backend('name', arg4); 6 | expect(backend.toTerraform()).toMatchSnapshot(); 7 | expect(backend.asArgument().toTerraform()).toMatchSnapshot(); 8 | expect(() => backend.attr('attr')).toThrow(); 9 | }); 10 | -------------------------------------------------------------------------------- /test/blocks/Data.test.ts: -------------------------------------------------------------------------------- 1 | import { arg4 } from '..'; 2 | import { Data } from '../../src/blocks'; 3 | 4 | test('Data', () => { 5 | const data = new Data('type', 'name', arg4); 6 | expect(data.toTerraform()).toMatchSnapshot(); 7 | expect(data.asArgument().toTerraform()).toMatchSnapshot(); 8 | expect(data.attr('attr').toTerraform()).toMatchSnapshot(); 9 | }); 10 | -------------------------------------------------------------------------------- /typedoc.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "terraform-generator - v6", 3 | "out": "docs/terraform-generator-v6", 4 | "entryPoints": [ 5 | "src/index.ts" 6 | ], 7 | "categoryOrder": [ 8 | "TerraformGenerator", 9 | "Block", 10 | "Argument", 11 | "*" 12 | ], 13 | "excludePrivate": true, 14 | "disableSources": true, 15 | "hideGenerator": true 16 | } 17 | -------------------------------------------------------------------------------- /test/blocks/Locals.test.ts: -------------------------------------------------------------------------------- 1 | import { arg4 } from '..'; 2 | import { Locals } from '../../src/blocks'; 3 | 4 | test('Locals', () => { 5 | const locals = new Locals(arg4); 6 | expect(locals.toTerraform()).toMatchSnapshot(); 7 | expect(() => locals.asArgument()).toThrow(); 8 | expect(() => locals.attr('attr')).toThrow(); 9 | expect(locals.arg('arg').toTerraform()).toMatchSnapshot(); 10 | }); 11 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2021", 4 | "module": "commonjs", 5 | "outDir": "dist", 6 | "declaration": true, 7 | "esModuleInterop": true, 8 | "strict": true, 9 | "noImplicitAny": false, 10 | "noImplicitReturns": true, 11 | "experimentalDecorators": true, 12 | "emitDecoratorMetadata": true 13 | }, 14 | "include": [ 15 | "src" 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /test/arguments/Heredoc.test.ts: -------------------------------------------------------------------------------- 1 | import { Heredoc, heredoc } from '../../src/arguments'; 2 | 3 | test('Heredoc', () => { 4 | expect(new Heredoc('x').toTerraform()).toMatchSnapshot(); 5 | expect(new Heredoc({ x: 123 }).toTerraform()).toMatchSnapshot(); 6 | }); 7 | 8 | test('heredoc', () => { 9 | expect(heredoc('x').toTerraform()).toMatchSnapshot(); 10 | expect(heredoc({ x: 123 }).toTerraform()).toMatchSnapshot(); 11 | }); 12 | -------------------------------------------------------------------------------- /test/blocks/Module.test.ts: -------------------------------------------------------------------------------- 1 | import { arg4 } from '..'; 2 | import { Module } from '../../src/blocks'; 3 | 4 | test('Module', () => { 5 | const module = new Module('name', { 6 | source: 'source', 7 | version: '1', 8 | ...arg4 9 | }); 10 | expect(module.toTerraform()).toMatchSnapshot(); 11 | expect(module.asArgument().toTerraform()).toMatchSnapshot(); 12 | expect(module.attr('attr').toTerraform()).toMatchSnapshot(); 13 | }); 14 | -------------------------------------------------------------------------------- /src/blocks/index.ts: -------------------------------------------------------------------------------- 1 | export * from './Block'; 2 | export * from './Backend'; 3 | export * from './Comment'; 4 | export * from './Data'; 5 | export * from './Import'; 6 | export * from './Locals'; 7 | export * from './Module'; 8 | export * from './Moved'; 9 | export * from './Output'; 10 | export * from './Provider'; 11 | export * from './Provisioner'; 12 | export * from './Removed'; 13 | export * from './Resource'; 14 | export * from './Variable'; 15 | -------------------------------------------------------------------------------- /test/blocks/Removed.test.ts: -------------------------------------------------------------------------------- 1 | import { arg } from '../../src/arguments'; 2 | import { Removed } from '../../src/blocks'; 3 | 4 | test('Removed', () => { 5 | const moved = new Removed({ 6 | from: arg('resource.a'), 7 | lifecycle: { 8 | destroy: false 9 | } 10 | }); 11 | expect(moved.toTerraform()).toMatchSnapshot(); 12 | expect(() => moved.asArgument()).toThrow(); 13 | expect(() => moved.attr('attr')).toThrow(); 14 | }); 15 | -------------------------------------------------------------------------------- /test/arguments/__snapshots__/Heredoc.test.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`Heredoc 1`] = ` 4 | "< { 5 | const variable = new Variable('name', { 6 | type: new Argument('string'), 7 | default: 'value' 8 | }); 9 | expect(variable.toTerraform()).toMatchSnapshot(); 10 | expect(variable.asArgument().toTerraform()).toMatchSnapshot(); 11 | expect(variable.attr('attr').toTerraform()).toMatchSnapshot(); 12 | }); 13 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.tabSize": 2, 3 | "editor.detectIndentation": false, 4 | "editor.insertSpaces": true, 5 | "editor.codeActionsOnSave": { 6 | "source.fixAll.eslint": "explicit" 7 | }, 8 | "editor.formatOnSave": true, 9 | "[javascript]": { 10 | "editor.formatOnSave": false 11 | }, 12 | "[typescript]": { 13 | "editor.formatOnSave": false 14 | }, 15 | "files.insertFinalNewline": true, 16 | "files.trimTrailingWhitespace": true 17 | } 18 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: ahzhezhe 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To reproduce** 14 | Steps to reproduce the behavior: 15 | 16 | **Expected behavior** 17 | A clear and concise description of what you expected to happen. 18 | 19 | **Additional context** 20 | Add any other context about the problem here. 21 | -------------------------------------------------------------------------------- /.github/workflows/nodejs.yml: -------------------------------------------------------------------------------- 1 | name: test 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | 8 | runs-on: ubuntu-latest 9 | 10 | strategy: 11 | matrix: 12 | node-version: [16.x] 13 | 14 | steps: 15 | - uses: actions/checkout@v2 16 | - name: Use Node.js ${{ matrix.node-version }} 17 | uses: actions/setup-node@v1 18 | with: 19 | node-version: ${{ matrix.node-version }} 20 | - run: npm ci -f 21 | - run: npm test 22 | env: 23 | CI: true 24 | -------------------------------------------------------------------------------- /test/blocks/Provisioner.test.ts: -------------------------------------------------------------------------------- 1 | import { Argument } from '../../src/arguments'; 2 | import { Provisioner } from '../../src/blocks'; 3 | 4 | test('Provisioner', () => { 5 | const provisioner = new Provisioner('local-exec', { 6 | command: 'cmd', 7 | when: new Argument('destroy'), 8 | on_failure: new Argument('fail') 9 | }); 10 | expect(provisioner.toTerraform()).toMatchSnapshot(); 11 | expect(() => provisioner.asArgument()).toThrow(); 12 | expect(() => provisioner.attr('attr')).toThrow(); 13 | }); 14 | -------------------------------------------------------------------------------- /test/blocks/Import.test.ts: -------------------------------------------------------------------------------- 1 | import { arg4 } from '..'; 2 | import { Argument } from '../../src/arguments'; 3 | import { Import, Resource } from '../../src/blocks'; 4 | 5 | const resource = new Resource('type', 'name', arg4); 6 | 7 | test('Import', () => { 8 | const imp = new Import({ 9 | to: resource, 10 | id: 'id', 11 | provider: new Argument('arg') 12 | }); 13 | expect(imp.toTerraform()).toMatchSnapshot(); 14 | expect(() => imp.asArgument()).toThrow(); 15 | expect(() => imp.attr('attr')).toThrow(); 16 | }); 17 | -------------------------------------------------------------------------------- /test/arguments/__snapshots__/Argument.test.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`.attr 1`] = `"x.y"`; 4 | 5 | exports[`.attr 2`] = `"type.name.attr.y"`; 6 | 7 | exports[`.element 1`] = `"x[0]"`; 8 | 9 | exports[`.element 2`] = `"type.name.attr[0]"`; 10 | 11 | exports[`Argument 1`] = `"x"`; 12 | 13 | exports[`arg 1`] = `"x"`; 14 | 15 | exports[`arg 2`] = `"type.name.attr"`; 16 | 17 | exports[`interpolation 1`] = `"prefix-\${x}-suffix"`; 18 | 19 | exports[`interpolation 2`] = `"prefix-\${type.name.attr}-suffix"`; 20 | -------------------------------------------------------------------------------- /test/blocks/Comment.test.ts: -------------------------------------------------------------------------------- 1 | import { Comment } from '../../src/blocks'; 2 | 3 | test('Comment', () => { 4 | const comment = new Comment('line1'); 5 | expect(comment.toTerraform()).toMatchSnapshot(); 6 | expect(() => comment.asArgument()).toThrow(); 7 | expect(() => comment.attr('attr')).toThrow(); 8 | }); 9 | 10 | test('Comment multiline', () => { 11 | const comment = new Comment(` 12 | line1 13 | line2 14 | 15 | line3 16 | line4 17 | `); 18 | expect(comment.toTerraform()).toMatchSnapshot(); 19 | expect(() => comment.asArgument()).toThrow(); 20 | expect(() => comment.attr('attr')).toThrow(); 21 | }); 22 | -------------------------------------------------------------------------------- /test/blocks/Provider.test.ts: -------------------------------------------------------------------------------- 1 | import { arg4 } from '..'; 2 | import { Provider } from '../../src/blocks'; 3 | 4 | test('Provider', () => { 5 | const provider = new Provider('name', arg4); 6 | expect(provider.toTerraform()).toMatchSnapshot(); 7 | expect(() => provider.asArgument()).toThrow(); 8 | expect(() => provider.attr('attr')).toThrow(); 9 | }); 10 | 11 | test('Provider alias', () => { 12 | const provider = new Provider('name', { ...arg4, alias: 'alias' }); 13 | expect(provider.toTerraform()).toMatchSnapshot(); 14 | expect(provider.asArgument().toTerraform()).toMatchSnapshot(); 15 | expect(() => provider.attr('attr')).toThrow(); 16 | }); 17 | -------------------------------------------------------------------------------- /src/arguments/Map.ts: -------------------------------------------------------------------------------- 1 | import { TerraformArgs, Util } from '../utils'; 2 | import { Argument } from '.'; 3 | 4 | /** 5 | * @category Argument 6 | */ 7 | export class Map extends Argument { 8 | 9 | readonly arguments: TerraformArgs; 10 | 11 | /** 12 | * Construct map. 13 | * 14 | * @param args map values 15 | */ 16 | constructor(args: TerraformArgs) { 17 | super(Util.argumentValueToString(args)!); 18 | this.arguments = args; 19 | } 20 | 21 | } 22 | 23 | /** 24 | * Convenient function to construct new [[Map]]. 25 | * 26 | * @param args map values 27 | * 28 | * @category Argument 29 | */ 30 | export const map = (args: TerraformArgs): Map => new Map(args); 31 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: ahzhezhe 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export { TerraformElement, TerraformArgs } from './utils'; 2 | 3 | export { TerraformGenerator, WriteOptions } from './TerraformGenerator'; 4 | 5 | export { 6 | Block, 7 | Backend, 8 | Comment, 9 | Data, 10 | Import, ImportArgs, 11 | Locals, 12 | Module, ModuleArgs, 13 | Moved, MovedArgs, 14 | Output, OutputArgs, 15 | Provider, 16 | Provisioner, FileProvisionerArgs, LocalExecProvisionerArgs, RemoteExecProvisionerArgs, 17 | Removed, RemovedArgs, 18 | Resource, ResourceToDataOptions, 19 | Variable, VariableArgs 20 | } from './blocks'; 21 | 22 | export { 23 | Argument, arg, 24 | Attribute, attr, 25 | Function, fn, 26 | Heredoc, heredoc, 27 | List, list, 28 | Map, map 29 | } from './arguments'; 30 | -------------------------------------------------------------------------------- /src/arguments/Heredoc.ts: -------------------------------------------------------------------------------- 1 | import { Argument } from '.'; 2 | 3 | /** 4 | * @category Argument 5 | */ 6 | export class Heredoc extends Argument { 7 | 8 | /** 9 | * Construct heredoc argument. 10 | * 11 | * @param content string or object, object will be stringify 12 | */ 13 | constructor(content: string | Record) { 14 | super(`<): Heredoc => new Heredoc(content); 27 | -------------------------------------------------------------------------------- /src/arguments/Attribute.ts: -------------------------------------------------------------------------------- 1 | import { Block } from '../blocks'; 2 | import { Argument } from '.'; 3 | 4 | /** 5 | * @category Argument 6 | */ 7 | export class Attribute extends Argument { 8 | 9 | /** 10 | * Construct block's attribute. 11 | * 12 | * @param block block 13 | * @param attrName attribute name 14 | */ 15 | constructor(block: Block, attrName: string) { 16 | super(`${block.asArgument().toTerraform()}.${attrName.trim()}`); 17 | } 18 | 19 | } 20 | 21 | /** 22 | * Convenient function to construct new block's [[Attribute]]. 23 | * 24 | * @param block block 25 | * @param name attribute name 26 | * 27 | * @category Argument 28 | */ 29 | export const attr = (block: Block, name: string): Attribute => new Attribute(block, name); 30 | -------------------------------------------------------------------------------- /test/blocks/Moved.test.ts: -------------------------------------------------------------------------------- 1 | import { arg } from '../../src/arguments'; 2 | import { Moved, Resource } from '../../src/blocks'; 3 | 4 | test('To argument', () => { 5 | const moved = new Moved({ 6 | from: arg('resource.a'), 7 | to: arg('resource.b') 8 | }); 9 | expect(moved.toTerraform()).toMatchSnapshot(); 10 | expect(() => moved.asArgument()).toThrow(); 11 | expect(() => moved.attr('attr')).toThrow(); 12 | }); 13 | 14 | test('To resource', () => { 15 | const resource = new Resource('resource', 'b'); 16 | const moved = new Moved({ 17 | from: arg('resource.a'), 18 | to: resource 19 | }); 20 | expect(moved.toTerraform()).toMatchSnapshot(); 21 | expect(() => moved.asArgument()).toThrow(); 22 | expect(() => moved.attr('attr')).toThrow(); 23 | }); 24 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | ISC License (ISC) 2 | 3 | Copyright 2020 Chang Zhe Jiet 4 | 5 | Permission to use, copy, modify, and/or distribute this software for any purpose 6 | with or without fee is hereby granted, provided that the above copyright notice 7 | and this permission notice appear in all copies. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH 10 | REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY 11 | AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, 12 | INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM 13 | LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR 14 | OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE 15 | OF THIS SOFTWARE. 16 | -------------------------------------------------------------------------------- /src/blocks/Locals.ts: -------------------------------------------------------------------------------- 1 | import { Argument, Attribute } from '../arguments'; 2 | import { TerraformArgs, Util } from '../utils'; 3 | import { Block } from '.'; 4 | 5 | /** 6 | * @category Block 7 | */ 8 | export class Locals extends Block { 9 | 10 | /** 11 | * Construct locals. 12 | * 13 | * Refer to Terraform documentation on what can be put as arguments. 14 | * 15 | * @param args arguments 16 | */ 17 | constructor(args: TerraformArgs) { 18 | super('locals', [], args); 19 | } 20 | 21 | override asArgument(): Argument { 22 | throw Util.inaccessibleMethod(); 23 | } 24 | 25 | override attr(_name: string): Attribute { 26 | throw Util.inaccessibleMethod(); 27 | } 28 | 29 | arg(name: string): Argument { 30 | return new Argument(`local.${name}`); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /test/blocks/__snapshots__/Block.test.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`Block arguments 1`] = `{}`; 4 | 5 | exports[`Block arguments 2`] = ` 6 | { 7 | "a": 1, 8 | } 9 | `; 10 | 11 | exports[`Block arguments 3`] = ` 12 | { 13 | "a": 0, 14 | "b": 1, 15 | "c": 2, 16 | } 17 | `; 18 | 19 | exports[`Block arguments 4`] = ` 20 | { 21 | "a": 0, 22 | "c": 2, 23 | } 24 | `; 25 | 26 | exports[`Block arguments 5`] = ` 27 | [ 28 | Provisioner { 29 | "blockNames": [ 30 | "local-exec", 31 | ], 32 | "blockType": "provisioner", 33 | "type": "local-exec", 34 | }, 35 | Provisioner { 36 | "blockNames": [ 37 | "remote-exec", 38 | ], 39 | "blockType": "provisioner", 40 | "type": "remote-exec", 41 | }, 42 | ] 43 | `; 44 | 45 | exports[`Block arguments 6`] = `[]`; 46 | -------------------------------------------------------------------------------- /test/arguments/Attribute.test.ts: -------------------------------------------------------------------------------- 1 | import { resource } from '..'; 2 | import { Attribute, attr } from '../../src/arguments'; 3 | import { Block } from '../../src/blocks'; 4 | 5 | test('Attribute invalid args', () => { 6 | expect(() => new Attribute(null as unknown as Block, null as unknown as string)).toThrow(); 7 | expect(() => new Attribute(resource, null as unknown as string)).toThrow(); 8 | expect(() => new Attribute(null as unknown as Block, 'x')).toThrow(); 9 | expect(() => new Attribute(null as unknown as Block, '')).toThrow(); 10 | expect(() => new Attribute(null as unknown as Block, ' ')).toThrow(); 11 | }); 12 | 13 | test('Attribute', () => { 14 | expect(new Attribute(resource, 'x').toTerraform()).toMatchSnapshot(); 15 | }); 16 | 17 | test('attr', () => { 18 | expect(attr(resource, 'x').toTerraform()).toMatchSnapshot(); 19 | }); 20 | -------------------------------------------------------------------------------- /src/blocks/Backend.ts: -------------------------------------------------------------------------------- 1 | import { Argument, Attribute } from '../arguments'; 2 | import { TerraformArgs, Util } from '../utils'; 3 | import { Block } from '.'; 4 | 5 | /** 6 | * @category Block 7 | */ 8 | export class Backend extends Block { 9 | 10 | readonly type: string; 11 | 12 | /** 13 | * Construct backend. 14 | * 15 | * Refer to Terraform documentation on what can be put as type & arguments. 16 | * 17 | * @param type type 18 | * @param args arguments 19 | */ 20 | constructor(type: string, args: TerraformArgs) { 21 | super('backend', [type], args, undefined, true); 22 | 23 | this.type = type; 24 | } 25 | 26 | override asArgument(): Argument { 27 | return new Argument(JSON.stringify(this.type)); 28 | } 29 | 30 | override attr(_name: string): Attribute { 31 | throw Util.inaccessibleMethod(); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/blocks/Moved.ts: -------------------------------------------------------------------------------- 1 | import { Argument, Attribute } from '../arguments'; 2 | import { TerraformElement, Util } from '../utils'; 3 | import { Block } from '.'; 4 | 5 | /** 6 | * @category Block 7 | */ 8 | export interface MovedArgs { 9 | from: TerraformElement; 10 | to: TerraformElement; 11 | } 12 | 13 | /** 14 | * @category Block 15 | */ 16 | export class Moved extends Block { 17 | 18 | /** 19 | * Construct moved. 20 | * 21 | * Refer to Terraform documentation on what can be put as arguments. 22 | * 23 | * @param args arguments 24 | */ 25 | constructor(args: MovedArgs) { 26 | super('moved', [], args); 27 | } 28 | 29 | override asArgument(): Argument { 30 | throw Util.inaccessibleMethod(); 31 | } 32 | 33 | override attr(_name: string): Attribute { 34 | throw Util.inaccessibleMethod(); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /test/arguments/Argument.test.ts: -------------------------------------------------------------------------------- 1 | import { attr } from '..'; 2 | import { Argument, arg } from '../../src/arguments'; 3 | 4 | test('Argument', () => { 5 | expect(new Argument('x').toTerraform()).toMatchSnapshot(); 6 | }); 7 | 8 | test('arg', () => { 9 | expect(arg('x').toTerraform()).toMatchSnapshot(); 10 | expect(attr.toTerraform()).toMatchSnapshot(); 11 | }); 12 | 13 | test('.attr', () => { 14 | expect(arg('x').attr('y').toTerraform()).toMatchSnapshot(); 15 | expect(attr.attr('y').toTerraform()).toMatchSnapshot(); 16 | }); 17 | 18 | test('.element', () => { 19 | expect(arg('x').element(0).toTerraform()).toMatchSnapshot(); 20 | expect(attr.element(0).toTerraform()).toMatchSnapshot(); 21 | }); 22 | 23 | test('interpolation', () => { 24 | expect(`prefix-${arg('x')}-suffix`).toMatchSnapshot(); 25 | expect(`prefix-${attr}-suffix`).toMatchSnapshot(); 26 | }); 27 | -------------------------------------------------------------------------------- /src/blocks/Comment.ts: -------------------------------------------------------------------------------- 1 | import { Argument, Attribute } from '../arguments'; 2 | import { Util } from '../utils'; 3 | import { Block } from '.'; 4 | 5 | /** 6 | * @category Block 7 | */ 8 | export class Comment extends Block> { 9 | 10 | readonly comment: string; 11 | 12 | /** 13 | * Construct comment. 14 | * 15 | * @param comment comment 16 | */ 17 | constructor(comment: string) { 18 | super('comment', [], {}); 19 | 20 | this.comment = comment; 21 | } 22 | 23 | override toTerraform(): string { 24 | return `${this.comment.trim().split('\n').map(line => line.trim() ? `# ${line.trim()}` : '').join('\n')}\n\n`; 25 | } 26 | 27 | override asArgument(): Argument { 28 | throw Util.inaccessibleMethod(); 29 | } 30 | 31 | override attr(_name: string): Attribute { 32 | throw Util.inaccessibleMethod(); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /test/arguments/List.test.ts: -------------------------------------------------------------------------------- 1 | import { arg1, arg2, arg3, arg4 } from '..'; 2 | import { List, list } from '../../src/arguments'; 3 | 4 | test('List', () => { 5 | expect(new List('x', 'y', 'z').toTerraform()).toMatchSnapshot(); 6 | expect(new List(1, 2, 3).toTerraform()).toMatchSnapshot(); 7 | expect(new List(true, false, true).toTerraform()).toMatchSnapshot(); 8 | expect(new List('x', 2, true).toTerraform()).toMatchSnapshot(); 9 | expect(new List(arg1, arg2, arg3, arg4).toTerraform()).toMatchSnapshot(); 10 | }); 11 | 12 | test('list', () => { 13 | expect(list('x', 'y', 'z').toTerraform()).toMatchSnapshot(); 14 | expect(list(1, 2, 3).toTerraform()).toMatchSnapshot(); 15 | expect(list(true, false, true).toTerraform()).toMatchSnapshot(); 16 | expect(list('x', 2, true).toTerraform()).toMatchSnapshot(); 17 | expect(list(arg1, arg2, arg3, arg4).toTerraform()).toMatchSnapshot(); 18 | }); 19 | -------------------------------------------------------------------------------- /src/blocks/Import.ts: -------------------------------------------------------------------------------- 1 | import { Argument, Attribute } from '../arguments'; 2 | import { TerraformElement, Util } from '../utils'; 3 | import { Block } from '.'; 4 | 5 | /** 6 | * @category Block 7 | */ 8 | export interface ImportArgs { 9 | to: TerraformElement; 10 | id: TerraformElement | string; 11 | provider?: Argument; 12 | } 13 | 14 | /** 15 | * @category Block 16 | */ 17 | export class Import extends Block { 18 | 19 | /** 20 | * Construct import. 21 | * 22 | * Refer to Terraform documentation on what can be put as arguments. 23 | * 24 | * @param args arguments 25 | */ 26 | constructor(args: ImportArgs) { 27 | super('import', [], args); 28 | } 29 | 30 | override asArgument(): Argument { 31 | throw Util.inaccessibleMethod(); 32 | } 33 | 34 | override attr(_name: string): Attribute { 35 | throw Util.inaccessibleMethod(); 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/blocks/Removed.ts: -------------------------------------------------------------------------------- 1 | import { Argument, Attribute } from '../arguments'; 2 | import { TerraformElement, Util } from '../utils'; 3 | import { Block } from '.'; 4 | 5 | /** 6 | * @category Block 7 | */ 8 | export interface RemovedArgs { 9 | from: TerraformElement; 10 | lifecycle: { 11 | destroy: boolean; 12 | }; 13 | } 14 | 15 | /** 16 | * @category Block 17 | */ 18 | export class Removed extends Block { 19 | 20 | /** 21 | * Construct removed. 22 | * 23 | * Refer to Terraform documentation on what can be put as arguments. 24 | * 25 | * @param args arguments 26 | */ 27 | constructor(args: RemovedArgs) { 28 | super('removed', [], args); 29 | } 30 | 31 | override asArgument(): Argument { 32 | throw Util.inaccessibleMethod(); 33 | } 34 | 35 | override attr(_name: string): Attribute { 36 | throw Util.inaccessibleMethod(); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/arguments/List.ts: -------------------------------------------------------------------------------- 1 | import { Util } from '../utils'; 2 | import { Argument } from '.'; 3 | 4 | /** 5 | * @category Argument 6 | */ 7 | export class List extends Argument { 8 | 9 | /** 10 | * Construct list. 11 | * 12 | * @param elements list elements 13 | */ 14 | constructor(...elements: any[]) { 15 | super(List.#constructArgument(elements)); 16 | } 17 | 18 | static #constructArgument(elements: any[]): string { 19 | let str = '[\n'; 20 | elements.forEach((element, i) => { 21 | str += `${Util.argumentValueToString(element)}${i < elements.length - 1 ? ',' : ''}\n`; 22 | }); 23 | str += ']'; 24 | return str; 25 | } 26 | 27 | } 28 | 29 | /** 30 | * Convenient function to construct new [[List]]. 31 | * 32 | * @param elements list elements 33 | * 34 | * @category Argument 35 | */ 36 | export const list = (...elements: any[]): List => new List(...elements); 37 | -------------------------------------------------------------------------------- /src/blocks/Data.ts: -------------------------------------------------------------------------------- 1 | import { Argument, Attribute } from '../arguments'; 2 | import { TerraformArgs } from '../utils'; 3 | import { Block } from '.'; 4 | 5 | /** 6 | * @category Block 7 | */ 8 | export class Data extends Block { 9 | 10 | readonly type: string; 11 | readonly name: string; 12 | 13 | /** 14 | * Construct data source. 15 | * 16 | * Refer to Terraform documentation on what can be put as type & arguments. 17 | * 18 | * @param type type 19 | * @param name name 20 | * @param args arguments 21 | */ 22 | constructor(type: string, name: string, args: TerraformArgs) { 23 | super('data', [type, name], args); 24 | 25 | this.type = type; 26 | this.name = name; 27 | } 28 | 29 | override asArgument(): Argument { 30 | return new Argument(`data.${this.type}.${this.name}`); 31 | } 32 | 33 | override attr(name: string): Attribute { 34 | return new Attribute(this, name); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/blocks/Provider.ts: -------------------------------------------------------------------------------- 1 | import { Argument, Attribute } from '../arguments'; 2 | import { TerraformArgs, Util } from '../utils'; 3 | import { Block } from '.'; 4 | 5 | /** 6 | * @category Block 7 | */ 8 | export class Provider extends Block { 9 | 10 | readonly type: string; 11 | 12 | /** 13 | * Construct provider. 14 | * 15 | * Refer to Terraform documentation on what can be put as type & arguments. 16 | * 17 | * @param type type 18 | * @param args arguments 19 | */ 20 | constructor(type: string, args: TerraformArgs) { 21 | super('provider', [type], args); 22 | 23 | this.type = type; 24 | } 25 | 26 | override asArgument(): Argument { 27 | if (this.getArgument('alias')) { 28 | return new Argument(`${this.type}.${this.getArgument('alias')}`); 29 | } 30 | throw new Error('Provider has no alias.'); 31 | } 32 | 33 | override attr(_name: string): Attribute { 34 | throw Util.inaccessibleMethod(); 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/blocks/Module.ts: -------------------------------------------------------------------------------- 1 | import { Argument, Attribute } from '../arguments'; 2 | import { TerraformArgs } from '../utils'; 3 | import { Block } from '.'; 4 | 5 | /** 6 | * @category Block 7 | */ 8 | export interface ModuleArgs extends TerraformArgs { 9 | source: string; 10 | version?: string; 11 | } 12 | 13 | /** 14 | * @category Block 15 | */ 16 | export class Module extends Block { 17 | 18 | readonly name: string; 19 | 20 | /** 21 | * Construct module. 22 | * 23 | * Refer to Terraform documentation on what can be put as arguments. 24 | * 25 | * @param name name 26 | * @param args arguments 27 | */ 28 | constructor(name: string, args: ModuleArgs) { 29 | super('module', [name], args); 30 | 31 | this.name = name; 32 | } 33 | 34 | override asArgument(): Argument { 35 | return new Argument(`module.${this.name}`); 36 | } 37 | 38 | override attr(name: string): Attribute { 39 | return new Attribute(this, name); 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /test/index.ts: -------------------------------------------------------------------------------- 1 | import { Attribute, arg, heredoc, fn, map, list } from '../src/arguments'; 2 | import { Resource } from '../src/blocks'; 3 | 4 | export const resource = new Resource('type', 'name', { test: true }); 5 | 6 | export const attr = new Attribute(resource, 'attr'); 7 | 8 | export const arg1 = { 9 | arg0: 'a', 10 | arg1: ['b', 'c', 'd'], 11 | arg2: 0, 12 | arg3: [1, 2, 3], 13 | arg4: true, 14 | arg5: [false, true, false], 15 | arg6: attr, 16 | arg7: [attr, attr, attr], 17 | arg8: resource, 18 | arg9: [resource, resource, resource], 19 | arg10: ['e', 4, true, attr, resource], 20 | arg11: arg('arg'), 21 | arg12: heredoc('heredoc'), 22 | arg13: fn('fn', 1, 2, 3), 23 | arg14: fn('fn', attr, attr, attr) 24 | }; 25 | 26 | export const arg2 = { 27 | ...arg1, 28 | arg100: arg1 29 | }; 30 | 31 | export const arg3 = { 32 | ...arg2, 33 | arg101: [arg2, arg2, arg2] 34 | }; 35 | 36 | export const arg4 = { 37 | ...arg3, 38 | arg102: map(arg3), 39 | arg103: list(arg3, arg3, arg3) 40 | }; 41 | -------------------------------------------------------------------------------- /src/blocks/Output.ts: -------------------------------------------------------------------------------- 1 | import { Argument, Attribute } from '../arguments'; 2 | import { TerraformArgs, Util } from '../utils'; 3 | import { Block, Resource } from '.'; 4 | 5 | /** 6 | * @category Block 7 | */ 8 | export interface OutputArgs { 9 | value: any; 10 | description?: string; 11 | sensitive?: boolean; 12 | precondition?: TerraformArgs; 13 | depends_on?: Resource[]; 14 | } 15 | 16 | /** 17 | * @category Block 18 | */ 19 | export class Output extends Block { 20 | 21 | readonly name: string; 22 | 23 | /** 24 | * Construct output. 25 | * 26 | * Refer to Terraform documentation on what can be put as arguments. 27 | * 28 | * @param name name 29 | * @param args arguments 30 | */ 31 | constructor(name: string, args: OutputArgs) { 32 | super('output', [name], args); 33 | 34 | this.name = name; 35 | } 36 | 37 | override asArgument(): Argument { 38 | throw Util.inaccessibleMethod(); 39 | } 40 | 41 | override attr(_name: string): Attribute { 42 | throw Util.inaccessibleMethod(); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/blocks/Variable.ts: -------------------------------------------------------------------------------- 1 | import { Argument, Attribute } from '../arguments'; 2 | import { TerraformArgs } from '../utils'; 3 | import { Block } from '.'; 4 | 5 | /** 6 | * @category Block 7 | */ 8 | export interface VariableArgs { 9 | type: Argument; 10 | default?: any; 11 | description?: string; 12 | sensitive?: boolean; 13 | nullable?: boolean; 14 | validation?: TerraformArgs; 15 | } 16 | 17 | /** 18 | * @category Block 19 | */ 20 | export class Variable extends Block { 21 | 22 | readonly name: string; 23 | 24 | /** 25 | * Construct variable. 26 | * 27 | * Refer to Terraform documentation on what can be put as arguments. 28 | * 29 | * @param name name 30 | * @param args arguments 31 | */ 32 | constructor(name: string, args: VariableArgs) { 33 | super('variable', [name], args); 34 | 35 | this.name = name; 36 | } 37 | 38 | override asArgument(): Argument { 39 | return new Argument(`var.${this.name}`); 40 | } 41 | 42 | override attr(name: string): Attribute { 43 | return new Attribute(this, name); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /test/arguments/__snapshots__/Function.test.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`Function 1`] = `"fn()"`; 4 | 5 | exports[`Function 2`] = `"fn(&tfgquot;x&tfgquot;, &tfgquot;y&tfgquot;, &tfgquot;z&tfgquot;)"`; 6 | 7 | exports[`Function 3`] = `"fn(1, 2, 3)"`; 8 | 9 | exports[`Function 4`] = `"fn(true, false, true)"`; 10 | 11 | exports[`Function 5`] = `"fn(&tfgquot;x&tfgquot;, 2, true)"`; 12 | 13 | exports[`Function 6`] = `"fn(&tfgquot;x&tfgquot;, type.name.attr)"`; 14 | 15 | exports[`Function 7`] = ` 16 | "fn(&tfgquot;x&tfgquot;, { 17 | a = 1 18 | b = &tfgquot;2&tfgquot; 19 | })" 20 | `; 21 | 22 | exports[`fn 1`] = `"fn()"`; 23 | 24 | exports[`fn 2`] = `"fn(&tfgquot;x&tfgquot;, &tfgquot;y&tfgquot;, &tfgquot;z&tfgquot;)"`; 25 | 26 | exports[`fn 3`] = `"fn(1, 2, 3)"`; 27 | 28 | exports[`fn 4`] = `"fn(true, false, true)"`; 29 | 30 | exports[`fn 5`] = `"fn(&tfgquot;x&tfgquot;, 2, true)"`; 31 | 32 | exports[`fn 6`] = `"fn(&tfgquot;x&tfgquot;, type.name.attr)"`; 33 | 34 | exports[`fn 7`] = ` 35 | "fn(&tfgquot;x&tfgquot;, { 36 | a = 1 37 | b = &tfgquot;2&tfgquot; 38 | })" 39 | `; 40 | -------------------------------------------------------------------------------- /src/arguments/Function.ts: -------------------------------------------------------------------------------- 1 | import { Util } from '../utils'; 2 | import { Argument } from '.'; 3 | 4 | /** 5 | * @category Argument 6 | */ 7 | export class Function extends Argument { 8 | 9 | /** 10 | * Construct function argument. 11 | * 12 | * @param name function name 13 | * @param args function arguments 14 | */ 15 | constructor(name: string, ...args: any[]) { 16 | super(Function.#constructArgument(name, ...args)); 17 | } 18 | 19 | static #constructArgument(fn: string, ...args: any[]): string { 20 | let str = `${fn}(`; 21 | args.forEach((arg, i) => { 22 | str += Util.argumentValueToString(arg); 23 | if (i < args.length - 1) { 24 | str += ', '; 25 | } 26 | }); 27 | str += ')'; 28 | return str; 29 | } 30 | 31 | } 32 | 33 | /** 34 | * Convenient function to construct new [[Function]]. 35 | * 36 | * @param name function name 37 | * @param args function arguments 38 | * 39 | * @category Argument 40 | */ 41 | // eslint-disable-next-line @typescript-eslint/ban-types 42 | export const fn = (name: string, ...args: any[]): Function => new Function(name, ...args); 43 | -------------------------------------------------------------------------------- /test/arguments/Function.test.ts: -------------------------------------------------------------------------------- 1 | import { attr } from '..'; 2 | import { Function, fn } from '../../src/arguments'; 3 | 4 | test('Function', () => { 5 | expect(new Function('fn').toTerraform()).toMatchSnapshot(); 6 | expect(new Function('fn', 'x', 'y', 'z').toTerraform()).toMatchSnapshot(); 7 | expect(new Function('fn', 1, 2, 3).toTerraform()).toMatchSnapshot(); 8 | expect(new Function('fn', true, false, true).toTerraform()).toMatchSnapshot(); 9 | expect(new Function('fn', 'x', 2, true).toTerraform()).toMatchSnapshot(); 10 | expect(new Function('fn', 'x', attr).toTerraform()).toMatchSnapshot(); 11 | expect(new Function('fn', 'x', { a: 1, b: '2' }).toTerraform()).toMatchSnapshot(); 12 | }); 13 | 14 | test('fn', () => { 15 | expect(fn('fn').toTerraform()).toMatchSnapshot(); 16 | expect(fn('fn', 'x', 'y', 'z').toTerraform()).toMatchSnapshot(); 17 | expect(fn('fn', 1, 2, 3).toTerraform()).toMatchSnapshot(); 18 | expect(fn('fn', true, false, true).toTerraform()).toMatchSnapshot(); 19 | expect(fn('fn', 'x', 2, true).toTerraform()).toMatchSnapshot(); 20 | expect(fn('fn', 'x', attr).toTerraform()).toMatchSnapshot(); 21 | expect(fn('fn', 'x', { a: 1, b: '2' }).toTerraform()).toMatchSnapshot(); 22 | }); 23 | -------------------------------------------------------------------------------- /test/blocks/Block.test.ts: -------------------------------------------------------------------------------- 1 | import { Argument } from '../../src/arguments'; 2 | import { Resource, Provisioner, Output } from '../../src/blocks'; 3 | 4 | test('Block identifier', () => { 5 | expect(() => new Resource('!@#', '$%^')).toThrow(); 6 | expect(() => new Resource('', ' ')).toThrow(); 7 | expect(() => new Output(null as unknown as string, { value: 'value' })).toThrow(); 8 | }); 9 | 10 | test('Block arguments', () => { 11 | const resource = new Resource('type', 'name'); 12 | expect(resource.getArguments()).toMatchSnapshot(); 13 | expect(resource.setArgument('a', 1).getArguments()).toMatchSnapshot(); 14 | expect(resource.setArguments({ 15 | a: 0, 16 | b: 1, 17 | c: 2 18 | }).getArguments()).toMatchSnapshot(); 19 | expect(resource.deleteArgument('b').getArguments()).toMatchSnapshot(); 20 | expect(resource.setProvisioners([ 21 | new Provisioner('local-exec', { 22 | command: 'cmd1' 23 | }), 24 | new Provisioner('remote-exec', { 25 | script: 'cmd2', 26 | when: new Argument('destroy'), 27 | on_failure: new Argument('fail') 28 | }) 29 | ]).getProvisioners()).toMatchSnapshot(); 30 | expect(resource.setProvisioners(undefined).getProvisioners()).toMatchSnapshot(); 31 | }); 32 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "terraform-generator", 3 | "version": "6.4.4", 4 | "author": "Chang Zhe Jiet", 5 | "description": "Generate Terraform configurations with Node.js.", 6 | "keywords": [ 7 | "terraform", 8 | "terraformjs", 9 | "hashicorp", 10 | "node", 11 | "node.js", 12 | "cloud", 13 | "infrastructure", 14 | "infra", 15 | "aws" 16 | ], 17 | "homepage": "https://github.com/ahzhezhe/terraform-generator#readme", 18 | "repository": { 19 | "type": "git", 20 | "url": "https://github.com/ahzhezhe/terraform-generator" 21 | }, 22 | "funding": "https://github.com/sponsors/ahzhezhe", 23 | "license": "ISC", 24 | "files": [ 25 | ".github/FUNDING.yml", 26 | "dist/**/*" 27 | ], 28 | "main": "dist/index.js", 29 | "types": "dist/index.d.ts", 30 | "scripts": { 31 | "lint": "eslint src/*.ts src/**/*.ts test/**/*.ts", 32 | "test": "jest", 33 | "tryout": "ts-node tryout.ts", 34 | "build": "rm -rf dist && tsc", 35 | "build:watch": "tsc -w", 36 | "prepublishOnly": "npm run build", 37 | "postpublish": "rm -rf dist", 38 | "postversion": "git push" 39 | }, 40 | "dependencies": { 41 | "shelljs": "^0.10.0" 42 | }, 43 | "devDependencies": { 44 | "@types/jest": "^29.5.11", 45 | "@types/shelljs": "^0.8.15", 46 | "@typescript-eslint/eslint-plugin": "^5.61.0", 47 | "@typescript-eslint/parser": "^5.61.0", 48 | "eslint": "^8.44.0", 49 | "eslint-plugin-import": "^2.27.5", 50 | "eslint-plugin-security": "^1.7.1", 51 | "jest": "^29.7.0", 52 | "ts-jest": "^29.1.1", 53 | "ts-node": "^10.9.2", 54 | "typedoc": "^0.26.10", 55 | "typescript": "^5.6.3" 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/arguments/Argument.ts: -------------------------------------------------------------------------------- 1 | import { TerraformElement, Util } from '../utils'; 2 | 3 | /** 4 | * @category Argument 5 | */ 6 | export class Argument extends TerraformElement { 7 | 8 | readonly #argument: T; 9 | 10 | /** 11 | * Construct argument. 12 | * 13 | * @param arg argument as string 14 | */ 15 | constructor(arg: T) { 16 | super(); 17 | this.#argument = arg; 18 | } 19 | 20 | /** 21 | * Get argument's attribute. 22 | * 23 | * @param name attribute name 24 | */ 25 | attr(name: string): Argument { 26 | return new Argument(`${this.#argument}.${name.trim()}`); 27 | } 28 | 29 | /** 30 | * Get list argument's element. 31 | * 32 | * @param idx element index 33 | */ 34 | element(idx: number): Argument { 35 | return new Argument(`${this.#argument}[${idx}]`); 36 | } 37 | 38 | /** 39 | * To Terraform representation. 40 | * 41 | * Use this method when argument is used as an interpolation in another Terraform argument or code. 42 | */ 43 | override toTerraform(): string { 44 | return Util.escape(this.#argument); 45 | } 46 | 47 | /** 48 | * To string. 49 | * 50 | * Use this method when argument is used as an interpolation in a Terraform string or heredoc. 51 | * 52 | * It is automatically called when argument is used in template literal. 53 | */ 54 | toString(): string { 55 | return `\${${this.toTerraform()}}`; 56 | } 57 | 58 | } 59 | 60 | /** 61 | * Convenient function to construct new [[Argument]]. 62 | * 63 | * @param arg argument as string or copy from another argument object 64 | * 65 | * @category Argument 66 | */ 67 | export const arg = (arg: T): Argument => new Argument(arg); 68 | -------------------------------------------------------------------------------- /src/blocks/Provisioner.ts: -------------------------------------------------------------------------------- 1 | import { Argument, Attribute, Map } from '../arguments'; 2 | import { Util } from '../utils'; 3 | import { Block } from '.'; 4 | 5 | interface ProvisionerArgs { 6 | when?: Argument<'create' | 'destroy'>; 7 | on_failure?: Argument<'continue' | 'fail'>; 8 | } 9 | 10 | /** 11 | * @category Block 12 | */ 13 | export interface FileProvisionerArgs extends ProvisionerArgs { 14 | source?: string; 15 | content?: string; 16 | destination?: string; 17 | } 18 | 19 | /** 20 | * @category Block 21 | */ 22 | export interface LocalExecProvisionerArgs extends ProvisionerArgs { 23 | command: string; 24 | working_dir?: string; 25 | interpreter?: string[]; 26 | environment?: Map; 27 | quiet?: boolean; 28 | } 29 | 30 | /** 31 | * @category Block 32 | */ 33 | export interface RemoteExecProvisionerArgs extends ProvisionerArgs { 34 | inline?: string[]; 35 | script?: string; 36 | scripts?: string[]; 37 | } 38 | 39 | /** 40 | * @category Block 41 | */ 42 | export class Provisioner extends Block { 43 | 44 | readonly type: 'file' | 'local-exec' | 'remote-exec'; 45 | 46 | /** 47 | * Construct provisioner. 48 | * 49 | * Refer to Terraform documentation on what can be put as type & arguments. 50 | * 51 | * @param type type 52 | * @param args arguments 53 | */ 54 | constructor(type: 'file', args: FileProvisionerArgs); 55 | constructor(type: 'local-exec', args: LocalExecProvisionerArgs); 56 | constructor(type: 'remote-exec', args: RemoteExecProvisionerArgs); 57 | constructor(type: 'file' | 'local-exec' | 'remote-exec', args: FileProvisionerArgs | LocalExecProvisionerArgs | RemoteExecProvisionerArgs) { 58 | super('provisioner', [type], args); 59 | 60 | this.type = type; 61 | } 62 | 63 | override asArgument(): Argument { 64 | throw Util.inaccessibleMethod(); 65 | } 66 | 67 | override attr(_name: string): Attribute { 68 | throw Util.inaccessibleMethod(); 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /test/blocks/Resource.test.ts: -------------------------------------------------------------------------------- 1 | import { arg4 } from '..'; 2 | import { Map } from '../../src/arguments'; 3 | import { Resource } from '../../src/blocks'; 4 | 5 | test('Resource', () => { 6 | const resource = new Resource('type', 'name', arg4); 7 | expect(resource.toTerraform()).toMatchSnapshot(); 8 | expect(resource.asArgument().toTerraform()).toMatchSnapshot(); 9 | expect(resource.attr('attr').toTerraform()).toMatchSnapshot(); 10 | }); 11 | 12 | describe('toData', () => { 13 | 14 | const resource = new Resource('type', 'name', { 15 | arg: 'arg', 16 | tags: new Map({ 17 | a: 'a', 18 | b: 'b' 19 | }) 20 | }); 21 | 22 | test('OK', () => { 23 | expect(resource.toData(undefined, ['arg', ['tags', 'tag']]).toTerraform()).toMatchSnapshot(); 24 | expect(resource.toData({ type: 'newType', name: 'newName' }, ['arg', ['tags', 'tag']]).toTerraform()).toMatchSnapshot(); 25 | }); 26 | 27 | test('Data args', () => { 28 | expect(resource.toData(undefined, ['arg', ['tags', 'tag']], { a: 'a' }).toTerraform()).toMatchSnapshot(); 29 | expect(resource.toData({ type: 'newType', name: 'newName' }, ['arg', ['tags', 'tag']], { a: 'a' }).toTerraform()).toMatchSnapshot(); 30 | }); 31 | 32 | test('Data args overwrite', () => { 33 | expect(resource.toData(undefined, ['arg', ['tags', 'tag']], { arg: 'a' }).toTerraform()).toMatchSnapshot(); 34 | expect(resource.toData({ type: 'newType', name: 'newName' }, ['arg', ['tags', 'tag']], { arg: 'a' }).toTerraform()).toMatchSnapshot(); 35 | }); 36 | 37 | test('Data args with filter', () => { 38 | expect(resource.toData(undefined, ['arg', ['tags', 'tag']], { filter: [] }).toTerraform()).toMatchSnapshot(); 39 | expect(resource.toData({ type: 'newType', name: 'newName' }, ['arg', ['tags', 'tag']], { filter: [] }).toTerraform()) 40 | .toMatchSnapshot(); 41 | }); 42 | 43 | test('Data args invalid filter', () => { 44 | expect(() => resource.toData(undefined, ['arg'], { filter: 'a' })).toThrow(); 45 | expect(() => resource.toData(undefined, ['arg'], { filter: 'a' })).toThrow(); 46 | }); 47 | 48 | }); 49 | -------------------------------------------------------------------------------- /test/tfg/Others.test.ts: -------------------------------------------------------------------------------- 1 | import fs from 'fs'; 2 | import path from 'path'; 3 | import { Argument, arg, map } from '../../src/arguments'; 4 | import { Provisioner } from '../../src/blocks'; 5 | import { TerraformGenerator } from '../../src/TerraformGenerator'; 6 | 7 | const createTerraformGenerator = (): TerraformGenerator => { 8 | const tfg = new TerraformGenerator(); 9 | 10 | tfg.variable('test', { 11 | type: arg('string') 12 | }); 13 | 14 | tfg.variable('test2', { 15 | type: arg('string') 16 | }, 'test'); 17 | 18 | tfg.data('aws_vpc', 'test', { 19 | cidr_block: 'test' 20 | }); 21 | 22 | tfg.module('test', { 23 | source: './test' 24 | }); 25 | 26 | const r = tfg.resource('aws_vpc', 'test', { 27 | cidr_block: 'test', 28 | tags: map({ 29 | a: 'a' 30 | }) 31 | }); 32 | 33 | tfg.dataFromResource(r, undefined, ['cidr_block', ['tags', 'tag']]); 34 | tfg.dataFromResource(r, { name: 'test2' }, ['cidr_block', ['tags', 'tag']]); 35 | 36 | const resource = tfg.resource('innerBlock', 'innerBlock', { 37 | a: 'a' 38 | }, [ 39 | new Provisioner('local-exec', { 40 | command: 'echo hello' 41 | }), 42 | new Provisioner('local-exec', { 43 | command: 'echo world' 44 | }) 45 | ]); 46 | 47 | const locals = tfg.locals({ 48 | a: 'a', 49 | b: 123, 50 | c: r.attr('x') 51 | }); 52 | tfg.resource('locals', 'locals', { 53 | a: locals.arg('a') 54 | }); 55 | 56 | tfg.import({ 57 | to: resource, 58 | id: 'id', 59 | provider: arg('arg') 60 | }); 61 | 62 | tfg.resource('tags', 'tags', { 63 | tags: map({ 64 | 'a': 'a', 65 | 'b': 'b c d' 66 | }) 67 | }); 68 | 69 | tfg.comment('comment'); 70 | 71 | tfg.comment(` 72 | line1 73 | line2 74 | line3 75 | line4 76 | `); 77 | 78 | tfg.moved({ 79 | from: new Argument('resource.a'), 80 | to: resource 81 | }); 82 | 83 | tfg.removed({ 84 | from: new Argument('resource.b'), 85 | lifecycle: { 86 | destroy: false 87 | } 88 | }); 89 | 90 | const tfg2 = new TerraformGenerator(); 91 | tfg2.resource('tfg2', 'tfg2', { 92 | tfg2: 'tfg2' 93 | }); 94 | 95 | tfg.merge(tfg2); 96 | 97 | return tfg; 98 | }; 99 | 100 | const outputDir = path.join('test', '__output__'); 101 | 102 | test('Others', () => { 103 | const tfg = createTerraformGenerator(); 104 | 105 | expect(tfg.getArguments()).toMatchSnapshot(); 106 | expect(tfg.getBlocks()).toMatchSnapshot(); 107 | expect(tfg.getVars()).toMatchSnapshot(); 108 | expect(tfg.generate()).toMatchSnapshot(); 109 | 110 | tfg.write({ 111 | dir: outputDir, 112 | tfFilename: 'others', 113 | tfvarsFilename: 'others' 114 | }); 115 | const tf = fs.readFileSync(path.join(outputDir, 'others.tf'), 'utf8'); 116 | expect(tf).toMatchSnapshot(); 117 | const tfvars = fs.readFileSync(path.join(outputDir, 'others.tfvars'), 'utf8'); 118 | expect(tfvars).toMatchSnapshot(); 119 | }); 120 | -------------------------------------------------------------------------------- /src/blocks/Resource.ts: -------------------------------------------------------------------------------- 1 | import { Argument, Attribute, Map } from '../arguments'; 2 | import { TerraformArgs } from '../utils'; 3 | import { Block, Data, Provisioner } from '.'; 4 | 5 | /** 6 | * @category Block 7 | */ 8 | export interface ResourceToDataOptions { 9 | /** 10 | * New type of the data source. 11 | */ 12 | type?: string; 13 | /** 14 | * New name of the data source. 15 | */ 16 | name?: string; 17 | } 18 | 19 | /** 20 | * @category Block 21 | */ 22 | export class Resource extends Block { 23 | 24 | readonly type: string; 25 | readonly name: string; 26 | 27 | /** 28 | * Construct resource. 29 | * 30 | * Refer to Terraform documentation on what can be put as type & arguments. 31 | * 32 | * @param type type 33 | * @param name name 34 | * @param args arguments 35 | * @param provisioners provisioners 36 | */ 37 | constructor(type: string, name: string, args?: TerraformArgs, provisioners?: Provisioner[]) { 38 | super('resource', [type, name], args ?? {}, provisioners); 39 | 40 | this.type = type; 41 | this.name = name; 42 | } 43 | 44 | override asArgument(): Argument { 45 | return new Argument(`${this.type}.${this.name}`); 46 | } 47 | 48 | override attr(name: string): Attribute { 49 | return new Attribute(this, name); 50 | } 51 | 52 | /** 53 | * Get provisioners. 54 | */ 55 | getProvisioners(): Provisioner[] { 56 | return this.getInnerBlocks() as Provisioner[]; 57 | } 58 | 59 | /** 60 | * Set provisioners. 61 | */ 62 | setProvisioners(provisioners: Provisioner[] | undefined): this { 63 | this.setInnerBlocks(provisioners); 64 | return this; 65 | } 66 | 67 | /** 68 | * Convert resource into data source. 69 | * 70 | * Refer to Terraform documentation on what can be put as arguments. 71 | * 72 | * @param options options 73 | * @param argNames names of resource arguments to converted into data source arguments; 74 | * use array for name mapping, position 0 = original resource's argument name, position 1 = mapped data source's argument name 75 | * @param args extra arguments 76 | */ 77 | toData( 78 | options: ResourceToDataOptions | undefined, 79 | argNames: (string | [string, string])[], 80 | args?: TerraformArgs 81 | ): Data { 82 | const type = options?.type ?? this.type; 83 | const name = options?.name ?? this.name; 84 | 85 | if (!args) { 86 | args = {}; 87 | } 88 | if (!args['filter']) { 89 | args['filter'] = []; 90 | } else if (!Array.isArray(args['filter'])) { 91 | throw new Error('Filter is not an array.'); 92 | } 93 | 94 | for (const argName of argNames) { 95 | let actualArgName: string; 96 | let newArgName: string; 97 | if (typeof argName === 'string') { 98 | actualArgName = argName; 99 | newArgName = argName; 100 | } else { 101 | actualArgName = argName[0]; 102 | newArgName = argName[1]; 103 | } 104 | 105 | const arg = this.getArgument(actualArgName); 106 | if (arg instanceof Map) { 107 | for (const mapArgName in arg.arguments) { 108 | args['filter'].push({ 109 | name: `${newArgName}:${mapArgName}`, 110 | values: [arg.arguments[mapArgName]] 111 | }); 112 | } 113 | } else if (!args[newArgName]) { 114 | args[newArgName] = arg; 115 | } 116 | } 117 | 118 | return new Data(type, name, args); 119 | } 120 | 121 | } 122 | -------------------------------------------------------------------------------- /src/utils/Util.ts: -------------------------------------------------------------------------------- 1 | import { Block } from '../blocks'; 2 | import { IDENTIFIER_REGEX, TerraformArgs, TerraformElement } from '.'; 3 | 4 | export class Util { 5 | 6 | static readonly #escapeChars = [ 7 | ['"', '&tfgquot;'] 8 | ]; 9 | 10 | static escape(str: string): string { 11 | this.#escapeChars.forEach(char => { 12 | str = str.replaceAll(char[0], char[1]); 13 | }); 14 | return str; 15 | } 16 | 17 | static unescape(str: string): string { 18 | this.#escapeChars.slice().reverse().forEach(char => { 19 | str = str.replaceAll(char[1], char[0]); 20 | }); 21 | return str; 22 | } 23 | 24 | static argumentsToString(args?: TerraformArgs): string { 25 | let str = ''; 26 | for (const key in args) { 27 | str += this.argumentToString(key, args[key]); 28 | } 29 | return str; 30 | } 31 | 32 | static isObjectArgument(value: any): boolean { 33 | if (['string', 'number', 'boolean'].indexOf(typeof value) >= 0 || value instanceof TerraformElement) { 34 | return false; 35 | } 36 | if (typeof value === 'object') { 37 | return true; 38 | } 39 | throw new Error(`Invalid value: ${value}`); 40 | } 41 | 42 | static argumentToString(key: string, value: any): string { 43 | try { 44 | if (value == null) { 45 | return ''; 46 | } 47 | 48 | if (!key.match(IDENTIFIER_REGEX)) { 49 | key = `"${key}"`; 50 | } 51 | 52 | let operator = ' = '; 53 | let isObjectArray = false; 54 | 55 | if (Array.isArray(value)) { 56 | if (value.length === 0 || this.isObjectArgument(value[0])) { 57 | value = value.filter(element => element != null); 58 | operator = ' '; 59 | isObjectArray = true; 60 | } 61 | } else if (this.isObjectArgument(value)) { 62 | operator = ' '; 63 | } 64 | 65 | if (isObjectArray) { 66 | let str = ''; 67 | if (Array.isArray(value)) { 68 | value.forEach(element => { 69 | str += `${key}${operator}${this.argumentValueToString(element)}\n`; 70 | }); 71 | } 72 | return str; 73 | 74 | } 75 | return `${key}${operator}${this.argumentValueToString(value)}\n`; 76 | 77 | } catch (err) { 78 | throw new Error(`Invalid value: ${key} = ${value}`); 79 | } 80 | } 81 | 82 | static argumentValueToString(value: any): string | null { 83 | if (value == null) { 84 | return null; 85 | } 86 | 87 | if (value instanceof Block) { 88 | return value.asArgument().toTerraform(); 89 | } 90 | 91 | if (value instanceof TerraformElement) { 92 | return value.toTerraform(); 93 | } 94 | 95 | if (['string', 'number', 'boolean'].indexOf(typeof value) >= 0) { 96 | return JSON.stringify(value); 97 | } 98 | 99 | if (typeof value === 'object') { 100 | if (Array.isArray(value)) { 101 | let str = '[\n'; 102 | value.forEach((element, i) => { 103 | str += `${this.argumentValueToString(element)}${i < value.length - 1 ? ',' : ''}\n`; 104 | }); 105 | str += ']'; 106 | return str; 107 | } 108 | 109 | let str = '{\n'; 110 | for (const key in value) { 111 | str += this.argumentToString(key, value[key]); 112 | } 113 | str += '}'; 114 | return str; 115 | } 116 | 117 | throw new Error(`Invalid value: ${value}`); 118 | } 119 | 120 | static inaccessibleMethod() { 121 | return new Error('Inaccessible method.'); 122 | } 123 | 124 | } 125 | -------------------------------------------------------------------------------- /src/blocks/Block.ts: -------------------------------------------------------------------------------- 1 | import { Argument, Attribute } from '../arguments'; 2 | import { IDENTIFIER_REGEX, TerraformArgs, TerraformElement, Util } from '../utils'; 3 | 4 | /** 5 | * @category Block 6 | */ 7 | export abstract class Block extends TerraformElement { 8 | 9 | readonly blockType: string; 10 | readonly blockNames: string[]; 11 | #arguments: Args; 12 | #innerBlocks: Block[]; 13 | readonly #insideTerraformBlock: boolean; 14 | 15 | /** 16 | * Construct block. 17 | * 18 | * @param type type 19 | * @param names names 20 | * @param args arguments 21 | */ 22 | constructor(type: string, names: string[], args: Args, innerBlocks?: Block[], insideTerraformBlock = false) { 23 | super(); 24 | 25 | this.#validateIdentifier(type); 26 | names.forEach(name => { 27 | this.#validateIdentifier(name); 28 | }); 29 | 30 | this.blockType = type; 31 | this.blockNames = names; 32 | this.#arguments = args; 33 | this.#innerBlocks = innerBlocks ? innerBlocks : []; 34 | this.#insideTerraformBlock = insideTerraformBlock; 35 | } 36 | 37 | /** 38 | * Is this block to be placed inside top-level terraform block. 39 | */ 40 | isInsideTerraformBlock() { 41 | return this.#insideTerraformBlock; 42 | } 43 | 44 | /** 45 | * Get arguments. 46 | */ 47 | getArguments(): Args { 48 | return this.#arguments; 49 | } 50 | 51 | /** 52 | * Get argument by key. 53 | * 54 | * @param key key 55 | */ 56 | getArgument(key: K): Args[K] { 57 | return this.#arguments[key]; 58 | } 59 | 60 | /** 61 | * Set argument. 62 | * 63 | * @param key key 64 | * @param value value 65 | */ 66 | setArgument(key: K, value: Args[K]): this { 67 | this.#arguments[key] = value; 68 | return this; 69 | } 70 | 71 | /** 72 | * Set arguments. 73 | * 74 | * @param args arguments 75 | */ 76 | setArguments(args: Partial): this { 77 | this.#arguments = { 78 | ...this.#arguments, 79 | ...args 80 | }; 81 | return this; 82 | } 83 | 84 | /** 85 | * Delete argument by key. 86 | * 87 | * @param key key 88 | */ 89 | deleteArgument(key: string): this { 90 | delete this.#arguments[key]; 91 | return this; 92 | } 93 | 94 | /** 95 | * Get inner blocks. 96 | */ 97 | protected getInnerBlocks(): Block[] { 98 | return this.#innerBlocks; 99 | } 100 | 101 | /** 102 | * Set inner blocks. 103 | */ 104 | protected setInnerBlocks(innerBlocks: Block[] | undefined): this { 105 | this.#innerBlocks = innerBlocks ? innerBlocks : []; 106 | return this; 107 | } 108 | 109 | override toTerraform(): string { 110 | let str = this.blockType; 111 | this.blockNames.forEach(name => { 112 | str += ` "${name}"`; 113 | }); 114 | str += '{\n'; 115 | str += Util.argumentsToString(this.#arguments); 116 | this.#innerBlocks.forEach(block => { 117 | str += `${block.toTerraform().trim()}\n`; 118 | }); 119 | str += '}\n\n'; 120 | return Util.escape(str); 121 | } 122 | 123 | /** 124 | * Represent block as argument. 125 | */ 126 | abstract asArgument(): Argument; 127 | 128 | /** 129 | * Get block's attribute. 130 | * 131 | * @param name attribute name 132 | */ 133 | abstract attr(name: string): Attribute; 134 | 135 | /** 136 | * Block's id attribute. 137 | */ 138 | get id(): Attribute { 139 | return this.attr('id'); 140 | } 141 | 142 | #validateIdentifier(identifier: string): void { 143 | if (!identifier.match(IDENTIFIER_REGEX)) { 144 | throw new Error(`Invalid identifier: ${identifier}`); 145 | } 146 | } 147 | 148 | } 149 | -------------------------------------------------------------------------------- /test/tfg/__snapshots__/Others.test.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`Others 1`] = `undefined`; 4 | 5 | exports[`Others 2`] = ` 6 | [ 7 | Variable { 8 | "blockNames": [ 9 | "test", 10 | ], 11 | "blockType": "variable", 12 | "name": "test", 13 | }, 14 | Variable { 15 | "blockNames": [ 16 | "test2", 17 | ], 18 | "blockType": "variable", 19 | "name": "test2", 20 | }, 21 | Data { 22 | "blockNames": [ 23 | "aws_vpc", 24 | "test", 25 | ], 26 | "blockType": "data", 27 | "name": "test", 28 | "type": "aws_vpc", 29 | }, 30 | Module { 31 | "blockNames": [ 32 | "test", 33 | ], 34 | "blockType": "module", 35 | "name": "test", 36 | }, 37 | Resource { 38 | "blockNames": [ 39 | "aws_vpc", 40 | "test", 41 | ], 42 | "blockType": "resource", 43 | "name": "test", 44 | "type": "aws_vpc", 45 | }, 46 | Data { 47 | "blockNames": [ 48 | "aws_vpc", 49 | "test", 50 | ], 51 | "blockType": "data", 52 | "name": "test", 53 | "type": "aws_vpc", 54 | }, 55 | Data { 56 | "blockNames": [ 57 | "aws_vpc", 58 | "test2", 59 | ], 60 | "blockType": "data", 61 | "name": "test2", 62 | "type": "aws_vpc", 63 | }, 64 | Resource { 65 | "blockNames": [ 66 | "innerBlock", 67 | "innerBlock", 68 | ], 69 | "blockType": "resource", 70 | "name": "innerBlock", 71 | "type": "innerBlock", 72 | }, 73 | Locals { 74 | "blockNames": [], 75 | "blockType": "locals", 76 | }, 77 | Resource { 78 | "blockNames": [ 79 | "locals", 80 | "locals", 81 | ], 82 | "blockType": "resource", 83 | "name": "locals", 84 | "type": "locals", 85 | }, 86 | Import { 87 | "blockNames": [], 88 | "blockType": "import", 89 | }, 90 | Resource { 91 | "blockNames": [ 92 | "tags", 93 | "tags", 94 | ], 95 | "blockType": "resource", 96 | "name": "tags", 97 | "type": "tags", 98 | }, 99 | Comment { 100 | "blockNames": [], 101 | "blockType": "comment", 102 | "comment": "comment", 103 | }, 104 | Comment { 105 | "blockNames": [], 106 | "blockType": "comment", 107 | "comment": " 108 | line1 109 | line2 110 | line3 111 | line4 112 | ", 113 | }, 114 | Moved { 115 | "blockNames": [], 116 | "blockType": "moved", 117 | }, 118 | Removed { 119 | "blockNames": [], 120 | "blockType": "removed", 121 | }, 122 | Resource { 123 | "blockNames": [ 124 | "tfg2", 125 | "tfg2", 126 | ], 127 | "blockType": "resource", 128 | "name": "tfg2", 129 | "type": "tfg2", 130 | }, 131 | ] 132 | `; 133 | 134 | exports[`Others 3`] = ` 135 | { 136 | "test2": "test", 137 | } 138 | `; 139 | 140 | exports[`Others 4`] = ` 141 | { 142 | "tf": "variable "test"{ 143 | type = string 144 | } 145 | 146 | variable "test2"{ 147 | type = string 148 | } 149 | 150 | data "aws_vpc" "test"{ 151 | cidr_block = "test" 152 | } 153 | 154 | module "test"{ 155 | source = "./test" 156 | } 157 | 158 | resource "aws_vpc" "test"{ 159 | cidr_block = "test" 160 | tags = { 161 | a = "a" 162 | } 163 | } 164 | 165 | data "aws_vpc" "test"{ 166 | filter { 167 | name = "tag:a" 168 | values = [ 169 | "a" 170 | ] 171 | } 172 | cidr_block = "test" 173 | } 174 | 175 | data "aws_vpc" "test2"{ 176 | filter { 177 | name = "tag:a" 178 | values = [ 179 | "a" 180 | ] 181 | } 182 | cidr_block = "test" 183 | } 184 | 185 | resource "innerBlock" "innerBlock"{ 186 | a = "a" 187 | provisioner "local-exec"{ 188 | command = "echo hello" 189 | } 190 | provisioner "local-exec"{ 191 | command = "echo world" 192 | } 193 | } 194 | 195 | locals{ 196 | a = "a" 197 | b = 123 198 | c = aws_vpc.test.x 199 | } 200 | 201 | resource "locals" "locals"{ 202 | a = local.a 203 | } 204 | 205 | import{ 206 | to = innerBlock.innerBlock 207 | id = "id" 208 | provider = arg 209 | } 210 | 211 | resource "tags" "tags"{ 212 | tags = { 213 | a = "a" 214 | b = "b c d" 215 | } 216 | } 217 | 218 | # comment 219 | 220 | # line1 221 | # line2 222 | # line3 223 | # line4 224 | 225 | moved{ 226 | from = resource.a 227 | to = innerBlock.innerBlock 228 | } 229 | 230 | removed{ 231 | from = resource.b 232 | lifecycle { 233 | destroy = false 234 | } 235 | } 236 | 237 | resource "tfg2" "tfg2"{ 238 | tfg2 = "tfg2" 239 | } 240 | 241 | ", 242 | "tfvars": "test2 = "test" 243 | 244 | ", 245 | } 246 | `; 247 | 248 | exports[`Others 5`] = ` 249 | "variable "test"{ 250 | type = string 251 | } 252 | 253 | variable "test2"{ 254 | type = string 255 | } 256 | 257 | data "aws_vpc" "test"{ 258 | cidr_block = "test" 259 | } 260 | 261 | module "test"{ 262 | source = "./test" 263 | } 264 | 265 | resource "aws_vpc" "test"{ 266 | cidr_block = "test" 267 | tags = { 268 | a = "a" 269 | } 270 | } 271 | 272 | data "aws_vpc" "test"{ 273 | filter { 274 | name = "tag:a" 275 | values = [ 276 | "a" 277 | ] 278 | } 279 | cidr_block = "test" 280 | } 281 | 282 | data "aws_vpc" "test2"{ 283 | filter { 284 | name = "tag:a" 285 | values = [ 286 | "a" 287 | ] 288 | } 289 | cidr_block = "test" 290 | } 291 | 292 | resource "innerBlock" "innerBlock"{ 293 | a = "a" 294 | provisioner "local-exec"{ 295 | command = "echo hello" 296 | } 297 | provisioner "local-exec"{ 298 | command = "echo world" 299 | } 300 | } 301 | 302 | locals{ 303 | a = "a" 304 | b = 123 305 | c = aws_vpc.test.x 306 | } 307 | 308 | resource "locals" "locals"{ 309 | a = local.a 310 | } 311 | 312 | import{ 313 | to = innerBlock.innerBlock 314 | id = "id" 315 | provider = arg 316 | } 317 | 318 | resource "tags" "tags"{ 319 | tags = { 320 | a = "a" 321 | b = "b c d" 322 | } 323 | } 324 | 325 | # comment 326 | 327 | # line1 328 | # line2 329 | # line3 330 | # line4 331 | 332 | moved{ 333 | from = resource.a 334 | to = innerBlock.innerBlock 335 | } 336 | 337 | removed{ 338 | from = resource.b 339 | lifecycle { 340 | destroy = false 341 | } 342 | } 343 | 344 | resource "tfg2" "tfg2"{ 345 | tfg2 = "tfg2" 346 | } 347 | 348 | " 349 | `; 350 | 351 | exports[`Others 6`] = ` 352 | "test2 = "test" 353 | 354 | " 355 | `; 356 | -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "@typescript-eslint/parser", 3 | "parserOptions": { 4 | "ecmaVersion": 2018, 5 | "sourceType": "module" 6 | }, 7 | "extends": [ 8 | "plugin:@typescript-eslint/recommended", 9 | "plugin:import/errors", 10 | "plugin:import/warnings", 11 | "plugin:import/typescript", 12 | "plugin:security/recommended" 13 | ], 14 | "rules": { 15 | "@typescript-eslint/no-var-requires": "off", 16 | "@typescript-eslint/no-explicit-any": "off", 17 | "@typescript-eslint/no-non-null-assertion": "off", 18 | "@typescript-eslint/explicit-function-return-type": "off", 19 | "@typescript-eslint/explicit-module-boundary-types": "off", 20 | "@typescript-eslint/prefer-for-of": "error", 21 | "@typescript-eslint/type-annotation-spacing": "error", 22 | "@typescript-eslint/comma-spacing": "error", 23 | "@typescript-eslint/keyword-spacing": "error", 24 | "@typescript-eslint/func-call-spacing": "error", 25 | "@typescript-eslint/space-infix-ops": "error", 26 | "@typescript-eslint/prefer-optional-chain": "error", 27 | "@typescript-eslint/no-unused-vars": [ 28 | "error", 29 | { 30 | "argsIgnorePattern": "^_" 31 | } 32 | ], 33 | "@typescript-eslint/indent": [ 34 | "error", 35 | 2 36 | ], 37 | "@typescript-eslint/member-delimiter-style": [ 38 | "error", 39 | { 40 | "singleline": { 41 | "delimiter": "semi", 42 | "requireLast": false 43 | } 44 | } 45 | ], 46 | "@typescript-eslint/explicit-member-accessibility": [ 47 | "error", 48 | { 49 | "accessibility": "no-public" 50 | } 51 | ], 52 | "@typescript-eslint/naming-convention": [ 53 | "error", 54 | { 55 | "selector": "variableLike", 56 | "format": [ 57 | "strictCamelCase", 58 | "UPPER_CASE", 59 | "snake_case" 60 | ], 61 | "leadingUnderscore": "allow" 62 | }, 63 | { 64 | "selector": "memberLike", 65 | "format": [ 66 | "strictCamelCase", 67 | "UPPER_CASE", 68 | "snake_case" 69 | ] 70 | }, 71 | { 72 | "selector": "enumMember", 73 | "format": [ 74 | "UPPER_CASE" 75 | ] 76 | }, 77 | { 78 | "selector": "typeLike", 79 | "format": [ 80 | "StrictPascalCase" 81 | ] 82 | } 83 | ], 84 | "indent": "off", 85 | "no-unused-vars": "off", 86 | "comma-spacing": "off", 87 | "keyword-spacing": "off", 88 | "func-call-spacing": "off", 89 | "space-infix-ops": "off", 90 | "no-warning-comments": "warn", 91 | "prefer-const": "error", 92 | "no-multi-spaces": "error", 93 | "no-return-await": "error", 94 | "curly": "error", 95 | "prefer-template": "error", 96 | "block-spacing": "error", 97 | "eol-last": "error", 98 | "key-spacing": "error", 99 | "arrow-spacing": "error", 100 | "semi-spacing": "error", 101 | "space-before-blocks": "error", 102 | "space-in-parens": "error", 103 | "space-unary-ops": "error", 104 | "default-param-last": "error", 105 | "no-eval": "error", 106 | "no-implied-eval": "error", 107 | "no-extra-label": "error", 108 | "no-new-wrappers": "error", 109 | "no-return-assign": "error", 110 | "no-useless-return": "error", 111 | "radix": "error", 112 | "no-lonely-if": "error", 113 | "no-mixed-operators": "error", 114 | "no-whitespace-before-property": "error", 115 | "no-unneeded-ternary": "error", 116 | "operator-assignment": "error", 117 | "no-useless-constructor": "error", 118 | "quotes": [ 119 | "error", 120 | "single", 121 | { 122 | "avoidEscape": true 123 | } 124 | ], 125 | "max-len": [ 126 | "error", 127 | { 128 | "code": 150, 129 | "ignoreStrings": true 130 | } 131 | ], 132 | "semi": [ 133 | "error", 134 | "always" 135 | ], 136 | "comma-dangle": [ 137 | "error", 138 | "never" 139 | ], 140 | "arrow-parens": [ 141 | "error", 142 | "as-needed" 143 | ], 144 | "arrow-body-style": [ 145 | "error", 146 | "as-needed" 147 | ], 148 | "padded-blocks": [ 149 | "error", 150 | { 151 | "classes": "always", 152 | "switches": "never" 153 | } 154 | ], 155 | "no-multiple-empty-lines": [ 156 | "error", 157 | { 158 | "max": 1 159 | } 160 | ], 161 | "eqeqeq": [ 162 | "error", 163 | "smart" 164 | ], 165 | "no-trailing-spaces": [ 166 | "error", 167 | { 168 | "ignoreComments": true 169 | } 170 | ], 171 | "no-else-return": [ 172 | "error", 173 | { 174 | "allowElseIf": false 175 | } 176 | ], 177 | "object-curly-spacing": [ 178 | "error", 179 | "always" 180 | ], 181 | "array-bracket-spacing": [ 182 | "error", 183 | "never" 184 | ], 185 | "space-before-function-paren": [ 186 | "error", 187 | { 188 | "anonymous": "never", 189 | "asyncArrow": "always", 190 | "named": "never" 191 | } 192 | ], 193 | "max-classes-per-file": [ 194 | "error", 195 | 1 196 | ], 197 | "array-bracket-newline": [ 198 | "error", 199 | "consistent" 200 | ], 201 | "brace-style": [ 202 | "error", 203 | "1tbs" 204 | ], 205 | "max-lines": [ 206 | "error", 207 | 2000 208 | ], 209 | "max-lines-per-function": "off", 210 | "max-statements-per-line": [ 211 | "error", 212 | { 213 | "max": 1 214 | } 215 | ], 216 | "max-params": [ 217 | "error", 218 | 5 219 | ], 220 | "operator-linebreak": [ 221 | "error", 222 | "after" 223 | ], 224 | "no-duplicate-imports": [ 225 | "error", 226 | { 227 | "includeExports": true 228 | } 229 | ], 230 | "import/no-default-export": "error", 231 | "import/order": [ 232 | "error", 233 | { 234 | "alphabetize": { 235 | "order": "asc", 236 | "caseInsensitive": true 237 | }, 238 | "newlines-between": "never" 239 | } 240 | ], 241 | "security/detect-object-injection": "off", 242 | "security/detect-non-literal-fs-filename": "off", 243 | "security/detect-non-literal-require": "off", 244 | "security/detect-new-buffer": "off" 245 | } 246 | } 247 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # **terraform-generator** 2 | 3 | [![npm package](https://img.shields.io/npm/v/terraform-generator)](https://www.npmjs.com/package/terraform-generator) 4 | [![npm downloads](https://img.shields.io/npm/dt/terraform-generator)](https://www.npmjs.com/package/terraform-generator) 5 | [![GitHub test](https://github.com/ahzhezhe/terraform-generator/workflows/test/badge.svg?branch=master)](https://github.com/ahzhezhe/terraform-generator) 6 | [![GitHub issues](https://img.shields.io/github/issues/ahzhezhe/terraform-generator)](https://github.com/ahzhezhe/terraform-generator/issues) 7 | [![GitHub license](https://img.shields.io/github/license/ahzhezhe/terraform-generator)](https://github.com/ahzhezhe/terraform-generator/blob/master/LICENSE) 8 | 9 | Use Node.js to generate Terraform configurations. 10 | 11 | You do not need to have Terraform installed to use this module. 12 | 13 | The end result of using this module is Terraform configurations in plain text, you will need to write the text into a file (terraform-generator does provide an utility function to write the file for you) and execute it yourself. 14 | 15 | Currently support generating configurations for Terraform version >= 0.12. 16 | 17 | [API Documentation](https://ahzhezhe.github.io/docs/terraform-generator-v6/index.html) 18 | 19 | ## **Benefit** 20 | 21 | Make use of all Javascript programming features (some of which is not available in Terraform), e.g. functions, array, loops, if-else, map, etc. to generate a plain Terraform configurations. 22 | 23 | You can easily maintain your infra in Javascript/Typescript. 24 | 25 | You don't need to use Terraform variables, you can use your own Javascript/JSON variables or use dotenv. 26 | 27 | You don't need to use Terraform modules for reusable resource creations, you can make use of Javascript functions. 28 | 29 | You can incorporate other Node.js libraries to facilitate your work. 30 | 31 | ## **Limitation** 32 | 33 | The generated configurations are unformatted and its validity is not verified, use `terraform fmt` and `terraform plan` to format it and check its validity yourself. 34 | 35 | ## **Install via NPM** 36 | 37 | ``` 38 | npm install terraform-generator 39 | ``` 40 | 41 | ## **Usage** 42 | 43 | ### **Import** 44 | ```typescript 45 | import { TerraformGenerator, Resource, map, fn } from 'terraform-generator'; 46 | ``` 47 | or 48 | ```typescript 49 | const { TerraformGenerator, Resource, map, fn } = require('terraform-generator'); 50 | ``` 51 | 52 | ### **Initialize TerraformGenerator** 53 | ```typescript 54 | const tfg = new TerraformGenerator({ 55 | required_version: '>= 0.12' 56 | }); 57 | ``` 58 | 59 | ### **Blocks** 60 | Some block's arguments are not typed, please refer to official Terraform documentation on what arguments can be supplied. 61 | 62 | ```typescript 63 | tfg.provider('aws', { 64 | region: 'ap-southeast-1', 65 | profile: 'example' 66 | }); 67 | 68 | const vpc = tfg.resource('aws_vpc', 'vpc', { 69 | cidr_block: '172.88.0.0/16' 70 | }); 71 | ``` 72 | 73 | ### **Convert resource to data source** 74 | ```typescript 75 | import { vpc as vpcDS } from 'other-terraform-generator-configuration'; 76 | 77 | const vpc = tfg.dataFromResource(vpcDS, undefined, ['cidr_block', ['tags', 'tag']]); 78 | ``` 79 | 80 | ### **Arguments** 81 | ```typescript 82 | { 83 | string: 'str', 84 | number: 123, 85 | boolean: true, 86 | stringList: ['str1', 'str2', 'str3'], 87 | numberList: [111, 222, 333], 88 | booleanList: [true, false, true], 89 | tuple: ['str', 123, true], 90 | object: { 91 | arg1: 'str', 92 | arg2: 123, 93 | arg3: true 94 | }, 95 | objectList: [ 96 | { 97 | arg1: 'str' 98 | }, 99 | { 100 | arg1: 'str' 101 | } 102 | ], 103 | objectListForVariable: list( 104 | { 105 | arg1: 'str' 106 | }, 107 | { 108 | arg1: 'str' 109 | } 110 | ), 111 | map: map({ 112 | arg1: 'str', 113 | arg2: 123, 114 | arg3: true 115 | }), 116 | block: block, 117 | blockAttribute: block.attr('attrName'), 118 | heredoc: heredoc(`line1 119 | line2 120 | line3`), 121 | heredocJson: heredoc({ 122 | arg1: 'str', 123 | arg2: 123, 124 | arg3: true 125 | }), 126 | function1: fn('max', 5, 12, 19), 127 | function2: fn('sort', 'a', block.attr('attrName'), 'c'), 128 | functionElement: fn('tolist', ['a', 'b', 'c']).element(0), 129 | custom: arg('max(5, 12, 9)'), 130 | interpolation: `str-${block.attr('attrName')}` 131 | } 132 | ``` 133 | 134 | ### **Attributes** 135 | ```typescript 136 | block.attr('id') // block id, string 137 | block.id // convenience getter function, same as above 138 | block.attr('subnets') // subnet objects, object list 139 | block.attr('subnets.*.id') // subnet ids, string list 140 | block.attr('subnets').attr('*').attr('id') // same as above 141 | block.attr('subnets.*.id[0]') // first subnet id, string 142 | block.attr('subnets').attr('*').attr('id').element(0) // same as above 143 | ``` 144 | 145 | ### **Variables** 146 | ```typescript 147 | // You can directly add multiple variable values. 148 | tfg.addVars({ 149 | var1: 123, 150 | var2: 'abc' 151 | }); 152 | 153 | // You can also add single variable value while adding variable block to your configuration. 154 | tfg.variable('password', { 155 | type: 'string' 156 | }, 'p@ssW0rd'); 157 | ``` 158 | 159 | ### **Merge multiple configurations** 160 | ```typescript 161 | // You can split your configuration into multiple files and merge them before you generate the final outcome. 162 | tfg.merge(tfg2, tfg3); 163 | ``` 164 | 165 | ### **Generate Terraform configuration** 166 | ```typescript 167 | // Generate Terraform configuration as string 168 | const result = tfg.generate(); 169 | console.log(result.tf); 170 | console.log(result.tfvars); 171 | 172 | // Write Terraform configuration to a file 173 | tfg.write({ 174 | dir: 'outputDir', 175 | format: true 176 | }); 177 | ``` 178 | 179 | ## **Example** 180 | ```typescript 181 | import TerraformGenerator, { Map, map } from 'terraform-generator'; 182 | import path from 'path'; 183 | 184 | // Constants 185 | const project = 'example'; 186 | 187 | // Environment variables 188 | const configs = { 189 | env: 'dev', 190 | tiers: [ 191 | { 192 | name: 'web', 193 | cidr: '172.88.100.0/22', 194 | subnetCidrs: ['172.88.100.0/24', '172.88.101.0/24', '172.88.102.0/24'] 195 | }, 196 | { 197 | name: 'app', 198 | cidr: '172.88.104.0/22', 199 | subnetCidrs: ['172.88.104.0/24', '172.88.105.0/24', '172.88.106.0/24'] 200 | }, 201 | { 202 | name: 'db', 203 | cidr: '172.88.108.0/22', 204 | subnetCidrs: ['172.88.108.0/24', '172.88.109.0/24', '172.88.110.0/24'] 205 | } 206 | ] 207 | }; 208 | 209 | // Utility functions 210 | const getAvailabilityZone = (i: number): string => { 211 | if (i === 0) { 212 | return 'ap-southeast-1a'; 213 | } else if (i === 1) { 214 | return 'ap-southeast-1b'; 215 | } else { 216 | return 'ap-southeast-1c'; 217 | } 218 | }; 219 | 220 | const getTagName = (type: string, name?: string): string => 221 | `${type}-${project}-${configs.env}${name ? `-${name}` : ''}`; 222 | 223 | const getTags = (type: string, name?: string): Map => new Map({ 224 | Name: getTagName(type, name), 225 | Project: project, 226 | Env: configs.env 227 | }); 228 | 229 | // Start writing Terraform configuration 230 | const tfg = new TerraformGenerator(); 231 | 232 | // Configure provider 233 | tfg.provider('aws', { 234 | region: 'ap-southeast-1', 235 | profile: 'example' 236 | }); 237 | 238 | // Find VPC by name 239 | const vpc = tfg.data('aws_vpc', 'vpc', { 240 | filter: [{ 241 | name: 'tag:Name', 242 | values: [getTagName('vpc')] 243 | }] 244 | }); 245 | 246 | const subnets = { 247 | web: [], 248 | app: [], 249 | db: [] 250 | }; 251 | 252 | // Create 3-tiers, each tier has 3 subnets spread across availabilty zones 253 | configs.tiers.forEach(tier => { 254 | tier.subnetCidrs.forEach((cidr, i) => { 255 | const name = `${tier.name}${i}`; 256 | const subnet = tfg.resource('aws_subnet', `subnet_${name}`, { 257 | vpc_id: vpc.id, 258 | cidr_block: cidr, 259 | availability_zone: getAvailabilityZone(i), 260 | tags: getTags('subnet', name) 261 | }); 262 | subnets[tier.name].push(subnet); 263 | }); 264 | }); 265 | 266 | // Output all subnet ids 267 | tfg.output('subnets', { 268 | value: map({ 269 | webSubnets: subnets.web.map(subnet => subnet.id), 270 | appSubnets: subnets.app.map(subnet => subnet.id), 271 | dbSubnets: subnets.db.map(subnet => subnet.id) 272 | }) 273 | }); 274 | 275 | // Write the configuration into a terraform.tf file 276 | const outputDir = path.join('output', configs.env, 'subnets'); 277 | tfg.write({ dir: outputDir, format: true }); 278 | ``` 279 | -------------------------------------------------------------------------------- /test/tfg/Base.test.ts: -------------------------------------------------------------------------------- 1 | import fs from 'fs'; 2 | import path from 'path'; 3 | import { Map, map } from '../../src/arguments'; 4 | import { Resource } from '../../src/blocks'; 5 | import { TerraformGenerator } from '../../src/TerraformGenerator'; 6 | 7 | const project = 'test'; 8 | 9 | const configs = { 10 | env: 'dev', 11 | vpc: { 12 | cidr: '172.88.0.0/16' 13 | }, 14 | tiers: [ 15 | { 16 | name: 'public', 17 | cidr: '172.88.100.0/22', 18 | subnetCidrs: ['172.88.100.0/24', '172.88.101.0/24', '172.88.102.0/24'] 19 | }, 20 | { 21 | name: 'web', 22 | cidr: '172.88.104.0/22', 23 | subnetCidrs: ['172.88.104.0/24', '172.88.105.0/24', '172.88.106.0/24'] 24 | }, 25 | { 26 | name: 'app', 27 | cidr: '172.88.108.0/22', 28 | subnetCidrs: ['172.88.108.0/24', '172.88.109.0/24', '172.88.110.0/24'] 29 | }, 30 | { 31 | name: 'gut', 32 | cidr: '172.88.112.0/22', 33 | subnetCidrs: ['172.88.112.0/24', '172.88.113.0/24', '172.88.114.0/24'] 34 | }, 35 | { 36 | name: 'db', 37 | cidr: '172.88.116.0/22', 38 | subnetCidrs: ['172.88.116.0/24', '172.88.117.0/24', '172.88.118.0/24'] 39 | } 40 | ] 41 | }; 42 | 43 | const findTier = (name: string): { name: string; cidr: string; subnetCidrs: string[] } => 44 | configs.tiers.filter(tier => tier.name === name)[0]; 45 | 46 | const getAvailabilityZone = (index: number): string => { 47 | switch (index) { 48 | case 0: 49 | return 'ap-southeast-1a'; 50 | case 1: 51 | return 'ap-southeast-1b'; 52 | case 2: 53 | return 'ap-southeast-1c'; 54 | default: 55 | throw new Error(`Invalid availability zone ${index}`); 56 | } 57 | }; 58 | 59 | const getTagName = (type: string, name?: string, tier?: string): string => 60 | `${type}-${project}-${configs.env}${tier ? `-${tier}` : ''}${name ? `-${name}` : ''}`; 61 | 62 | const getTags = (type: string, name?: string, tier?: string): Map => map({ 63 | name: getTagName(type, name, tier), 64 | project, 65 | env: configs.env 66 | }); 67 | 68 | const createTerraformGenerator = (): TerraformGenerator => { 69 | // Terraform 70 | const tfg = new TerraformGenerator({ 71 | required_version: '= 0.12' 72 | }); 73 | 74 | tfg.backend('s3', { 75 | bucket: 'mybucket', 76 | key: 'path/to/my/key', 77 | region: 'ap-southeast-1' 78 | }); 79 | 80 | // Provider 81 | tfg.provider('aws', { 82 | region: 'ap-southeast-1', 83 | profile: 'test' 84 | }); 85 | 86 | // VPC 87 | const vpc = tfg.resource('aws_vpc', 'vpc', { 88 | cidr_block: configs.vpc.cidr, 89 | tags: getTags('vpc') 90 | }); 91 | 92 | // Subnets 93 | const publicSubnets: Resource[] = []; 94 | const webSubnets: Resource[] = []; 95 | const appSubnets: Resource[] = []; 96 | const gutSubnets: Resource[] = []; 97 | const dbSubnets: Resource[] = []; 98 | const itSubnets: Resource[] = []; 99 | const mgtSubnets: Resource[] = []; 100 | 101 | configs.tiers.forEach(tier => { 102 | for (let i = 0; i < tier.subnetCidrs.length; i++) { 103 | const name = `${tier.name}${i}`; 104 | const subnet = tfg.resource('aws_subnet', name, { 105 | vpc_id: vpc.id, 106 | cidr_block: tier.subnetCidrs[i], 107 | availability_zone: getAvailabilityZone(i), 108 | tags: getTags('subnet', name) 109 | }); 110 | if (tier.name === 'public') { 111 | publicSubnets.push(subnet); 112 | } else if (tier.name === 'web') { 113 | webSubnets.push(subnet); 114 | } else if (tier.name === 'app') { 115 | appSubnets.push(subnet); 116 | } else if (tier.name === 'gut') { 117 | gutSubnets.push(subnet); 118 | } else if (tier.name === 'db') { 119 | dbSubnets.push(subnet); 120 | } else if (tier.name === 'it') { 121 | itSubnets.push(subnet); 122 | } else if (tier.name === 'mgt') { 123 | mgtSubnets.push(subnet); 124 | } 125 | } 126 | }); 127 | 128 | // Internet gateway 129 | const igw = tfg.resource('aws_internet_gateway', 'igw', { 130 | vpc_id: vpc.id, 131 | tags: getTags('igw') 132 | }); 133 | 134 | // Route tables 135 | const rtDefault = tfg.resource('aws_route_table', 'default', { 136 | vpc_id: vpc.id, 137 | tags: getTags('rt', 'default') 138 | }); 139 | 140 | const rtIgw = tfg.resource('aws_route_table', 'igw', { 141 | vpc_id: vpc.id, 142 | route: [ 143 | { 144 | cidr_block: '0.0.0.0/0', 145 | gateway_id: igw.id 146 | } 147 | ], 148 | tags: getTags('rt', 'igw') 149 | }); 150 | 151 | webSubnets.concat(appSubnets, gutSubnets, dbSubnets, itSubnets).forEach(subnet => { 152 | tfg.resource('aws_route_table_association', `default-${subnet.name}`, { 153 | subnet_id: subnet.id, 154 | route_table_id: rtDefault.id 155 | }); 156 | }); 157 | 158 | publicSubnets.forEach(subnet => { 159 | tfg.resource('aws_route_table_association', `igw-${subnet.name}`, { 160 | subnet_id: subnet.id, 161 | route_table_id: rtIgw.id 162 | }); 163 | }); 164 | 165 | // NetworkACL 166 | const defaultNaclRules = [ 167 | { 168 | protocol: 'all', 169 | rule_no: 100, 170 | action: 'allow', 171 | cidr_block: '0.0.0.0/0', 172 | from_port: 0, 173 | to_port: 0 174 | } 175 | ]; 176 | 177 | const dbNaclRules = [ 178 | { 179 | protocol: 'all', 180 | rule_no: 100, 181 | action: 'allow', 182 | cidr_block: findTier('app').cidr, 183 | from_port: 0, 184 | to_port: 0 185 | }, 186 | { 187 | protocol: 'all', 188 | rule_no: 110, 189 | action: 'allow', 190 | cidr_block: findTier('db').cidr, 191 | from_port: 0, 192 | to_port: 0 193 | } 194 | ]; 195 | 196 | tfg.resource('aws_network_acl', 'default', { 197 | vpc_id: vpc.id, 198 | subnet_ids: publicSubnets.concat(webSubnets, appSubnets, gutSubnets, itSubnets, mgtSubnets).map(subnet => subnet.id), 199 | ingress: defaultNaclRules, 200 | egress: defaultNaclRules, 201 | tags: getTags('nacl', 'default') 202 | }); 203 | 204 | tfg.resource('aws_network_acl', 'db', { 205 | vpc_id: vpc.id, 206 | subnet_ids: dbSubnets.map(subnet => subnet.id), 207 | ingress: dbNaclRules, 208 | egress: dbNaclRules, 209 | tags: getTags('nacl', 'db') 210 | }); 211 | 212 | // Tiers' security groups 213 | const sgEgress = { 214 | protocol: '-1', 215 | from_port: 0, 216 | to_port: 0, 217 | cidr_blocks: ['0.0.0.0/0'] 218 | }; 219 | 220 | configs.tiers.forEach(tier => { 221 | const sgIngress = { 222 | protocol: 'tcp', 223 | from_port: 22, 224 | to_port: 22, 225 | cidr_blocks: [tier.cidr], 226 | description: 'SSH for tier' 227 | }; 228 | 229 | tfg.resource('aws_security_group', `${tier.name}-default`, { 230 | name: `fw-${tier.name}-default`, 231 | description: `Default for ${tier.name} tier`, 232 | vpc_id: vpc.id, 233 | ingress: sgIngress, 234 | egress: sgEgress, 235 | tags: getTags('sg', 'default', tier.name) 236 | }); 237 | }); 238 | 239 | // NAT Gateway 240 | const natEip = tfg.resource('aws_eip', 'nat', { 241 | vpc: true, 242 | tags: getTags('eip', 'nat') 243 | }); 244 | 245 | const nat = tfg.resource('aws_nat_gateway', 'nat', { 246 | allocation_id: natEip.id, 247 | subnet_id: publicSubnets[0].id, 248 | tags: getTags('nat') 249 | }); 250 | 251 | const rtNat = tfg.resource('aws_route_table', 'nat', { 252 | vpc_id: vpc.id, 253 | route: { 254 | cidr_block: '0.0.0.0/0', 255 | gateway_id: nat.id 256 | }, 257 | tags: getTags('rt', 'nat') 258 | }); 259 | 260 | gutSubnets.forEach(subnet => { 261 | tfg.resource('aws_route_table_association', `nat-${subnet.name}`, { 262 | subnet_id: subnet.id, 263 | route_table_id: rtNat.id 264 | }); 265 | }); 266 | 267 | // Output 268 | tfg.output('vpc', { 269 | value: map({ 270 | cidr: vpc.attr('cidr_block') 271 | }) 272 | }); 273 | 274 | tfg.output('subnets', { 275 | value: map({ 276 | publicSubnets: publicSubnets.map(subnet => subnet.attr('cidr_block')), 277 | webSubnets: webSubnets.map(subnet => subnet.attr('cidr_block')), 278 | appSubnets: appSubnets.map(subnet => subnet.attr('cidr_block')), 279 | gutSubnets: gutSubnets.map(subnet => subnet.attr('cidr_block')), 280 | mgtSubnets: mgtSubnets.map(subnet => subnet.attr('cidr_block')), 281 | dbSubnets: dbSubnets.map(subnet => subnet.attr('cidr_block')) 282 | }) 283 | }); 284 | 285 | return tfg; 286 | }; 287 | 288 | const outputDir = path.join('test', '__output__'); 289 | 290 | test('Base', () => { 291 | const tfg = createTerraformGenerator(); 292 | 293 | expect(tfg.getArguments()).toMatchSnapshot(); 294 | expect(tfg.getBlocks()).toMatchSnapshot(); 295 | expect(tfg.getVars()).toMatchSnapshot(); 296 | expect(tfg.generate()).toMatchSnapshot(); 297 | 298 | tfg.write({ 299 | dir: outputDir, 300 | tfFilename: 'base', 301 | tfvarsFilename: 'base' 302 | }); 303 | const tf = fs.readFileSync(path.join(outputDir, 'base.tf'), 'utf8'); 304 | expect(tf).toMatchSnapshot(); 305 | }); 306 | 307 | -------------------------------------------------------------------------------- /src/TerraformGenerator.ts: -------------------------------------------------------------------------------- 1 | import child_process from 'child_process'; 2 | import fs from 'fs'; 3 | import path from 'path'; 4 | import shell from 'shelljs'; 5 | import { Block, Comment, Resource, Data, Module, Output, Provider, Variable, Backend, Provisioner, ResourceToDataOptions, Locals, Import, ImportArgs, VariableArgs, ModuleArgs, OutputArgs, Moved, MovedArgs, RemovedArgs, Removed } from './blocks'; 6 | import { TerraformArgs, Util } from './utils'; 7 | 8 | /** 9 | * @category TerraformGenerator 10 | */ 11 | export interface WriteOptions { 12 | /** 13 | * Directory to write to. 14 | * 15 | * Default = . 16 | */ 17 | dir?: string; 18 | /** 19 | * Terraform filename, must ends with .tf. 20 | * 21 | * Default = terraform.tf 22 | */ 23 | tfFilename?: string; 24 | /** 25 | * Terraform variables filename, must ends with .tfvars. 26 | * 27 | * Default = terraform.tfvars 28 | */ 29 | tfvarsFilename?: string; 30 | /** 31 | * Put `true` to use `terraform fmt` to format the configuration, Terraform must be installed. 32 | * 33 | * If the terraform binary is named differently in your machine, put the binary name instead. 34 | * 35 | * Default = false 36 | */ 37 | format?: boolean | string; 38 | } 39 | 40 | /** 41 | * @category TerraformGenerator 42 | */ 43 | export class TerraformGenerator { 44 | 45 | readonly #arguments?: TerraformArgs; 46 | readonly #blocks: Block[] = []; 47 | #variables: TerraformArgs = {}; 48 | 49 | /** 50 | * Construct Terraform generator. 51 | * 52 | * Refer to Terraform documentation on what can be put as arguments. 53 | * 54 | * @param args arguments 55 | */ 56 | constructor(args?: TerraformArgs) { 57 | this.#arguments = args; 58 | } 59 | 60 | /** 61 | * Generate Terraform configuration as string. 62 | */ 63 | generate(): { tf: string; tfvars?: string } { 64 | return { 65 | tf: this.#generateTf(), 66 | tfvars: Object.keys(this.#variables).length > 0 ? this.#generateTfvars() : undefined 67 | }; 68 | } 69 | 70 | #generateTf(): string { 71 | let str = ''; 72 | 73 | if (this.#arguments || this.#blocks.filter(block => block.isInsideTerraformBlock()).length > 0) { 74 | str += 'terraform {\n'; 75 | str += Util.argumentsToString(this.#arguments); 76 | this.#blocks.forEach(block => { 77 | if (block.isInsideTerraformBlock()) { 78 | str += block.toTerraform(); 79 | } 80 | }); 81 | str += '}\n\n'; 82 | } 83 | 84 | this.#blocks.forEach(block => { 85 | if (!block.isInsideTerraformBlock()) { 86 | str += block.toTerraform(); 87 | } 88 | }); 89 | 90 | return Util.unescape(str); 91 | } 92 | 93 | #generateTfvars(): string { 94 | let str = ''; 95 | 96 | Object.keys(this.#variables).forEach(key => { 97 | str += Util.argumentsToString({ [key]: this.#variables[key] }); 98 | str += '\n'; 99 | }); 100 | 101 | return str; 102 | } 103 | 104 | /** 105 | * Write Terraform configuration to a file. 106 | * 107 | * @param options options 108 | */ 109 | write(options?: WriteOptions): void { 110 | if (!options) { 111 | options = {}; 112 | } 113 | if (!options.dir) { 114 | options.dir = '.'; 115 | } 116 | if (!options.tfFilename) { 117 | options.tfFilename = 'terraform.tf'; 118 | } 119 | if (!options.tfFilename.endsWith('.tf')) { 120 | options.tfFilename += '.tf'; 121 | } 122 | if (!options.tfvarsFilename) { 123 | options.tfvarsFilename = 'terraform.tfvars'; 124 | } 125 | if (!options.tfvarsFilename.endsWith('.tfvars')) { 126 | options.tfvarsFilename += '.tfvars'; 127 | } 128 | if (options.format === true) { 129 | options.format = 'terraform'; 130 | } 131 | 132 | const result = this.generate(); 133 | shell.mkdir('-p', options.dir); 134 | fs.writeFileSync(path.join(options.dir, options.tfFilename), result.tf); 135 | if (result.tfvars) { 136 | fs.writeFileSync(path.join(options.dir, options.tfvarsFilename), result.tfvars); 137 | } 138 | 139 | if (options.format) { 140 | child_process.execSync(`${options.format} fmt`, { cwd: options.dir }); 141 | } 142 | } 143 | 144 | /** 145 | * Add blocks into Terraform. 146 | * 147 | * @param blocks blocks 148 | */ 149 | addBlocks(...blocks: Block[]): this { 150 | blocks.forEach(block => this.#blocks.push(block)); 151 | return this; 152 | } 153 | 154 | /** 155 | * Add comment into Terraform. 156 | * 157 | * @param comment comment 158 | */ 159 | comment(comment: string): Comment { 160 | const block = new Comment(comment); 161 | this.addBlocks(block); 162 | return block; 163 | } 164 | 165 | /** 166 | * Add provider into Terraform. 167 | * 168 | * Refer to Terraform documentation on what can be put as type & arguments. 169 | * 170 | * @param type type 171 | * @param args arguments 172 | */ 173 | provider(type: string, args: TerraformArgs): Provider { 174 | const block = new Provider(type, args); 175 | this.addBlocks(block); 176 | return block; 177 | } 178 | 179 | /** 180 | * Add resource into Terraform. 181 | * 182 | * Refer to Terraform documentation on what can be put as type & arguments. 183 | * 184 | * @param type type 185 | * @param name name 186 | * @param args arguments 187 | * @param provisioners provisioners 188 | */ 189 | resource(type: string, name: string, args: TerraformArgs, provisioners?: Provisioner[]): Resource { 190 | const block = new Resource(type, name, args, provisioners); 191 | this.addBlocks(block); 192 | return block; 193 | } 194 | 195 | /** 196 | * Convert resource into data source and add it into Terraform. 197 | * 198 | * @param resource resource 199 | * @param options options 200 | * @param argNames names of resource arguments to be converted into data source arguments; 201 | * use array for name mapping, position 0 = original resource's argument name, position 1 = mapped data source's argument name 202 | * @param args extra arguments 203 | */ 204 | dataFromResource( 205 | resource: Resource, 206 | options: ResourceToDataOptions | undefined, 207 | argNames: (string | [string, string])[], 208 | args?: TerraformArgs 209 | ): Data { 210 | const block = resource.toData(options, argNames, args); 211 | this.addBlocks(block); 212 | return block; 213 | } 214 | 215 | /** 216 | * Add data source into Terraform. 217 | * 218 | * Refer to Terraform documentation on what can be put as type & arguments. 219 | * 220 | * @param type type 221 | * @param name name 222 | * @param args arguments 223 | */ 224 | data(type: string, name: string, args: TerraformArgs): Data { 225 | const block = new Data(type, name, args); 226 | this.addBlocks(block); 227 | return block; 228 | } 229 | 230 | /** 231 | * Add module into Terraform. 232 | * 233 | * Refer to Terraform documentation on what can be put as arguments. 234 | * 235 | * @param name name 236 | * @param args arguments 237 | */ 238 | module(name: string, args: ModuleArgs): Module { 239 | const block = new Module(name, args); 240 | this.addBlocks(block); 241 | return block; 242 | } 243 | 244 | /** 245 | * Add output into Terraform. 246 | * 247 | * Refer to Terraform documentation on what can be put as arguments. 248 | * 249 | * @param name name 250 | * @param args arguments 251 | */ 252 | output(name: string, args: OutputArgs): Output { 253 | const block = new Output(name, args); 254 | this.addBlocks(block); 255 | return block; 256 | } 257 | 258 | /** 259 | * Add locals into Terraform. 260 | * 261 | * Refer to Terraform documentation on what can be put as arguments. 262 | * 263 | * @param args arguments 264 | */ 265 | locals(args: TerraformArgs): Locals { 266 | const block = new Locals(args); 267 | this.addBlocks(block); 268 | return block; 269 | } 270 | 271 | /** 272 | * Add variable into Terraform. 273 | * 274 | * Refer to Terraform documentation on what can be put as arguments. 275 | * 276 | * @param name name 277 | * @param args arguments 278 | * @param value variable value 279 | */ 280 | variable(name: string, args: VariableArgs, value?: any): Variable { 281 | const block = new Variable(name, args); 282 | this.addBlocks(block); 283 | if (value != null) { 284 | this.addVars({ [name]: value }); 285 | } 286 | return block; 287 | } 288 | 289 | /** 290 | * Add import into Terraform. 291 | * 292 | * Refer to Terraform documentation on what can be put as arguments. 293 | * 294 | * @param args arguments 295 | */ 296 | import(args: ImportArgs): Import { 297 | const block = new Import(args); 298 | this.addBlocks(block); 299 | return block; 300 | } 301 | 302 | /** 303 | * Add backend into Terraform. 304 | * 305 | * Refer to Terraform documentation on what can be put as type & arguments. 306 | * 307 | * @param type type 308 | * @param args arguments 309 | */ 310 | backend(type: string, args: TerraformArgs): Backend { 311 | const block = new Backend(type, args); 312 | this.addBlocks(block); 313 | return block; 314 | } 315 | 316 | /** 317 | * Add moved into Terraform. 318 | * 319 | * Refer to Terraform documentation on what can be put as type & arguments. 320 | * 321 | * @param args arguments 322 | */ 323 | moved(args: MovedArgs): Moved { 324 | const block = new Moved(args); 325 | this.addBlocks(block); 326 | return block; 327 | } 328 | 329 | /** 330 | * Add removed into Terraform. 331 | * 332 | * Refer to Terraform documentation on what can be put as type & arguments. 333 | * 334 | * @param args arguments 335 | */ 336 | removed(args: RemovedArgs): Removed { 337 | const block = new Removed(args); 338 | this.addBlocks(block); 339 | return block; 340 | } 341 | 342 | /** 343 | * Add variable values into Terraform. 344 | * 345 | * @param variables variables 346 | */ 347 | addVars(variables: TerraformArgs): this { 348 | this.#variables = { 349 | ...this.#variables, 350 | ...variables 351 | }; 352 | return this; 353 | } 354 | 355 | /** 356 | * Merge this instance with other TerraformGenerator instances. 357 | * 358 | * @param tfgs other instances 359 | */ 360 | merge(...tfgs: TerraformGenerator[]): this { 361 | tfgs.forEach(tfg => { 362 | this.addBlocks(...tfg.getBlocks()); 363 | this.addVars(tfg.getVars()); 364 | }); 365 | return this; 366 | } 367 | 368 | /** 369 | * Get arguments. 370 | */ 371 | getArguments(): TerraformArgs | undefined { 372 | return this.#arguments; 373 | } 374 | 375 | /** 376 | * Get blocks. 377 | */ 378 | getBlocks(): Block[] { 379 | return this.#blocks; 380 | } 381 | 382 | /** 383 | * Get variables. 384 | */ 385 | getVars(): TerraformArgs { 386 | return this.#variables; 387 | } 388 | 389 | } 390 | -------------------------------------------------------------------------------- /test/blocks/__snapshots__/Locals.test.ts.snap: -------------------------------------------------------------------------------- 1 | // Jest Snapshot v1, https://goo.gl/fbAQLP 2 | 3 | exports[`Locals 1`] = ` 4 | "locals{ 5 | arg0 = &tfgquot;a&tfgquot; 6 | arg1 = [ 7 | &tfgquot;b&tfgquot;, 8 | &tfgquot;c&tfgquot;, 9 | &tfgquot;d&tfgquot; 10 | ] 11 | arg2 = 0 12 | arg3 = [ 13 | 1, 14 | 2, 15 | 3 16 | ] 17 | arg4 = true 18 | arg5 = [ 19 | false, 20 | true, 21 | false 22 | ] 23 | arg6 = type.name.attr 24 | arg7 = [ 25 | type.name.attr, 26 | type.name.attr, 27 | type.name.attr 28 | ] 29 | arg8 = type.name 30 | arg9 = [ 31 | type.name, 32 | type.name, 33 | type.name 34 | ] 35 | arg10 = [ 36 | &tfgquot;e&tfgquot;, 37 | 4, 38 | true, 39 | type.name.attr, 40 | type.name 41 | ] 42 | arg11 = arg 43 | arg12 = <