Skip to content

Commit

Permalink
Merge pull request #11 from hahnavi/dev
Browse files Browse the repository at this point in the history
Add new modules:
- lineinfile
- template
  • Loading branch information
hahnavi authored Dec 16, 2024
2 parents 7eb26e6 + 9da59f3 commit b05412e
Show file tree
Hide file tree
Showing 10 changed files with 407 additions and 155 deletions.
48 changes: 48 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@ edition = "2021"
[dependencies]
anyhow = "1.0.93"
clap = { version = "4.5.21", features = ["derive"] }
mlua = { version = "0.10.1", features = ["anyhow", "async", "luajit", "macros", "vendored"] }
minijinja = "2.5.0"
mlua = { version = "0.10.1", features = ["anyhow", "async", "luajit", "macros", "serialize", "vendored"] }
rand = "0.8.5"
regex = "1.11.1"
rustyline = "15.0.0"
Expand Down
161 changes: 13 additions & 148 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,7 @@ Komandan is a server automation tool that simplifies remote server management by
- [Usage](#usage)
- [`komando` function](#komando-function)
- [Modules](#modules)
- [`cmd` module](#cmd-module)
- [`script` module](#script-module)
- [`upload` module](#upload-module)
- [`download` module](#download-module)
- [`apt` module](#apt-module)
- [Built-in functions](#built-in-functions)
- [`komandan.filter_hosts`](#komandan-filter-hosts)
- [`komandan.set_defaults`](#komandan-set-defaults)
- [Error Handling](#error-handling)
- [Contributing](#contributing)
- [License](#license)
Expand Down Expand Up @@ -129,154 +122,26 @@ The `komando` function returns a table with the following fields:

## Modules

Komandan provides built-in modules for common tasks. They are accessible through the `komandan.modules` table.
Komandan provides built-in modules for common tasks, accessible through the `komandan.modules` table. Here's a quick overview of the available modules:

### `cmd` module
- **`cmd`**: Execute shell commands on the remote host.
- **`script`**: Run scripts on the remote host, either from a local file or provided directly.
- **`upload`**: Upload files to the remote host.
- **`download`**: Download files from the remote host.
- **`apt`**: Manage packages on Debian/Ubuntu systems using `apt`.
- **`lineinfile`**: Insert or replace lines in a file.
- **`template`**: Render a jinja template file on the remote host.

Executes a shell command on the remote host.

**Arguments:**

- `cmd`: The command to execute.

**Example:**

```lua
local task = {
name = "Get system information",
komandan.modules.cmd({
cmd = "uname -a",
}),
}
```

### `script` module

Executes a script on the remote host.

**Arguments:**

- `script`: The script content to execute.
- `from_file`: The local path to a script file to upload and execute. (`script` and `from_file` are mutually exclusive)
- `interpreter`: The interpreter to use (e.g., "python3", "bash"). If not specified, the default shell is used.

**Example:**

```lua
local task = {
name = "Run a Python script",
komandan.modules.script({
from_file = "scripts/hello.py",
interpreter = "python3",
}),
}
```

### `upload` module

Uploads a file to the remote host.

**Arguments:**

- `src`: The local path of the file to upload.
- `dst`: The destination path on the remote host.

**Example:**

```lua
local task = {
name = "Upload a configuration file",
komandan.modules.upload({
src = "configs/app.conf",
dst = "/etc/app.conf",
}),
}
```

### `download` module

Downloads a file from the remote host.

**Arguments:**

- `src`: The path of the file to download on the remote host.
- `dst`: The local destination path.

**Example:**

```lua
local task = {
name = "Download a log file",
komandan.modules.download({
src = "/var/log/app.log",
dst = "logs/app.log",
}),
}
```

### `apt` module

Manages packages on Debian/Ubuntu systems using `apt`.

**Arguments:**

- `package`: The name of the package to manage.
- `action`: The action to perform (`install`, `remove`, `purge`, `upgrade`, `autoremove`; default: `install`).
- `update_cache`: Whether to update the package cache before the action (default: `false`).
- `install_recommends`: Whether to install recommended packages (default: `true`).

**Example:**

```lua
local task = {
name = "Install Nginx",
komandan.modules.apt({
package = "nginx",
action = "install",
update_cache = true,
elevate = true,
}),
}
```
For detailed explanations, arguments, and examples of each module, please refer to the [Modules section of the Komandan Documentation Site](https://komandan.vercel.app/docs/modules).

## Built-in functions

### `komandan.filter_hosts`
Komandan offers built-in functions to enhance scripting capabilities:

Filters a list of hosts based on a pattern.
- **`komandan.filter_hosts`**: Filters a list of hosts based on a pattern.
- **`komandan.set_defaults`**: Sets default values for host connection parameters.

**Arguments:**

- `hosts`: A table of host definitions.
- `pattern`: A string to match against host names or tags. Use `~` at the beginning for regular expression matching.

**Returns:**

A table containing only the hosts that match the pattern.

**Example:**

```lua
local webservers = komandan.filter_hosts(hosts, "webserver")
local dbservers = komandan.filter_hosts(hosts, "~^db") -- Using a regex
```

### `komandan.set_defaults`

Sets default values for host connection parameters.

**Arguments:**

- `data`: A table of default values (e.g., `user`, `private_key_file`).

**Example:**

```lua
komandan.set_defaults({
user = "admin",
port = 2222,
})
```
For detailed descriptions and usage examples of these functions, please visit the [Built-in Functions section of the Komandan Documentation Site](https://komandan.vercel.app/docs/functions/).

## Error Handling

Expand Down
19 changes: 19 additions & 0 deletions examples/lineinfile.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
local host = {
name = "server1",
address = "10.20.30.41",
user = "user1",
private_key_file = os.getenv("HOME") .. "/.ssh/id_ed25519",
}

local task = {
name = "Add a line in a file",
komandan.modules.lineinfile({
path = "/tmp/target_file.txt",
line = "This is a new line",
state = "present",
create = true,
backup = true,
}),
}

komandan.komando(host, task)
24 changes: 24 additions & 0 deletions examples/template.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
local host = {
name = "server1",
address = "10.20.30.41",
user = "user1",
private_key_file = os.getenv("HOME") .. "/.ssh/id_ed25519",
}

local task = {
name = "Write a file using a template",
komandan.modules.template({
src = "/tmp/template1.j2",
dst = "/tmp/target_file.txt",
vars = {
name = "John Doe",
age = 30
}
}),
}

komandan.komando(host, task)


-- Jinja template example:
-- {{ name }} is {{ age }} years old
9 changes: 5 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use args::Args;
use clap::Parser;
use mlua::{chunk, Error::RuntimeError, Integer, Lua, MultiValue, Table, Value};
use modules::{apt, base_module, cmd, download, script, upload};
use modules::{apt, base_module, cmd, lineinfile, download, script, template, upload};
use rustyline::DefaultEditor;
use ssh::{ElevateMethod, Elevation, SSHAuthMethod, SSHSession};
use std::{env, path::Path};
Expand Down Expand Up @@ -76,7 +76,9 @@ fn setup_komandan_table(lua: &Lua) -> mlua::Result<()> {
let modules_table = lua.create_table()?;
modules_table.set("apt", lua.create_function(apt)?)?;
modules_table.set("cmd", lua.create_function(cmd)?)?;
modules_table.set("lineinfile", lua.create_function(lineinfile)?)?;
modules_table.set("script", lua.create_function(script)?)?;
modules_table.set("template", lua.create_function(template)?)?;
modules_table.set("upload", lua.create_function(upload)?)?;
modules_table.set("download", lua.create_function(download)?)?;
komandan.set("modules", modules_table)?;
Expand Down Expand Up @@ -265,19 +267,16 @@ async fn komando(lua: Lua, (host, task): (Value, Value)) -> mlua::Result<Table>

for pair in env_defaults.pairs() {
let (key, value): (String, String) = pair?;
println!("{}={}", key, value);
ssh.set_env(&key, &value);
}

for pair in env_host.pairs() {
let (key, value): (String, String) = pair?;
println!("{}={}", key, value);
ssh.set_env(&key, &value);
}

for pair in env_task.pairs() {
let (key, value): (String, String) = pair?;
println!("{}={}", key, value);
ssh.set_env(&key, &value);
}

Expand Down Expand Up @@ -449,7 +448,9 @@ mod tests {
let modules_table = komandan_table.get::<Table>("modules").unwrap();
assert!(modules_table.contains_key("apt").unwrap());
assert!(modules_table.contains_key("cmd").unwrap());
assert!(modules_table.contains_key("lineinfile").unwrap());
assert!(modules_table.contains_key("script").unwrap());
assert!(modules_table.contains_key("template").unwrap());
assert!(modules_table.contains_key("upload").unwrap());
assert!(modules_table.contains_key("download").unwrap());
}
Expand Down
Loading

0 comments on commit b05412e

Please sign in to comment.