创建使用 Node.js 调用 vRealize Automation 项目 API 的示例脚本。
前提条件
下载并安装 Node.js 12。请参见 Node.js 下载。
过程
- 在本地计算机上,打开命令行 shell。
- 创建
vro-node-vra
文件夹。mkdir vro-node-vra
- 导航到
vro-node-vra
文件夹。cd vro-node-vra
- 创建名为 handler.js 的 Node.js 脚本。
touch handler.js
handler.js 脚本必须定义一个接受如下两个参数的函数:vRealize Orchestrator 工作流运行的上下文和绑定的 vRealize Orchestrator 输入。exports.handler = (context, inputs) => { console.log('Hello, your inputs were ' + inputs); return null; }
注: 使用标准日志记录库时,在使用脚本的操作中记录的所有内容也会显示在工作流日志中。脚本的输入和返回内容必须在 vRealize Orchestrator 客户端中具有已配置的相应输入参数和返回类型。例如,脚本中的vRAUrl
输入必须在 vRealize Orchestrator 客户端中具有名为vRAUrl
的相应输入参数。同样,如果脚本返回字符串值,则在 vRealize Orchestrator 客户端中配置的返回类型也必须是字符串类型。如果操作返回复合类型对象,则可以使用Properties
或Composite Type
返回类型。 - 安装 Node.js 请求模块。
npm install request
重要事项: 第三方依赖关系模块必须安装在主vro-node-vra
脚本文件夹中的根级别 node_modules 文件夹中。请勿移动或重命名此文件夹。 - 将请求模块添加到 handler.js 脚本中。
const request = require('request'); exports.handler = (context, inputs) => { console.log('Hello, your inputs were ' + inputs); return null; }
- 创建对 vRealize Automation 项目 API 的 GET 请求。
const token = ''; const vRAUrl = ''; request.get(vRAUrl + '/iaas/api/projects', { 'auth': { 'bearer': token } }, function (error, response, body) { console.log('Got response ' + body); });
- 定义
token
和vRAUrl
值。- 使用 vRealize Automation 身份验证服务 API 检索访问令牌。请参见获取 vRealize Automation API 的访问令牌。
- 对于
vRAUrl
值,请定义脚本,使其使用具有相同名称的 vRealize Orchestrator 输入参数。const vRAUrl = inputs.vRAUrl;
- 将新值添加到 handler.js 文件中。
const request = require('request'); exports.handler = (context, inputs, callback) => { const vRAUrl = inputs.vRAUrl; const token = 'ACCESS_TOKEN'; request.get(vRAUrl + '/iaas/api/projects', { 'auth': { 'bearer': token } }, function (error, response, body) { console.log('Got response ' + body); callback(null, JSON.parse(body)); }); }
注: 由于来自 vRealize Automation 项目 API 的响应为 JSON 格式,因此请对 vRealize Orchestrator 操作使用Properties
或Composite Type
返回类型。
- 创建一个 ZIP 包,其中包含 handler.js 文件和请求模块的 node_modules 文件夹。
zip -r --exclude=*.zip -X vro-node-vra.zip .
后续步骤
将 Node.js 脚本导入到 vRealize Orchestrator 操作。请参见在 vRealize Orchestrator 客户端中创建操作。