Creating an environment in Node.js
This article presents an example of using the Cloud Services Management REST API to create an environment with an access key in Node.js.
This example works only with the On-Premises version.
This example needs Node.js 18 or later. It uses only what Node.js has built in: fetch and crypto.
The script creates an environment with an access key.
Set ENVIRONMENTS_MANAGEMENT_SECRET_KEY and APPLICATION_ENDPOINT to the values from your configuration. Save the script as create-environment.mjs.
import crypto from 'node:crypto';
const ENVIRONMENTS_MANAGEMENT_SECRET_KEY = 'secret';
const APPLICATION_ENDPOINT = 'http://localhost:8000';
const newEnvironment = {
id: _randomString( 20 ), // required length 20
name: 'Production',
organizationId: _randomString( 60 ), // required length 10-60
accessKeys: [
{
value: _randomString( 100 ) // required length 10-120
}
],
services: []
};
await _send( 'POST', '/environments', newEnvironment );
console.log( `EnvironmentId: ${ newEnvironment.id }` );
console.log( `AccessKey: ${ newEnvironment.accessKeys[ 0 ].value }` );
async function _send( method, path, body ) {
const timestamp = Date.now();
const signature = _generateSignature( ENVIRONMENTS_MANAGEMENT_SECRET_KEY, method, path, timestamp, body );
const response = await fetch( `${ APPLICATION_ENDPOINT }${ path }`, {
method,
headers: {
'Content-Type': 'application/json',
'X-CS-Signature': signature,
'X-CS-Timestamp': String( timestamp )
},
body: JSON.stringify( body )
} );
if ( !response.ok ) {
throw new Error( `${ method } ${ path } answered ${ response.status }: ${ await response.text() }` );
}
}
function _generateSignature( apiSecret, method, path, timestamp, body ) {
const hmac = crypto.createHmac( 'SHA256', apiSecret );
hmac.update( `${ method.toUpperCase() }${ path }${ timestamp }` );
if ( body ) {
hmac.update( Buffer.from( JSON.stringify( body ) ) );
}
return hmac.digest( 'hex' );
}
function _randomString( length ) {
return crypto.randomBytes( length / 2 ).toString( 'hex' );
}Run:
node create-environment.mjsThe script prints the environment ID and the access key. Keep the access key on your server.
If your server uses a self-signed certificate, run the script with NODE_EXTRA_CA_CERTS=<path to your CA certificate>.
The script does not add an API secret. You need one to sign calls to the REST API, such as a bundle upload. Add it in the Management Panel. This is the way we recommend. To do it from a script, use the Management REST API.