Improved Rundeck-Node

This commit is contained in:
Jan Oberhauser 2020-03-15 19:20:41 +01:00
parent 07f0b95608
commit 1d43cbf3e7
6 changed files with 143 additions and 151 deletions

View file

@ -4,21 +4,16 @@ import {
} from 'n8n-workflow'; } from 'n8n-workflow';
export class Rundeck implements ICredentialType { export class RundeckApi implements ICredentialType {
name = 'rundeck'; name = 'rundeckApi';
displayName = 'Rundeck'; displayName = 'Rundeck API';
properties = [ properties = [
{ {
displayName: 'Url', displayName: 'Url',
name: 'url', name: 'url',
type: 'string' as NodePropertyTypes, type: 'string' as NodePropertyTypes,
default: '', default: '',
}, placeholder: 'http://127.0.0.1:4440',
{
displayName: 'Api Version',
name: 'apiVersion',
type: 'number' as NodePropertyTypes,
default: '',
}, },
{ {
displayName: 'Token', displayName: 'Token',

View file

@ -1,44 +0,0 @@
import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
export class Api {
private api: AxiosInstance;
constructor (config: AxiosRequestConfig) {
this.api = axios.create(config);
this.api.interceptors.request.use((param: AxiosRequestConfig) => ({
...param
}));
}
protected getUri (config?: AxiosRequestConfig): string {
return this.api.getUri(config);
}
protected request<T, R = AxiosResponse<T>> (config: AxiosRequestConfig): Promise<R> {
return this.api.request(config);
}
protected get<T, R = AxiosResponse<T>> (url: string, config?: AxiosRequestConfig): Promise<R> {
return this.api.get(url, config);
}
protected delete<T, R = AxiosResponse<T>> (url: string, config?: AxiosRequestConfig): Promise<R> {
return this.api.delete(url, config);
}
protected head<T, R = AxiosResponse<T>> (url: string, config?: AxiosRequestConfig): Promise<R> {
return this.api.head(url, config);
}
protected post<T, R = AxiosResponse<T>> (url: string, data?: string, config?: AxiosRequestConfig): Promise<R> {
return this.api.post(url, data, config);
}
protected put<T, R = AxiosResponse<T>> (url: string, data?: string, config?: AxiosRequestConfig): Promise<R> {
return this.api.put(url, data, config);
}
protected patch<T, R = AxiosResponse<T>> (url: string, data?: string, config?: AxiosRequestConfig): Promise<R> {
return this.api.patch(url, data, config);
}
}

View file

@ -5,8 +5,7 @@ import {
INodeType, INodeType,
INodeTypeDescription, INodeTypeDescription,
} from 'n8n-workflow'; } from 'n8n-workflow';
import { Parser } from 'xml2js'; import { RundeckApi } from './RundeckApi';
import { RundeckApi, RundeckCredentials } from "./RundeckApi";
export class Rundeck implements INodeType { export class Rundeck implements INodeType {
description: INodeTypeDescription = { description: INodeTypeDescription = {
@ -15,6 +14,7 @@ export class Rundeck implements INodeType {
icon: 'file:rundeck.png', icon: 'file:rundeck.png',
group: ['transform'], group: ['transform'],
version: 1, version: 1,
subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}',
description: 'Manage Rundeck API', description: 'Manage Rundeck API',
defaults: { defaults: {
name: 'Rundeck', name: 'Rundeck',
@ -24,28 +24,46 @@ export class Rundeck implements INodeType {
outputs: ['main'], outputs: ['main'],
credentials: [ credentials: [
{ {
name: 'rundeck', name: 'rundeckApi',
required: true, required: true,
} }
], ],
properties: [ properties: [
{
displayName: 'Resource',
name: 'resource',
type: 'options',
options: [
{
name: 'Job',
value: 'job',
},
],
default: 'job',
description: 'The resource to operate on.',
},
{ {
displayName: 'Operation', displayName: 'Operation',
name: 'operation', name: 'operation',
type: 'options', type: 'options',
options: [ options: [
{ {
name: 'Execute Job', name: 'Execute',
value: 'executeJob', value: 'execute',
description: 'Executes Job.', description: 'Executes job',
},
{
name: 'Get Metadata',
value: 'getMetadata',
description: 'Get metadata of a job',
}, },
], ],
default: 'executeJob', default: 'execute',
description: 'The operation to perform.', description: 'The operation to perform.',
}, },
// ---------------------------------- // ----------------------------------
// JobId // job:execute
// ---------------------------------- // ----------------------------------
{ {
displayName: 'Job Id', displayName: 'Job Id',
@ -54,7 +72,10 @@ export class Rundeck implements INodeType {
displayOptions: { displayOptions: {
show: { show: {
operation: [ operation: [
'executeJob' 'execute',
],
resource: [
'job',
], ],
}, },
}, },
@ -63,14 +84,10 @@ export class Rundeck implements INodeType {
required: true, required: true,
description: 'The job Id to execute.', description: 'The job Id to execute.',
}, },
// ----------------------------------
// Arguments
// ----------------------------------
{ {
displayName: 'Arguments', displayName: 'Arguments',
name: 'arguments', name: 'arguments',
placeholder: 'Arguments', placeholder: 'Add Argument',
type: 'fixedCollection', type: 'fixedCollection',
typeOptions: { typeOptions: {
multipleValues: true, multipleValues: true,
@ -78,7 +95,10 @@ export class Rundeck implements INodeType {
displayOptions: { displayOptions: {
show: { show: {
operation: [ operation: [
'executeJob' 'execute',
],
resource: [
'job',
], ],
}, },
}, },
@ -86,7 +106,7 @@ export class Rundeck implements INodeType {
options: [ options: [
{ {
name: 'arguments', name: 'arguments',
displayName: 'Add argument', displayName: 'Arguments',
values: [ values: [
{ {
displayName: 'Name', displayName: 'Name',
@ -104,7 +124,32 @@ export class Rundeck implements INodeType {
}, },
], ],
}, },
]
// ----------------------------------
// job:getMetadata
// ----------------------------------
{
displayName: 'Job Id',
name: 'jobid',
type: 'string',
displayOptions: {
show: {
operation: [
'getMetadata',
],
resource: [
'job',
],
},
},
default: '',
placeholder: 'Rundeck Job Id',
required: true,
description: 'The job Id to get metadata off.',
},
],
}; };
@ -114,58 +159,40 @@ export class Rundeck implements INodeType {
const items = this.getInputData(); const items = this.getInputData();
const returnData: IDataObject[] = []; const returnData: IDataObject[] = [];
const length = items.length as unknown as number; const length = items.length as unknown as number;
const credentials = this.getCredentials('rundeck');
if (credentials === undefined) {
throw new Error('No credentials got returned!');
}
const rundeckCredentials: RundeckCredentials = {
url: credentials.url as string,
apiVersion: credentials.apiVersion as number,
token: credentials.token as string
};
const operation = this.getNodeParameter('operation', 0) as string; const operation = this.getNodeParameter('operation', 0) as string;
const resource = this.getNodeParameter('resource', 0) as string;
for (let i = 0; i < length; i++) { for (let i = 0; i < length; i++) {
if (operation === 'executeJob') { const rundeckApi = new RundeckApi(this);
// ----------------------------------
// executeJob if (resource === 'job') {
// ---------------------------------- if (operation === 'execute') {
const rundeckApi = new RundeckApi(rundeckCredentials); // ----------------------------------
const jobid = this.getNodeParameter('jobid', i) as string; // job: execute
const rundeckArguments = (this.getNodeParameter('arguments', i) as IDataObject).arguments as IDataObject[]; // ----------------------------------
let response; const jobid = this.getNodeParameter('jobid', i) as string;
const rundeckArguments = (this.getNodeParameter('arguments', i) as IDataObject).arguments as IDataObject[];
try { const response = await rundeckApi.executeJob(jobid, rundeckArguments);
response = await rundeckApi.executeJob(jobid, rundeckArguments); returnData.push(response);
} else if (operation === 'getMetadata') {
const parser = new Parser({ // ----------------------------------
mergeAttrs: true, // job: getMetadata
explicitArray: false, // ----------------------------------
}); const jobid = this.getNodeParameter('jobid', i) as string;
const response = await rundeckApi.getJobMetadata(jobid);
// @ts-ignore
const json = await parser.parseStringPromise(response); returnData.push(response);
returnData.push({ json }); } else {
throw new Error(`The operation "${operation}" is not supported!`);
} catch(error) {
if(error.response && error.response.data && error.response.status) {
throw Error(`status: ${error.response.status}, response: ${(error.response.data).replace('\n', '')}`);
} else {
throw error;
}
} }
} else { } else {
throw new Error(`The operation "${operation}" is not supported!`); throw new Error(`The resource "${resource}" is not supported!`);
} }
} }
return [this.helpers.returnJsonArray(returnData)]; return [this.helpers.returnJsonArray(returnData)];
} }
} }

View file

@ -1,46 +1,59 @@
import { AxiosError, AxiosRequestConfig, AxiosResponse } from "axios"; import { OptionsWithUri } from 'request';
import { Api } from "./Api"; import { IExecuteFunctions } from 'n8n-core';
import * as https from 'https'; import { IDataObject } from 'n8n-workflow';
import { Xml } from "../Xml.node";
import { IDataObject } from "n8n-workflow";
export interface RundeckCredentials { export interface RundeckCredentials {
url: string; url: string;
apiVersion: number;
token: string; token: string;
} }
function acceptVersion(credentialsApiVersion: number, apiVersion: number) { export class RundeckApi {
if(apiVersion > credentialsApiVersion) {
throw Error('This endpoint is not supported for this version!');
}
}
export class RundeckApi extends Api {
private credentials: RundeckCredentials; private credentials: RundeckCredentials;
private executeFunctions: IExecuteFunctions;
constructor (credentials: RundeckCredentials) {
const config: AxiosRequestConfig = { constructor(executeFunctions: IExecuteFunctions) {
httpsAgent: new https.Agent({
rejectUnauthorized: false const credentials = executeFunctions.getCredentials('rundeckApi');
}),
if (credentials === undefined) {
throw new Error('No credentials got returned!');
}
this.credentials = credentials as unknown as RundeckCredentials;
this.executeFunctions = executeFunctions;
}
protected async request(method: string, endpoint: string, body: IDataObject, query: object) {
const options: OptionsWithUri = {
headers: { headers: {
'Accept': 'application/xml',
'user-agent': 'n8n', 'user-agent': 'n8n',
'X-Rundeck-Auth-Token': credentials.token, 'X-Rundeck-Auth-Token': this.credentials.token,
} },
rejectUnauthorized: false,
method,
qs: query,
uri: this.credentials.url + endpoint,
body,
json: true
}; };
super(config); try {
this.credentials = credentials; return await this.executeFunctions.helpers.request!(options);
} catch (error) {
let errorMessage = error.message;
if (error.response && error.response.body && error.response.body.message) {
errorMessage = error.response.body.message.replace('\n', '');
}
throw Error(`Rundeck Error [${error.statusCode}]: ${errorMessage}`);
}
} }
executeJob(jobId: string, args: IDataObject[]): Promise<Xml> {
acceptVersion(this.credentials.apiVersion, 12); executeJob(jobId: string, args: IDataObject[]): Promise<IDataObject> {
let params = ''; let params = '';
@ -49,15 +62,16 @@ export class RundeckApi extends Api {
params += "-" + arg.name + " " + arg.value + " "; params += "-" + arg.name + " " + arg.value + " ";
} }
} }
return this.post<Xml>(this.credentials.url + '/api/12/job/' + jobId + '/run?argString=' + params) const body = {
.then((response: AxiosResponse<Xml>) => { argString: params
const { data } = response; };
return data;
}) return this.request('POST', `/api/14/job/${jobId}/run`, body, {});
.catch((error: AxiosError) => {
throw error;
});
} }
} getJobMetadata(jobId: string): Promise<IDataObject> {
return this.request('GET', `/api/18/job/${jobId}/info`, {}, {});
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 825 B

After

Width:  |  Height:  |  Size: 319 B

View file

@ -83,7 +83,7 @@
"dist/credentials/Postgres.credentials.js", "dist/credentials/Postgres.credentials.js",
"dist/credentials/Redis.credentials.js", "dist/credentials/Redis.credentials.js",
"dist/credentials/RocketchatApi.credentials.js", "dist/credentials/RocketchatApi.credentials.js",
"dist/credentials/Rundeck.credentials.js", "dist/credentials/RundeckApi.credentials.js",
"dist/credentials/ShopifyApi.credentials.js", "dist/credentials/ShopifyApi.credentials.js",
"dist/credentials/SlackApi.credentials.js", "dist/credentials/SlackApi.credentials.js",
"dist/credentials/Smtp.credentials.js", "dist/credentials/Smtp.credentials.js",