Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: bring tfresource - custom terraform resources #35

Closed
wants to merge 14 commits into from
29 changes: 29 additions & 0 deletions .github/workflows/tfresource-pull.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
name: tfresource-pull
on:
pull_request:
paths:
- tfresource/**
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
sparse-checkout: tfresource
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: 18.x
registry-url: https://registry.npmjs.org
- name: Install winglang
run: npm i -g winglang
- name: Install dependencies
run: npm install --include=dev
working-directory: tfresource
- name: Test
run: wing test
working-directory: tfresource
- name: Pack
run: wing pack
working-directory: tfresource
37 changes: 37 additions & 0 deletions .github/workflows/tfresource-release.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
name: tfresource-release
on:
push:
branches:
- main
paths:
- tfresource/**
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
sparse-checkout: tfresource
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: 18.x
registry-url: https://registry.npmjs.org
- name: Install winglang
run: npm i -g winglang
- name: Install dependencies
run: npm install --include=dev
working-directory: tfresource
- name: Test
run: wing test
working-directory: tfresource
- name: Pack
run: wing pack
working-directory: tfresource
- name: Publish
run: npm publish --access=public --registry https://registry.npmjs.org --tag
latest *.tgz
working-directory: tfresource
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
2 changes: 2 additions & 0 deletions tfresource/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
target/
node_modules/
21 changes: 21 additions & 0 deletions tfresource/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Wing

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
120 changes: 120 additions & 0 deletions tfresource/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
# tfresource

A [winglang](https://winglang.io) library for creating custom Terraform resources.

Useful if there is no Terraform provider for a service you wish to provision in your app or if you
want more customization of the control plane.

## Prerequisites

* [winglang](https://winglang.io).

## Installation

```sh
npm i @winglibs/tfresource
```

## Usage

The `tfresource.TerraformResource` class represents a Terraform resource.

Use the `onXxx` methods to register handlers for the four Terraform lifecycle events:

* `onCreate(handler: inflight (): Json)` - create the resource and return the state to store.
* `onRead(handler: inflight (Json): Json)` - read the live state of the resource given the stored state.
* `onUpdate(handler: inflight (Json): Json)` - update the resource to the given state and return the new state to store.
* `onDelete(handler: inflight (Json): Json?)` - delete the resource given the stored state.

Let's look at an example which implements a `File` resource:

```js
bring tfresource as tfr;
bring fs;
bring util;

struct FileState {
hash: str;
path: str;
}

class File {
new(path: str, data: str) {
let r = new tfr.TerraformResource();

r.onCreate(inflight () => {
fs.writeFile(path, data);
return this.state(path, data);
});

r.onDelete(inflight (state) => {
let s = FileState.fromJson(state);
fs.remove(s.path);
});

r.onRead(inflight (state) => {
return this.state(path, data);
});
}

inflight state(path: str, data: str): FileState {
return {
hash: util.sha256(data),
path: path,
};
}
}
```

Now, we can use this new resource like this:

```js
new File("hello.txt", "my file") as "hello";
new File("world.txt", "your file") as "world";
```

If we compile this to `tf-*` and apply:

```sh
wing compile -t tf-aws main.w
cd target/main.tfaws
terraform init
terraform apply
```

You'll notice two new files:

```sh
$ cat hello.txt
my file
$ cat world.txt
your file
```

Now, let's change our code to:

```js
new File("hello1.txt", "my file") as "hello";
new File("world.txt", "your file 2") as "world";
```

Notice that we've changed the *name* of the first file and the *contents* of the 2nd file.

Compile and apply:

```sh
wing compile -t tf-aws main.w
cd target/main.tfaws
terraform apply
```

Now, you'll see that `hello.txt` was *renamed* to `hello1.txt` and `world.txt` includes the new
content. How cool is that?

## Maintainers

* [@eladb](https://github.com/eladb)

## License

This library is licensed under the [MIT License](./LICENSE).
38 changes: 38 additions & 0 deletions tfresource/examples/file.main.w
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
bring "../lib.w" as tfr;
bring fs;
bring util;

struct FileState {
hash: str;
path: str;
}

class File {
new(path: str, data: str) {
let r = new tfr.TerraformResource();

r.onCreate(inflight () => {
fs.writeFile(path, data);
return this.state(path, data);
});

r.onDelete(inflight (state) => {
let s = FileState.fromJson(state);
fs.remove(s.path);
});

r.onRead(inflight (state) => {
return this.state(path, data);
});
}

inflight state(path: str, data: str): FileState {
return {
hash: util.sha256(data),
path: path,
};
}
}

new File("hello1.txt", "my file") as "hello";
new File("world.txt", "your file2") as "world";
101 changes: 101 additions & 0 deletions tfresource/lib.w
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
bring "cdktf" as cdktf;
bring fs;
bring cloud;
bring util;

pub class TerraformResource {
commands: MutJson;

new() {
this.setupProvider();

this.commands = {};

class Shell extends cdktf.TerraformResource {
c: MutJson;

new(commands: MutJson) {
super(terraformResourceType: "shell_script");
this.c = commands;
}

pub synthesizeAttributes(): Json {
return {
lifecycle_commands: Json.deepCopy(this.c),
};
}
}

new Shell(this.commands);
}

pub onCreate(handler: inflight (): Json) {
let prog = this.toExecutable("create", handler);
this.commands.set("create", "node {prog}");
}

pub onRead(handler: inflight (Json): Json) {
let prog = this.toExecutable("read", handler);
this.commands.set("read", "node {prog}");
}

pub onUpdate(handler: inflight (Json): Json) {
let prog = this.toExecutable("update", handler);
this.commands.set("update", "node {prog}");
}

pub onDelete(handler: inflight (Json): Json?) {
let prog = this.toExecutable("delete", handler);
this.commands.set("delete", "node {prog}");
}

toExecutable(name: str, handler: inflight (Json): Json?): str {
let workdir = std.Node.of(this).app.workdir;
let code: str = unsafeCast(handler)?._toInflight();
eladb marked this conversation as resolved.
Show resolved Hide resolved

let path = fs.join(workdir, "{name}-{this.node.addr}.js");
let wrapper = "
skorfmann marked this conversation as resolved.
Show resolved Hide resolved
const fs = require('fs');
const data = fs.readFileSync(0, 'utf-8');
const input = data ? JSON.parse(data) : \{};
console.log = console.error;
const invoke = async () => ({code}).handle(input);
invoke().then(output => \{
output = output ?? \{};
process.stdout.write(JSON.stringify(output));
}).catch(e => \{
console.error(e);
process.exit(1);
});
";
fs.writeFile(path, wrapper);
return fs.relative(fs.dirname(fs.absolute(workdir)), path);
}

setupProvider() {
let uid = "TerraformProvider:scottwinkler-shell";
let root = std.Node.of(this).root;
let rootNode = std.Node.of(root);

if rootNode.tryFindChild(uid)? {
// already installed
return;
}

class ShellProvider extends cdktf.TerraformProvider {
new() {
super(
terraformResourceType: "shell",
terraformProviderSource: "scottwinkler/shell",
terraformGeneratorMetadata: {
providerName: "shell",
providerVersion: "1.7.10",
providerVersionConstraint: "~> 1.0"
},
);
}
}

new ShellProvider() as uid in root;
}
}
Loading
Loading