Skip to content

Commit

Permalink
True NAS VM clone script
Browse files Browse the repository at this point in the history
  • Loading branch information
kisztof committed Aug 23, 2023
0 parents commit 65fa0df
Show file tree
Hide file tree
Showing 8 changed files with 794 additions and 0 deletions.
31 changes: 31 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
name: Build and Test Run VM Clone with Mocked TrueNAS endpoint

on:
push:
branches: [ master ]
pull_request:
branches: [ master ]

jobs:
build-and-run:

runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2
- name: Use Node.js
uses: actions/setup-node@v2
with:
node-version: '14'
- name: Install Dependencies
run: yarn install
- name: Start Mock TrueNAS Server
run: node tests/mockTrueNas.js &
- name: Test Run Script
env:
TRUE_NAS_URL: http://localhost:3000
TRUE_NAS_USERNAME: mock_username
TRUE_NAS_PASSWORD: mock_password
TEMPLATE_VM_ID: mock_template_id
NUM_VMS: 1
run: node clone_vms.js --url $TRUE_NAS_URL --username $TRUE_NAS_USERNAME --password $TRUE_NAS_PASSWORD --template_vm_id $TEMPLATE_VM_ID --num_vms $NUM_VMS
51 changes: 51 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Logs and Databases
*.log
*.sql
*.sqlite

# Runtime data
pids/
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# Node build artifacts
build/

# Dependency directories
node_modules/
jspm_packages/

# Typescript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional REPL history
.node_repl_history

# dotenv environment variables file
.env

# IDE-specific files
.DS_Store
*.swp
*.swo
*.idea/
.vscode/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) [2023] [Krzysztof Słomka]

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.
46 changes: 46 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# TrueNAS VM Clone Tool

This Node.js script allows you to automate the creation of virtual machines (VMs) in TrueNAS SCALE by cloning a specified template VM. You can specify the number of VMs you want to create, the template to use, and the authentication details for your TrueNAS system.

## Prerequisites

- Node.js (tested with version 14.x or higher)
- TrueNAS SCALE (ensure the API is accessible)

## Installation

First, clone the repository or download the script. Then navigate to the directory containing the script and install the required dependencies:

```bash
yarn install
```

## Usage

The script accepts the following command-line arguments:

- `--url`: The URL of your TrueNAS system.
- `--username`: Your TrueNAS username.
- `--password`: Your TrueNAS password.
- `--template_vm_id`: The ID of the template VM that you want to clone.
- `--num_vms`: The number of VMs you want to create.

Example command:

```bash
node create_vms.js --url http://your-truenas-ip --username YOUR_USERNAME --password YOUR_PASSWORD --template_vm_id YOUR_TEMPLATE_VM_ID --num_vms 10
```

Replace the placeholders with your specific details.

## Warning

Please use this script with caution, especially in a production environment. Ensure that you have the necessary resources available in your system for the number of VMs you want to create.

## Support and Contribution

Feel free to open an issue if you find any problems or have suggestions. Contributions through pull requests are welcome.

## License

This project is licensed under the MIT License. See the `LICENSE` file for details.
78 changes: 78 additions & 0 deletions clone_vms.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
const axios = require('axios');
const yargs = require('yargs/yargs');
const { hideBin } = require('yargs/helpers');

const argv = yargs(hideBin(process.argv))
.option('url', {
alias: 'u',
description: 'TrueNAS URL',
type: 'string',
})
.option('username', {
alias: 'n',
description: 'TrueNAS Username',
type: 'string',
})
.option('password', {
alias: 'p',
description: 'TrueNAS Password',
type: 'string',
})
.option('template_vm_id', {
alias: 't',
description: 'Template VM ID',
type: 'string',
})
.option('num_vms', {
alias: 'v',
description: 'Number of VMs to create',
type: 'number',
})
.help()
.alias('help', 'h')
.argv;

const createVms = async (url, username, password, template_vm_id, num_vms) => {
try {
const loginResponse = await axios.post(`${url}/api/v2.0/auth/login`, {
username: username,
password: password,
});

const token = loginResponse.headers['x-auth-token'];

for (let i = 1; i <= num_vms; i++) {
const payload = {
name: `New_Clone_VM_${i}`,
description: 'Cloned from template',
};

const response = await axios.post(
`${url}/api/v2.0/vm/${template_vm_id}/clone/`,
payload,
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
},
}
);

if (response.status === 200) {
console.log(`VM ${i} cloned successfully!`);
} else {
console.log(`Failed to clone VM ${i}. Response: ${response.statusText}`);
}
}

await axios.post(`${url}/api/v2.0/auth/logout`, null, {
headers: {
'Authorization': `Bearer ${token}`,
},
});
} catch (error) {
console.error(`An error occurred: ${error}`);
}
};

createVms(argv.url, argv.username, argv.password, argv.template_vm_id, argv.num_vms);
16 changes: 16 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "truenas-vm-clone-tool",
"version": "1.0.0",
"description": "A script to create VMs using TrueNAS API",
"main": "clone_vms.js",
"scripts": {
"start": "node clone_vms.js"
},
"dependencies": {
"axios": "^0.21.4",
"yargs": "^17.0.1",
"express": "^4.17.1"
},
"author": "Krzysztof Słomka",
"license": "MIT"
}
22 changes: 22 additions & 0 deletions tests/mockTrueNas.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const express = require('express');
const app = express();
const port = 3000;

app.use(express.json());

app.post('/api/v2.0/auth/login', (req, res) => {
res.header('x-auth-token', 'mock-token');
res.send({ success: true });
});

app.post('/api/v2.0/vm/:template_vm_id/clone/', (req, res) => {
res.send({ status: 200 });
});

app.post('/api/v2.0/auth/logout', (req, res) => {
res.send({ success: true });
});

app.listen(port, () => {
console.log(`Mock TrueNAS server listening at http://localhost:${port}`);
});
Loading

0 comments on commit 65fa0df

Please sign in to comment.