This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

Examples

Komandan provides several examples that can be used to help you get started with Komandan.

1 - Simple Task

This example shows how to use the komando function to execute a simple command task on a remote server.

local host = {
    address = "10.20.30.41",
    user = "user1",
    private_key_file = "/path/to/private/key",
}

local task = {
    name = "Create a new directory",
    komandan.modules.cmd({
        cmd = "mkdir /tmp/new_dir"
    })
}

komandan.komando(host, task)

2 - Multi Host and Task

This example shows how to use multiple hosts and tasks in using Komandan.

hosts.lua:

return {
  {
    name = "server1",
    address = "10.20.30.41",
    user = "user2",
    tags = { "webserver" },
  },
  {
    name = "server2",
    address = "10.20.30.42",
    user = "user2",
    tags = { "dbserver" },
  },
  {
    address = "10.20.30.43",
    private_key_file = os.getenv("HOME") .. "/.ssh/id_ed25519",
    tags = { "dbserver" },
  },
}

main.lua:

local hosts = require("hosts")

komandan.set_defaults({
  user = "user1",
  private_key_file = os.getenv("HOME") .. "/.ssh/id_ed25519",
})

local tasks = {
  {
    name = "Create a directory",
    komandan.modules.cmd({
      cmd = "mkdir /tmp/newdir",
    }),
  },
  {
    name = "Delete a directory",
    komandan.modules.cmd({
      cmd = "rm -rf /tmp/newdir",
    }),
  },
}

local filtered_hosts = komandan.filter_hosts(hosts, "dbserver")

for _, task in pairs(tasks) do
  for _, host in pairs(filtered_hosts) do
    komandan.komando(host, task)
  end
end

This example will create a directory on all hosts that has name or tag dbserver and then delete the directory.