Skip to content

Instantly share code, notes, and snippets.

@jvillste
Created January 26, 2024 16:06
Show Gist options
  • Save jvillste/a0c3942b419057cfdb86bc0a12c618de to your computer and use it in GitHub Desktop.
Save jvillste/a0c3942b419057cfdb86bc0a12c618de to your computer and use it in GitHub Desktop.
(ns ansible
(:require
[clojure.java.shell :as shell]
[clojure.string :as string]
[clojure.test :refer [deftest is]]))
(defn- keyword-to-string [x]
(if (keyword? x)
(name x)
x))
(defn ansible-parameters [a-map]
(str "{"
(string/join ", "
(for [[key value] a-map]
(str "\""
(keyword-to-string key)
"\": \""
(keyword-to-string value)
"\"")))
"}"))
(deftest test-ansible-parameters
(is (= "{\"cmd\": \"ls\", \"chdir\": \"/\"}"
(ansible-parameters {:cmd "ls"
:chdir "/"}))))
(defn run-ansible [user host key-file module module-parameters & [additional-ansible-parameters]]
(let [result (apply shell/sh
"ansible"
"-i" (str host ",")
"--key-file" key-file
"-e" (str "ansible_ssh_user=" user)
"-m" (name module)
"all"
"-a" (ansible-parameters module-parameters)
additional-ansible-parameters)]
(when (not= 0 (:exit result))
(throw (Exception. (pr-str result))))
result))
(comment
(run-ansible "myaccount"
"example.com"
"~/.ssh/id_rsa"
:shell
{:cmd "ls -l"})
(run-ansible "myaccount"
"example.com"
"~/.ssh/id_rsa"
:shell
{:cmd "ls -l"}
"--check"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment