Skip to content

Instantly share code, notes, and snippets.

@imod
Created November 20, 2020 07:26
Show Gist options
  • Save imod/9a664c38d40256726028ab5a3b7f108f to your computer and use it in GitHub Desktop.
Save imod/9a664c38d40256726028ab5a3b7f108f to your computer and use it in GitHub Desktop.
Pulumi resource to execute a shell command localy
import * as pulumi from "@pulumi/pulumi";
// Use like this:
// var command = "docker ps -a"
// const myResource = new ShellCommand("List Files", {command: command, env: {'FOO': 'bar'}, runAllways: false});
export interface ShellCommandArgs {
uniqueId?: pulumi.Input<string>;
command: pulumi.Input<string>;
env: object;
runAllways?: pulumi.Input<boolean>;
}
interface ShellCommandProviderArgs {
uniqueId: string;
command: string;
env: object;
runAllways?: boolean;
}
const commandProp = "command";
const runAllwaysProp = "runAllways";
// a resource to execute a shell script
// the script will
//
// idea taken from: https://github.com/pulumi/examples/blob/master/azure-ts-static-website/staticWebsite.ts
// details to Dynamic Providers: https://www.pulumi.com/docs/intro/concepts/programming-model/#dynamicproviders
const shellCommandProvider: pulumi.dynamic.ResourceProvider = {
async create(inputs: ShellCommandProviderArgs) {
const { execSync } = require("child_process");
execSync(inputs.command, {
env: inputs.env ? inputs.env : {},
stdio: "inherit",
});
return { id: `${inputs.uniqueId}ShellCommand`, outs: {} };
},
async check(
olds: ShellCommandProviderArgs,
news: ShellCommandProviderArgs
): Promise<pulumi.dynamic.CheckResult> {
const failures = [];
if (news.command === undefined) {
failures.push({
property: commandProp,
reason: `required property '${commandProp}' missing`,
});
}
// if undefined: allways run
if (news.runAllways == undefined || news.runAllways) {
news.runAllways = true;
}
return { inputs: news, failures };
},
async diff(
id: pulumi.ID,
olds: ShellCommandProviderArgs,
news: ShellCommandProviderArgs
): Promise<pulumi.dynamic.DiffResult> {
const replaces = [];
if (olds[commandProp] !== news.command) {
// FIXME for some reason this `olds.command` currently is allways `undefined`
// -> command will allways be exected
pulumi.log.warn(
`command changed: old=${olds.command}, new=${news.command}`
);
replaces.push(commandProp);
}
var hasChanges = replaces.length > 0;
if (news.runAllways === true) {
hasChanges = true;
}
return { replaces, changes: hasChanges };
},
};
export class ShellCommand extends pulumi.dynamic.Resource {
constructor(
name: string,
props: ShellCommandArgs,
opts?: pulumi.CustomResourceOptions
) {
super(shellCommandProvider, name, { ...props, uniqueId: name }, opts);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment