make function def deprecated replace by task

This commit is contained in:
ansgarz 2022-03-18 22:04:32 +01:00
parent 908ac00a3b
commit 16c6292ca3
45 changed files with 208 additions and 251 deletions

View file

@ -2,7 +2,6 @@ package org.domaindrivenarchitecture.provs.desktop.infrastructure
import org.domaindrivenarchitecture.provs.framework.core.Prov import org.domaindrivenarchitecture.provs.framework.core.Prov
import org.domaindrivenarchitecture.provs.framework.core.ProvResult import org.domaindrivenarchitecture.provs.framework.core.ProvResult
import org.domaindrivenarchitecture.provs.framework.core.endingWithFileSeparator
import org.domaindrivenarchitecture.provs.framework.core.getResourceAsText import org.domaindrivenarchitecture.provs.framework.core.getResourceAsText
import org.domaindrivenarchitecture.provs.framework.ubuntu.filesystem.base.addTextToFile import org.domaindrivenarchitecture.provs.framework.ubuntu.filesystem.base.addTextToFile
import org.domaindrivenarchitecture.provs.framework.ubuntu.filesystem.base.createDir import org.domaindrivenarchitecture.provs.framework.ubuntu.filesystem.base.createDir
@ -12,11 +11,11 @@ import java.io.File
private val resourcePath = "org/domaindrivenarchitecture/provs/desktop/infrastructure/" private val resourcePath = "org/domaindrivenarchitecture/provs/desktop/infrastructure/"
fun Prov.configureBash() = def { fun Prov.configureBash() = task {
configureBashForUser() configureBashForUser()
} }
fun Prov.configureBashForUser(): ProvResult = def { fun Prov.configureBashForUser(): ProvResult = task {
val dirname = "~/.bashrc.d" val dirname = "~/.bashrc.d"
if(!dirExists(dirname)) { if(!dirExists(dirname)) {
createDir(dirname) createDir(dirname)

View file

@ -7,7 +7,7 @@ import org.domaindrivenarchitecture.provs.framework.ubuntu.install.base.aptInsta
import org.domaindrivenarchitecture.provs.framework.ubuntu.web.base.downloadFromURL import org.domaindrivenarchitecture.provs.framework.ubuntu.web.base.downloadFromURL
fun Prov.installDevOps() = def { fun Prov.installDevOps() = task {
installTerraform() installTerraform()
installKubectlAndTools() installKubectlAndTools()
installYq() installYq()
@ -18,7 +18,7 @@ fun Prov.installDevOps() = def {
fun Prov.installYq( fun Prov.installYq(
version: String = "4.13.2", version: String = "4.13.2",
sha256sum: String = "d7c89543d1437bf80fee6237eadc608d1b121c21a7cbbe79057d5086d74f8d79" sha256sum: String = "d7c89543d1437bf80fee6237eadc608d1b121c21a7cbbe79057d5086d74f8d79"
): ProvResult = def { ): ProvResult = task {
val path = "/usr/bin/" val path = "/usr/bin/"
val filename = "yq" val filename = "yq"
if (!fileExists(path + filename)) { if (!fileExists(path + filename)) {
@ -35,7 +35,7 @@ fun Prov.installYq(
} }
} }
fun Prov.installKubectlAndTools(): ProvResult = def { fun Prov.installKubectlAndTools(): ProvResult = task {
val resourcePath = "org/domaindrivenarchitecture/provs/desktop/infrastructure" val resourcePath = "org/domaindrivenarchitecture/provs/desktop/infrastructure"
task("installKubectl") { task("installKubectl") {
@ -88,7 +88,7 @@ fun Prov.installKubectlAndTools(): ProvResult = def {
} }
} }
fun Prov.installTerraform(): ProvResult = def { fun Prov.installTerraform(): ProvResult = task {
val dir = "/usr/lib/tfenv/" val dir = "/usr/lib/tfenv/"
if (!dirExists(dir)) { if (!dirExists(dir)) {
@ -105,7 +105,7 @@ fun Prov.installTerraform(): ProvResult = def {
// -------------------------------------------- AWS credentials file ----------------------------------------------- // -------------------------------------------- AWS credentials file -----------------------------------------------
fun Prov.installAwsCredentials(id: String = "REPLACE_WITH_YOUR_ID", key: String = "REPLACE_WITH_YOUR_KEY"): ProvResult = fun Prov.installAwsCredentials(id: String = "REPLACE_WITH_YOUR_ID", key: String = "REPLACE_WITH_YOUR_KEY"): ProvResult =
def { task {
val dir = "~/.aws" val dir = "~/.aws"
if (!dirExists(dir)) { if (!dirExists(dir)) {

View file

@ -3,7 +3,7 @@ package org.domaindrivenarchitecture.provs.desktop.infrastructure
import org.domaindrivenarchitecture.provs.framework.core.Prov import org.domaindrivenarchitecture.provs.framework.core.Prov
import org.domaindrivenarchitecture.provs.framework.ubuntu.install.base.aptInstall import org.domaindrivenarchitecture.provs.framework.ubuntu.install.base.aptInstall
fun Prov.installDocker() = def { fun Prov.installDocker() = task {
aptInstall("containerd docker.io") aptInstall("containerd docker.io")
if (!chk("getent group docker")) { if (!chk("getent group docker")) {
cmd("sudo groupadd docker") cmd("sudo groupadd docker")

View file

@ -5,7 +5,7 @@ import org.domaindrivenarchitecture.provs.framework.ubuntu.filesystem.base.creat
import org.domaindrivenarchitecture.provs.framework.ubuntu.web.base.downloadFromURL import org.domaindrivenarchitecture.provs.framework.ubuntu.web.base.downloadFromURL
fun Prov.installFakturama() = def { fun Prov.installFakturama() = task {
createDir("/tmp", sudo = true) createDir("/tmp", sudo = true)
downloadFromURL( "https://files.fakturama.info/release/v2.1.1/Installer_Fakturama_linux_x64_2.1.1b.deb", "fakturama.deb", "/tmp") downloadFromURL( "https://files.fakturama.info/release/v2.1.1/Installer_Fakturama_linux_x64_2.1.1b.deb", "fakturama.deb", "/tmp")
cmd("sudo dpkg -i fakturama.deb", "/tmp") cmd("sudo dpkg -i fakturama.deb", "/tmp")

View file

@ -12,13 +12,13 @@ fun Prov.installGopass(
version: String = "1.12.7", version: String = "1.12.7",
enforceVersion: Boolean = false, enforceVersion: Boolean = false,
sha256sum: String = "0824d5110ff1e68bff1ba10c1be63acb67cb1ad8e3bccddd6b6fc989608beca8" // checksum for sha256sum version 8.30 (e.g. ubuntu 20.04) sha256sum: String = "0824d5110ff1e68bff1ba10c1be63acb67cb1ad8e3bccddd6b6fc989608beca8" // checksum for sha256sum version 8.30 (e.g. ubuntu 20.04)
) = def { ) = task {
if (isPackageInstalled("gopass") && !enforceVersion) { if (isPackageInstalled("gopass") && !enforceVersion) {
return@def ProvResult(true) return@task ProvResult(true)
} }
if (checkGopassVersion(version)) { if (checkGopassVersion(version)) {
return@def ProvResult(true, out = "Version $version of gopass is already installed.") return@task ProvResult(true, out = "Version $version of gopass is already installed.")
} }
val path = "tmp" val path = "tmp"
@ -64,13 +64,13 @@ fun Prov.configureGopass(gopassRootFolder: String? = null) = task {
} }
fun Prov.gopassMountStore(storeName: String, path: String) = def { fun Prov.gopassMountStore(storeName: String, path: String) = task {
cmd("gopass mounts add $storeName $path") cmd("gopass mounts add $storeName $path")
} }
@Suppress("unused") @Suppress("unused")
fun Prov.gopassInitStore(storeName: String, indexOfRecepientKey: Int = 0) = def { fun Prov.gopassInitStore(storeName: String, indexOfRecepientKey: Int = 0) = task {
cmd("printf \"$indexOfRecepientKey\\n\" | gopass init --store=$storeName") cmd("printf \"$indexOfRecepientKey\\n\" | gopass init --store=$storeName")
} }

View file

@ -10,7 +10,7 @@ import org.domaindrivenarchitecture.provs.framework.ubuntu.install.base.isPackag
import org.domaindrivenarchitecture.provs.framework.ubuntu.web.base.downloadFromURL import org.domaindrivenarchitecture.provs.framework.ubuntu.web.base.downloadFromURL
fun Prov.downloadGopassBridge() = def { fun Prov.downloadGopassBridge() = task {
val version = "0.8.0" val version = "0.8.0"
val filename = "gopass_bridge-${version}-fx.xpi" val filename = "gopass_bridge-${version}-fx.xpi"
val downloadDir = "${userHome()}Downloads/" val downloadDir = "${userHome()}Downloads/"
@ -23,7 +23,7 @@ fun Prov.downloadGopassBridge() = def {
// needs manual install with: firefox Downloads/gopass_bridge-0.8.0-fx.xpi // needs manual install with: firefox Downloads/gopass_bridge-0.8.0-fx.xpi
} }
fun Prov.installGopassBridgeJsonApi() = def { fun Prov.installGopassBridgeJsonApi() = task {
// see https://github.com/gopasspw/gopass-jsonapi // see https://github.com/gopasspw/gopass-jsonapi
val gopassBridgeVersion = "1.11.1" val gopassBridgeVersion = "1.11.1"
val requiredGopassVersion = "1.12" val requiredGopassVersion = "1.12"
@ -69,7 +69,7 @@ fun Prov.installGopassBridgeJsonApi() = def {
} }
} }
fun Prov.configureGopassBridgeJsonApi() = def { fun Prov.configureGopassBridgeJsonApi() = task {
if (isPackageInstalled("gopass-jsonapi")) { if (isPackageInstalled("gopass-jsonapi")) {
// configure for firefox and choose default for each: // configure for firefox and choose default for each:
// "Install for all users? [y/N/q]", // "Install for all users? [y/N/q]",

View file

@ -4,7 +4,7 @@ import org.domaindrivenarchitecture.provs.framework.core.Prov
import org.domaindrivenarchitecture.provs.framework.ubuntu.filesystem.base.addTextToFile import org.domaindrivenarchitecture.provs.framework.ubuntu.filesystem.base.addTextToFile
import java.io.File import java.io.File
fun Prov.configureNoSwappiness() = def { fun Prov.configureNoSwappiness() = task {
// set swappiness to 0 // set swappiness to 0
addTextToFile("vm.swappiness=0", File("/etc/sysctl.conf"), sudo = true) addTextToFile("vm.swappiness=0", File("/etc/sysctl.conf"), sudo = true)
} }

View file

@ -5,7 +5,7 @@ import org.domaindrivenarchitecture.provs.framework.core.ProvResult
import org.domaindrivenarchitecture.provs.framework.ubuntu.install.base.aptInstall import org.domaindrivenarchitecture.provs.framework.ubuntu.install.base.aptInstall
fun Prov.installPython() = def { fun Prov.installPython() = task {
installPython3() installPython3()
installVenv() installVenv()
installPybuilder() installPybuilder()
@ -13,26 +13,26 @@ fun Prov.installPython() = def {
installJupyterlab() installJupyterlab()
} }
fun Prov.installPython3(): ProvResult = def { fun Prov.installPython3(): ProvResult = task {
aptInstall("python3.8-venv python3-pip") aptInstall("python3.8-venv python3-pip")
} }
fun Prov.installVenv(): ProvResult = def { fun Prov.installVenv(): ProvResult = task {
val venvHome = "~/.python/meissa" val venvHome = "~/.python/meissa"
cmd("python3 -m venv " + venvHome) cmd("python3 -m venv " + venvHome)
cmd("source " + venvHome + "/bin/activate") cmd("source " + venvHome + "/bin/activate")
cmd("pip3 install pip --upgrade") cmd("pip3 install pip --upgrade")
} }
fun Prov.installPybuilder(): ProvResult = def { fun Prov.installPybuilder(): ProvResult = task {
cmd("pip3 install pybuilder ddadevops pypandoc mockito coverage unittest-xml-reporting deprecation python_terraform " + cmd("pip3 install pybuilder ddadevops pypandoc mockito coverage unittest-xml-reporting deprecation python_terraform " +
"boto3") "boto3")
} }
fun Prov.installRestClient(): ProvResult = def { fun Prov.installRestClient(): ProvResult = task {
cmd("pip3 install requests") cmd("pip3 install requests")
} }
fun Prov.installJupyterlab(): ProvResult = def { fun Prov.installJupyterlab(): ProvResult = task {
cmd("pip3 install jupyterlab pandas matplotlib") cmd("pip3 install jupyterlab pandas matplotlib")
} }

View file

@ -6,12 +6,12 @@ import org.domaindrivenarchitecture.provs.framework.ubuntu.filesystem.base.creat
import org.domaindrivenarchitecture.provs.framework.ubuntu.install.base.aptInstall import org.domaindrivenarchitecture.provs.framework.ubuntu.install.base.aptInstall
fun Prov.installRedshift() = def { fun Prov.installRedshift() = task {
aptInstall("redshift redshift-gtk") aptInstall("redshift redshift-gtk")
} }
fun Prov.configureRedshift() = def { fun Prov.configureRedshift() = task {
aptInstall("redshift redshift-gtk") aptInstall("redshift redshift-gtk")
createDir(".config") createDir(".config")

View file

@ -6,7 +6,7 @@ import org.domaindrivenarchitecture.provs.framework.ubuntu.install.base.aptInsta
import org.domaindrivenarchitecture.provs.framework.ubuntu.install.base.isPackageInstalled import org.domaindrivenarchitecture.provs.framework.ubuntu.install.base.isPackageInstalled
fun Prov.installVSC(vararg options: String) = requireAll { fun Prov.installVSC(vararg options: String) = task {
val clojureExtensions = val clojureExtensions =
arrayListOf("betterthantomorrow.calva", "martinklepsch.clojure-joker-linter", "DavidAnson.vscode-markdownlint") arrayListOf("betterthantomorrow.calva", "martinklepsch.clojure-joker-linter", "DavidAnson.vscode-markdownlint")
val pythonExtensions = arrayListOf("ms-python.python") val pythonExtensions = arrayListOf("ms-python.python")
@ -29,13 +29,13 @@ fun Prov.installVSC(vararg options: String) = requireAll {
} }
private fun Prov.prerequisitesVSCinstall() = def { private fun Prov.prerequisitesVSCinstall() = task {
aptInstall("curl gpg unzip apt-transport-https") aptInstall("curl gpg unzip apt-transport-https")
} }
@Suppress("unused") // only required for installation of vscode via apt @Suppress("unused") // only required for installation of vscode via apt
private fun Prov.installVscWithApt() = requireAll { private fun Prov.installVscWithApt() = task {
val packageName = "code" val packageName = "code"
if (!isPackageInstalled(packageName)) { if (!isPackageInstalled(packageName)) {
// see https://code.visualstudio.com/docs/setup/linux // see https://code.visualstudio.com/docs/setup/linux
@ -53,14 +53,14 @@ private fun Prov.installVscWithApt() = requireAll {
} }
private fun Prov.installVSCPackage() = def { private fun Prov.installVSCPackage() = task {
cmd("sudo snap install code --classic") cmd("sudo snap install code --classic")
// to install via apt use: // to install via apt use:
// installVscWithApt() // installVscWithApt()
} }
private fun Prov.installVSCodiumPackage() = def { private fun Prov.installVSCodiumPackage() = task {
cmd("sudo snap install codium --classic") cmd("sudo snap install codium --classic")
} }
@ -84,7 +84,7 @@ private fun Prov.installExtensionsCodium(extensions: List<String>) = optional {
} }
internal fun Prov.provisionAdditionalTools() = requireAll { internal fun Prov.provisionAdditionalTools() = task {
// Joker // Joker
val version = "0.18.0" val version = "0.18.0"
cmd("curl -Lo joker-${version}-linux-amd64.zip https://github.com/candid82/joker/releases/download/v${version}/joker-${version}-linux-amd64.zip") cmd("curl -Lo joker-${version}-linux-amd64.zip https://github.com/candid82/joker/releases/download/v${version}/joker-${version}-linux-amd64.zip")

View file

@ -5,14 +5,14 @@ import org.domaindrivenarchitecture.provs.framework.core.ProvResult
import org.domaindrivenarchitecture.provs.framework.ubuntu.install.base.aptInstall import org.domaindrivenarchitecture.provs.framework.ubuntu.install.base.aptInstall
import org.domaindrivenarchitecture.provs.framework.ubuntu.user.base.whoami import org.domaindrivenarchitecture.provs.framework.ubuntu.user.base.whoami
fun Prov.installVirtualBoxGuestAdditions() = def { fun Prov.installVirtualBoxGuestAdditions() = task {
// if running in a VirtualBox vm // if running in a VirtualBox vm
if (!chk("lspci | grep VirtualBox")) { if (!chk("lspci | grep VirtualBox")) {
return@def ProvResult(true, "Not running in a VirtualBox") return@task ProvResult(true, "Not running in a VirtualBox")
} }
if (chk("VBoxService --version")) { if (chk("VBoxService --version")) {
return@def ProvResult(true, "VBoxService already installed") return@task ProvResult(true, "VBoxService already installed")
} }
// install guest additions // install guest additions

View file

@ -7,7 +7,7 @@ import org.domaindrivenarchitecture.provs.framework.ubuntu.install.base.aptInsta
import org.domaindrivenarchitecture.provs.framework.ubuntu.install.base.isPackageInstalled import org.domaindrivenarchitecture.provs.framework.ubuntu.install.base.isPackageInstalled
fun Prov.installZimWiki() = def { fun Prov.installZimWiki() = task {
if (isPackageInstalled("zim")) { if (isPackageInstalled("zim")) {
ProvResult(true, out = "zim already installed.") ProvResult(true, out = "zim already installed.")
} else { } else {

View file

@ -78,6 +78,7 @@ open class Prov protected constructor(
* defines a task with default success behavior, i.e. returns success if all subtasks finished with success. * defines a task with default success behavior, i.e. returns success if all subtasks finished with success.
* Same as requireAll. * Same as requireAll.
*/ */
@Deprecated("Use function task instead", replaceWith = ReplaceWith("task()"))
fun def(a: Prov.() -> ProvResult): ProvResult { fun def(a: Prov.() -> ProvResult): ProvResult {
return handle(ResultMode.ALL) { a() } return handle(ResultMode.ALL) { a() }
} }
@ -99,6 +100,7 @@ open class Prov protected constructor(
/** /**
* defines a task, which returns success if all subtasks finished with success * defines a task, which returns success if all subtasks finished with success
*/ */
@Suppress("unused")
fun requireAll(a: Prov.() -> ProvResult): ProvResult { fun requireAll(a: Prov.() -> ProvResult): ProvResult {
return handle(ResultMode.ALL) { a() } return handle(ResultMode.ALL) { a() }
} }
@ -216,7 +218,7 @@ open class Prov protected constructor(
* Adds a ProvResult to the overall success evaluation. * Adds a ProvResult to the overall success evaluation.
* Intended for use in methods which do not automatically add results. * Intended for use in methods which do not automatically add results.
*/ */
fun addResultToEval(result: ProvResult) = requireAll { fun addResultToEval(result: ProvResult) = task {
result result
} }
@ -225,7 +227,7 @@ open class Prov protected constructor(
* Multi-line commands within the script are not supported. * Multi-line commands within the script are not supported.
* Empty lines and comments (all text behind # in a line) are supported, i.e. they are ignored. * Empty lines and comments (all text behind # in a line) are supported, i.e. they are ignored.
*/ */
fun sh(script: String, dir: String? = null, sudo: Boolean = false) = def { fun sh(script: String, dir: String? = null, sudo: Boolean = false) = task {
val lines = script.trimIndent().replace("\\\n", "").replace("\r\n", "\n").split("\n") val lines = script.trimIndent().replace("\\\n", "").replace("\r\n", "\n").split("\n")
val linesWithoutComments = lines.stream().map { it.split("#")[0] } val linesWithoutComments = lines.stream().map { it.split("#")[0] }
val linesNonEmpty = linesWithoutComments.filter { it.trim().isNotEmpty() } val linesNonEmpty = linesWithoutComments.filter { it.trim().isNotEmpty() }

View file

@ -55,13 +55,13 @@ fun UbuntuProv.runContainerPlatform(
containerName: String = "defaultProvContainer", containerName: String = "defaultProvContainer",
imageName: String = "ubuntu", imageName: String = "ubuntu",
sudo: Boolean = true sudo: Boolean = true
) = def { ) = task {
val dockerCmd = dockerCommand(sudo) val dockerCmd = dockerCommand(sudo)
cmd(dockerCmd + "run -dit --name=$containerName $imageName") cmd(dockerCmd + "run -dit --name=$containerName $imageName")
} }
fun UbuntuProv.containerExecPlatform(containerName: String, cmd: String, sudo: Boolean = true) = def { fun UbuntuProv.containerExecPlatform(containerName: String, cmd: String, sudo: Boolean = true) = task {
val dockerCmd = dockerCommand(sudo) val dockerCmd = dockerCommand(sudo)
cmd(dockerCmd + "exec $containerName $cmd") cmd(dockerCmd + "exec $containerName $cmd")
} }
@ -96,7 +96,7 @@ fun UbuntuProv.dockerImageExistsPlatform(imageName: String, sudo: Boolean): Bool
fun UbuntuProv.exitAndRmContainerPlatform( fun UbuntuProv.exitAndRmContainerPlatform(
containerName: String, containerName: String,
sudo: Boolean sudo: Boolean
) = requireAll { ) = task {
val dockerCmd = dockerCommand(sudo) val dockerCmd = dockerCommand(sudo)
if (containerRuns(containerName)) { if (containerRuns(containerName)) {

View file

@ -23,7 +23,7 @@ class UbuntuProv internal constructor(
} }
} }
override fun cmd(cmd: String, dir: String?, sudo: Boolean): ProvResult = def { override fun cmd(cmd: String, dir: String?, sudo: Boolean): ProvResult = task {
exec(SHELL, "-c", commandWithDirAndSudo(cmd, dir, sudo)) exec(SHELL, "-c", commandWithDirAndSudo(cmd, dir, sudo))
} }

View file

@ -4,7 +4,7 @@ import org.domaindrivenarchitecture.provs.framework.core.Prov
import org.domaindrivenarchitecture.provs.framework.core.local import org.domaindrivenarchitecture.provs.framework.core.local
fun Prov.helloWorld() = def { fun Prov.helloWorld() = task {
cmd("echo Hello world!") cmd("echo Hello world!")
} }

View file

@ -19,14 +19,14 @@ fun main(vararg args: String) {
if (args.size !in 2..3) { if (args.size !in 2..3) {
println("Wrong number of arguments. Please specify either host and user if connection is done by ssh key or otherwise host, user and password. E.g. 172.0.0.123 username password") println("Wrong number of arguments. Please specify either host and user if connection is done by ssh key or otherwise host, user and password. E.g. 172.0.0.123 username password")
} else { } else {
val password = if (args.size == 2) null else Secret(args[3]) val password = if (args.size == 2) null else Secret(args[2])
remote(args[0], args[1], password = password).printInfos() remote(args[0], args[1], password = password).printInfos()
} }
} }
} }
fun Prov.printInfos() = def { fun Prov.printInfos() = task {
println("\nUbuntu Version:\n${ubuntuVersion()}") println("\nUbuntu Version:\n${ubuntuVersion()}")
println("\nCurrent directory:\n${currentDir()}") println("\nCurrent directory:\n${currentDir()}")
println("\nTime zone:\n${timeZone()}") println("\nTime zone:\n${timeZone()}")

View file

@ -10,7 +10,7 @@ import org.domaindrivenarchitecture.provs.framework.ubuntu.install.base.aptInsta
* Provisions a certbot for the specified serverName and email to obtain and renew letsencrypt certificates * Provisions a certbot for the specified serverName and email to obtain and renew letsencrypt certificates
* Parameter can be used to specify certbot options e.g. "--nginx" to configure nginx, see https://certbot.eff.org/docs/using.html#certbot-command-line-options * Parameter can be used to specify certbot options e.g. "--nginx" to configure nginx, see https://certbot.eff.org/docs/using.html#certbot-command-line-options
*/ */
fun Prov.provisionCertbot(serverName: String, email: String?, additionalOptions: String? = "") = requireAll { fun Prov.provisionCertbot(serverName: String, email: String?, additionalOptions: String? = "") = task {
aptInstall("snapd") aptInstall("snapd")
sh(""" sh("""
sudo snap install core; sudo snap refresh core sudo snap install core; sudo snap refresh core

View file

@ -5,7 +5,7 @@ import org.domaindrivenarchitecture.provs.framework.core.ProvResult
import org.domaindrivenarchitecture.provs.framework.ubuntu.install.base.aptInstall import org.domaindrivenarchitecture.provs.framework.ubuntu.install.base.aptInstall
fun Prov.saveIpTables() = requireAll { fun Prov.saveIpTables() = task {
sh(""" sh("""
iptables-save > /etc/iptables/rules.v4 iptables-save > /etc/iptables/rules.v4
ip6tables-save > /etc/iptables/rules.v6 ip6tables-save > /etc/iptables/rules.v6
@ -15,7 +15,8 @@ fun Prov.saveIpTables() = requireAll {
} }
fun Prov.makeIpTablesPersistent() = requireAll { @Suppress("unused")
fun Prov.makeIpTablesPersistent() = task {
// inspired by https://gist.github.com/alonisser/a2c19f5362c2091ac1e7 // inspired by https://gist.github.com/alonisser/a2c19f5362c2091ac1e7
// enables iptables-persistent to be installed without manual input // enables iptables-persistent to be installed without manual input
sh(""" sh("""
@ -28,7 +29,8 @@ fun Prov.makeIpTablesPersistent() = requireAll {
} }
fun Prov.resetFirewall() = requireAll { @Suppress("unused")
fun Prov.resetFirewall() = task {
sh(""" sh("""
#!/bin/bash #!/bin/bash
sudo iptables -F sudo iptables -F
@ -50,7 +52,7 @@ fun Prov.resetFirewall() = requireAll {
} }
fun Prov.provisionFirewall(addNetworkProtections: Boolean = false) = requireAll { fun Prov.provisionFirewall(addNetworkProtections: Boolean = false) = task {
if (addNetworkProtections) { if (addNetworkProtections) {
networkProtections() networkProtections()
} }
@ -111,7 +113,7 @@ fun Prov.provisionFirewall(addNetworkProtections: Boolean = false) = requireAll
} }
fun Prov.networkProtections() = def { fun Prov.networkProtections() = task {
sh(""" sh("""
# Drop ICMP echo-request messages sent to broadcast or multicast addresses # Drop ICMP echo-request messages sent to broadcast or multicast addresses
echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts
@ -137,7 +139,7 @@ fun Prov.networkProtections() = def {
} }
fun Prov.ipTablesRecreateDockerRules() = requireAll { fun Prov.ipTablesRecreateDockerRules() = task {
// see https://stackoverflow.com/questions/25917941/docker-how-to-re-create-dockers-additional-iptables-rules // see https://stackoverflow.com/questions/25917941/docker-how-to-re-create-dockers-additional-iptables-rules
cmd("sudo service docker restart") cmd("sudo service docker restart")
} }

View file

@ -6,7 +6,7 @@ import java.time.LocalDateTime
import java.time.format.DateTimeFormatter import java.time.format.DateTimeFormatter
fun Prov.saveIpTablesToFile() = def { fun Prov.saveIpTablesToFile() = task {
val dateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("-yyyy-MM-dd--HH:mm:ss")) val dateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("-yyyy-MM-dd--HH:mm:ss"))
val file = "savedrules$dateTime.txt" val file = "savedrules$dateTime.txt"
sh(""" sh("""
@ -14,7 +14,7 @@ fun Prov.saveIpTablesToFile() = def {
cat $file""") cat $file""")
} }
fun Prov.restoreIpTablesFromFile(file: String? = null) = def { fun Prov.restoreIpTablesFromFile(file: String? = null) = task {
val fileName = file ?: cmd("ls -r a* | head -1\n").out val fileName = file ?: cmd("ls -r a* | head -1\n").out
fileName?.let { cmd("sudo iptables-restore < $file") } fileName?.let { cmd("sudo iptables-restore < $file") }
?: ProvResult(false, err = "File to restore not found.") ?: ProvResult(false, err = "File to restore not found.")

View file

@ -18,7 +18,7 @@ import org.domaindrivenarchitecture.provs.framework.extensions.server_software.s
* If you would want nexus to be accessible directly from the internet (e.g. for test or demo reasons) * If you would want nexus to be accessible directly from the internet (e.g. for test or demo reasons)
* set parameter portAccessibleFromNetwork to true. * set parameter portAccessibleFromNetwork to true.
*/ */
fun Prov.provisionNexusWithDocker(portAccessibleFromNetwork: Boolean = false) = requireAll { fun Prov.provisionNexusWithDocker(portAccessibleFromNetwork: Boolean = false) = task {
// https://blog.sonatype.com/sonatype-nexus-installation-using-docker // https://blog.sonatype.com/sonatype-nexus-installation-using-docker
// https://medium.com/@AhGh/how-to-setup-sonatype-nexus-3-repository-manager-using-docker-7ff89bc311ce // https://medium.com/@AhGh/how-to-setup-sonatype-nexus-3-repository-manager-using-docker-7ff89bc311ce
aptInstall("docker.io") aptInstall("docker.io")
@ -66,10 +66,10 @@ private fun Prov.getDefaultNetworkingInterface(): String? {
@Suppress("unused") // to be used externally @Suppress("unused") // to be used externally
fun provisionNexusServer(serverName: String, certbotEmail: String) { fun provisionNexusServer(serverName: String, certbotEmail: String) {
val userName = "nexus" + 7 val userName = "nexus" + 7
remote(serverName, "root").def { remote(serverName, "root").task {
createUser(userName, copyAuthorizedSshKeysFromCurrentUser = true, sudo = true) createUser(userName, copyAuthorizedSshKeysFromCurrentUser = true, sudo = true)
} }
remote(serverName, userName).requireAll { remote(serverName, userName).task {
provisionNexusWithDocker() provisionNexusWithDocker()
if (provisionNginxStandAlone(NginxConf.nginxReverseProxyHttpConfig(serverName)).success) { if (provisionNginxStandAlone(NginxConf.nginxReverseProxyHttpConfig(serverName)).success) {

View file

@ -12,7 +12,7 @@ import org.domaindrivenarchitecture.provs.framework.ubuntu.install.base.aptInsta
internal const val NGINX_CONFIG_FILE = "/etc/nginx/nginx.conf" internal const val NGINX_CONFIG_FILE = "/etc/nginx/nginx.conf"
fun Prov.provisionNginxStandAlone(config: NginxConf? = null) = requireAll { fun Prov.provisionNginxStandAlone(config: NginxConf? = null) = task {
aptInstall("nginx") aptInstall("nginx")

View file

@ -1,12 +0,0 @@
package org.domaindrivenarchitecture.provs.framework.extensions.server_software.standalone_server.nginx.base
import org.domaindrivenarchitecture.provs.framework.core.Prov
import org.domaindrivenarchitecture.provs.framework.core.Secret
import org.domaindrivenarchitecture.provs.framework.ubuntu.install.base.aptInstall
fun Prov.nginxAddBasicAuth(user: String, password: Secret) = requireAll {
aptInstall("apache2-utils")
val passwordFile = "/etc/nginx/.htpasswd"
cmdNoLog("sudo htpasswd -b -c $passwordFile $user ${password.plain()}")
}

View file

@ -1,8 +1,8 @@
package org.domaindrivenarchitecture.provs.framework.extensions.server_software.standalone_server.nginx.base package org.domaindrivenarchitecture.provs.framework.extensions.server_software.standalone_server.nginx.base
import org.domaindrivenarchitecture.provs.framework.core.Prov import org.domaindrivenarchitecture.provs.framework.core.Prov
import org.domaindrivenarchitecture.provs.framework.core.ProvResult import org.domaindrivenarchitecture.provs.framework.ubuntu.filesystem.base.createDirs
import org.domaindrivenarchitecture.provs.framework.ubuntu.filesystem.base.* import org.domaindrivenarchitecture.provs.framework.ubuntu.filesystem.base.replaceTextInFile
internal const val locationsAvailableDir = "/etc/nginx/locations-available/" internal const val locationsAvailableDir = "/etc/nginx/locations-available/"
@ -10,35 +10,16 @@ internal const val locationsEnabledDir = "/etc/nginx/locations-enabled/"
internal const val locationsFileExtension = ".locations" internal const val locationsFileExtension = ".locations"
fun Prov.createNginxLocationFolders() = requireAll { fun Prov.createNginxLocationFolders() = task {
createDirs(locationsEnabledDir, sudo = true) createDirs(locationsEnabledDir, sudo = true)
createDirs(locationsAvailableDir, sudo = true) createDirs(locationsAvailableDir, sudo = true)
} }
fun Prov.nginxIncludeLocationFolders() = requireAll { fun Prov.nginxIncludeLocationFolders() = task {
replaceTextInFile("/etc/nginx/nginx.conf", "listen 80;\n", replaceTextInFile("/etc/nginx/nginx.conf", "listen 80;\n",
"""listen 80; """listen 80;
include ${locationsAvailableDir}port80*$locationsFileExtension; include ${locationsAvailableDir}port80*$locationsFileExtension;
include ${locationsEnabledDir}port443*$locationsFileExtension; include ${locationsEnabledDir}port443*$locationsFileExtension;
""") """)
} }
fun Prov.nginxAddLocation(port: String, locationFileName: String, urlPath: String, content: String) = requireAll {
val locationConf = """location $urlPath {""" +
content +
"\n}"
if (!dirExists(locationsAvailableDir, sudo = true)) {
createNginxLocationFolders()
}
createFile("${locationsAvailableDir}port${port}_$locationFileName$locationsFileExtension", locationConf, sudo = true)
if (!fileExists("${locationsEnabledDir}port${port}_$locationFileName$locationsFileExtension", sudo = true)) {
cmd("sudo ln -s ${locationsAvailableDir}port${port}_$locationFileName$locationsFileExtension ${locationsEnabledDir}port${port}_$locationFileName$locationsFileExtension ")
} else {
ProvResult(true)
}
}

View file

@ -2,7 +2,6 @@ package org.domaindrivenarchitecture.provs.framework.extensions.server_software.
import org.domaindrivenarchitecture.provs.framework.core.Prov import org.domaindrivenarchitecture.provs.framework.core.Prov
import org.domaindrivenarchitecture.provs.framework.ubuntu.filesystem.base.createDirs import org.domaindrivenarchitecture.provs.framework.ubuntu.filesystem.base.createDirs
import org.domaindrivenarchitecture.provs.framework.extensions.server_software.standalone_server.nginx.provisionNginxStandAlone
internal val certificateName = "selfsigned" internal val certificateName = "selfsigned"
@ -19,18 +18,10 @@ fun Prov.nginxCreateSelfSignedCertificate(
organizationalUnit: String = "test", organizationalUnit: String = "test",
commonName: String = "test", commonName: String = "test",
email : String = "test@test.net" email : String = "test@test.net"
) = def { ) = task {
// inspired by https://gist.github.com/adrianorsouza/2bbfe5e197ce1c0b97c8 // inspired by https://gist.github.com/adrianorsouza/2bbfe5e197ce1c0b97c8
createDirs(dirSslCert, sudo = true) createDirs(dirSslCert, sudo = true)
createDirs(dirSslKey, sudo = true) createDirs(dirSslKey, sudo = true)
cmd("cd $dirSslKey && sudo openssl req -x509 -nodes -newkey rsa:2048 -keyout $certificateName.key -out $certificateName.crt -days $sslDays -subj \"/C=$country/ST=$state/L=$locality/O=$organization/OU=$organizationalUnit/CN=$commonName/emailAddress=$email\"") cmd("cd $dirSslKey && sudo openssl req -x509 -nodes -newkey rsa:2048 -keyout $certificateName.key -out $certificateName.crt -days $sslDays -subj \"/C=$country/ST=$state/L=$locality/O=$organization/OU=$organizationalUnit/CN=$commonName/emailAddress=$email\"")
cmd("sudo mv $dirSslKey/$certificateName.crt $dirSslCert/") cmd("sudo mv $dirSslKey/$certificateName.crt $dirSslCert/")
} }
fun Prov.configureNginxWithSelfSignedCertificate() = def {
// todo: should not call provisionNginxStandAlone, which is defined in the package above
provisionNginxStandAlone(NginxConf.nginxReverseProxySslConfig("localhost",
dirSslCert+"/"+ certificateName + ".crt",
dirSslKey + "/" + certificateName + ".key"))
}

View file

@ -8,7 +8,8 @@ import org.domaindrivenarchitecture.provs.framework.extensions.server_software.s
* If running behind an nginx, pls specify the hostname in parameter nginxHost (e.g. mydomain.com). * If running behind an nginx, pls specify the hostname in parameter nginxHost (e.g. mydomain.com).
* To run it without nodeExporter (which provides system data to prometheus), set withNodeExporter to false. * To run it without nodeExporter (which provides system data to prometheus), set withNodeExporter to false.
*/ */
fun Prov.provisionPrometheusDocker(nginxHost: String? = null, withNodeExporter: Boolean = true) = def { @Suppress("unused")
fun Prov.provisionPrometheusDocker(nginxHost: String? = null, withNodeExporter: Boolean = true) = task {
configurePrometheusDocker() configurePrometheusDocker()
if (withNodeExporter) { if (withNodeExporter) {
installNodeExporter() installNodeExporter()

View file

@ -12,7 +12,7 @@ import org.domaindrivenarchitecture.provs.framework.ubuntu.user.base.whoami
internal val defaultInstallationDir = "/usr/local/bin/" internal val defaultInstallationDir = "/usr/local/bin/"
fun Prov.installNodeExporter() = requireAll { fun Prov.installNodeExporter() = task {
// inspired by https://devopscube.com/monitor-linux-servers-prometheus-node-exporter/ and // inspired by https://devopscube.com/monitor-linux-servers-prometheus-node-exporter/ and
// https://www.howtoforge.com/tutorial/how-to-install-prometheus-and-node-exporter-on-centos-8/#step-install-and-configure-nodeexporter // https://www.howtoforge.com/tutorial/how-to-install-prometheus-and-node-exporter-on-centos-8/#step-install-and-configure-nodeexporter
val downloadFileBasename = "node_exporter-1.0.1.linux-amd64" val downloadFileBasename = "node_exporter-1.0.1.linux-amd64"
@ -33,7 +33,7 @@ fun Prov.installNodeExporter() = requireAll {
} }
fun Prov.runNodeExporter() = def { fun Prov.runNodeExporter() = task {
createFile("/etc/systemd/system/node_exporter.service", nodeExporterServiceConf(whoami()?:"nouserfound"), sudo = true) createFile("/etc/systemd/system/node_exporter.service", nodeExporterServiceConf(whoami()?:"nouserfound"), sudo = true)
sh(""" sh("""
@ -52,7 +52,7 @@ fun Prov.runNodeExporter() = def {
fun Prov.addNodeExporterToPrometheusConf ( fun Prov.addNodeExporterToPrometheusConf (
prometheusConf: String = "/etc/prometheus/prometheus.yml", prometheusConf: String = "/etc/prometheus/prometheus.yml",
sudo: Boolean = true sudo: Boolean = true
) = requireAll { ) = task {
val prometheusConfNodeExporter = """ val prometheusConfNodeExporter = """
scrape_configs: scrape_configs:
- job_name: 'node_exporter' - job_name: 'node_exporter'

View file

@ -11,13 +11,13 @@ internal val configDir = "/etc/prometheus/"
internal val configFile = "prometheus.yml" internal val configFile = "prometheus.yml"
fun Prov.configurePrometheusDocker(config: String = prometheusDefaultConfig) = requireAll { fun Prov.configurePrometheusDocker(config: String = prometheusDefaultConfig) = task {
createDirs(configDir, sudo = true) createDirs(configDir, sudo = true)
createFile(configDir + configFile, config, sudo = true) createFile(configDir + configFile, config, sudo = true)
} }
fun Prov.runPrometheusDocker(nginxHost: String? = null) = requireAll { fun Prov.runPrometheusDocker(nginxHost: String? = null) = task {
aptInstall("docker.io") aptInstall("docker.io")
val containerName = "prometheus" val containerName = "prometheus"

View file

@ -23,7 +23,7 @@ fun Prov.createFileFromResource(
resourcePath: String = "", resourcePath: String = "",
posixFilePermission: String? = null, posixFilePermission: String? = null,
sudo: Boolean = false sudo: Boolean = false
): ProvResult = def { ): ProvResult = task {
createFile( createFile(
fullyQualifiedFilename, fullyQualifiedFilename,
getResourceAsText(resourcePath.endingWithFileSeparator() + resourceFilename), getResourceAsText(resourcePath.endingWithFileSeparator() + resourceFilename),
@ -43,7 +43,7 @@ fun Prov.createFileFromResourceTemplate(
values: Map<String, String>, values: Map<String, String>,
posixFilePermission: String? = null, posixFilePermission: String? = null,
sudo: Boolean = false sudo: Boolean = false
): ProvResult = def { ): ProvResult = task {
createFile( createFile(
fullyQualifiedFilename, fullyQualifiedFilename,
getResourceAsText(resourcePath.endingWithFileSeparator() + resourceFilename).resolve(values), getResourceAsText(resourcePath.endingWithFileSeparator() + resourceFilename).resolve(values),
@ -62,7 +62,7 @@ fun Prov.copyFileFromLocal(
fullyQualifiedLocalFilename: String, fullyQualifiedLocalFilename: String,
posixFilePermission: String? = null, posixFilePermission: String? = null,
sudo: Boolean = false sudo: Boolean = false
): ProvResult = def { ): ProvResult = task {
createFile( createFile(
fullyQualifiedFilename, fullyQualifiedFilename,
getLocalFileContent(fullyQualifiedLocalFilename), getLocalFileContent(fullyQualifiedLocalFilename),
@ -117,7 +117,7 @@ fun Prov.createSecretFile(
fullyQualifiedFilename: String, fullyQualifiedFilename: String,
secret: Secret, secret: Secret,
posixFilePermission: String? = null posixFilePermission: String? = null
): ProvResult = def { ): ProvResult = task {
posixFilePermission?.let { posixFilePermission?.let {
ensureValidPosixFilePermission(posixFilePermission) ensureValidPosixFilePermission(posixFilePermission)
cmd("install -m $posixFilePermission /dev/null $fullyQualifiedFilename") cmd("install -m $posixFilePermission /dev/null $fullyQualifiedFilename")
@ -126,7 +126,7 @@ fun Prov.createSecretFile(
} }
fun Prov.deleteFile(file: String, path: String? = null, sudo: Boolean = false): ProvResult = def { fun Prov.deleteFile(file: String, path: String? = null, sudo: Boolean = false): ProvResult = task {
val fullyQualifiedFilename = (path?.normalizePath() ?: "") + file val fullyQualifiedFilename = (path?.normalizePath() ?: "") + file
if (fileExists(fullyQualifiedFilename, sudo = sudo)) { if (fileExists(fullyQualifiedFilename, sudo = sudo)) {
cmd(prefixWithSudo("rm $fullyQualifiedFilename", sudo)) cmd(prefixWithSudo("rm $fullyQualifiedFilename", sudo))
@ -140,9 +140,9 @@ fun Prov.fileContainsText(file: String, content: String, sudo: Boolean = false):
// todo consider grep e.g. for content without newlines // todo consider grep e.g. for content without newlines
// return cmdNoEval(prefixWithSudo("grep -- '${content.escapeSingleQuote()}' $file", sudo)).success // return cmdNoEval(prefixWithSudo("grep -- '${content.escapeSingleQuote()}' $file", sudo)).success
val fileContent = fileContent(file, sudo = sudo) val fileContent = fileContent(file, sudo = sudo)
return if (fileContent == null) return if (fileContent == null) {
false false
else } else
fileContent.contains(content) fileContent.contains(content)
} }
@ -166,10 +166,10 @@ fun Prov.addTextToFile(
doNotAddIfExisting: Boolean = true, doNotAddIfExisting: Boolean = true,
sudo: Boolean = false sudo: Boolean = false
): ProvResult = ): ProvResult =
def { task {
val fileContainsText = fileContainsText(file.path, text, sudo = sudo) val fileContainsText = fileContainsText(file.path, text, sudo = sudo)
if (fileContainsText && doNotAddIfExisting) { if (fileContainsText && doNotAddIfExisting) {
return@def ProvResult(true, out = "Text already in file") return@task ProvResult(true, out = "Text already in file")
} }
cmd( cmd(
"printf '%s' " + text "printf '%s' " + text
@ -178,12 +178,12 @@ fun Prov.addTextToFile(
} }
fun Prov.replaceTextInFile(file: String, oldText: String, replacement: String) = def { fun Prov.replaceTextInFile(file: String, oldText: String, replacement: String) = task {
replaceTextInFile(file, Regex.fromLiteral(oldText), Regex.escapeReplacement(replacement)) replaceTextInFile(file, Regex.fromLiteral(oldText), Regex.escapeReplacement(replacement))
} }
fun Prov.replaceTextInFile(file: String, oldText: Regex, replacement: String) = def { fun Prov.replaceTextInFile(file: String, oldText: Regex, replacement: String) = task {
// todo: only use sudo for root or if owner different from current // todo: only use sudo for root or if owner different from current
val content = fileContent(file, true) val content = fileContent(file, true)
if (content != null) { if (content != null) {
@ -195,7 +195,7 @@ fun Prov.replaceTextInFile(file: String, oldText: Regex, replacement: String) =
} }
fun Prov.insertTextInFile(file: String, textBehindWhichToInsert: Regex, textToInsert: String) = def { fun Prov.insertTextInFile(file: String, textBehindWhichToInsert: Regex, textToInsert: String) = task {
// todo: only use sudo for root or if owner different from current // todo: only use sudo for root or if owner different from current
val content = fileContent(file, true) val content = fileContent(file, true)
if (content != null) { if (content != null) {
@ -231,7 +231,7 @@ fun Prov.createDir(
path: String = "~/", path: String = "~/",
failIfExisting: Boolean = false, failIfExisting: Boolean = false,
sudo: Boolean = false sudo: Boolean = false
): ProvResult = def { ): ProvResult = task {
if (!failIfExisting && dirExists(dir, path, sudo)) { if (!failIfExisting && dirExists(dir, path, sudo)) {
ProvResult(true) ProvResult(true)
} else { } else {
@ -246,7 +246,7 @@ fun Prov.createDirs(
path: String = "~/", path: String = "~/",
failIfExisting: Boolean = false, failIfExisting: Boolean = false,
sudo: Boolean = false sudo: Boolean = false
): ProvResult = def { ): ProvResult = task {
if (!failIfExisting && dirExists(dirs, path, sudo)) { if (!failIfExisting && dirExists(dirs, path, sudo)) {
ProvResult(true) ProvResult(true)
} else { } else {

View file

@ -10,7 +10,7 @@ fun Prov.provisionGit(
email: String? = null, email: String? = null,
signingKey: String? = null, signingKey: String? = null,
diffTool: String? = null diffTool: String? = null
): ProvResult = def { ): ProvResult = task {
aptInstall("git") aptInstall("git")

View file

@ -10,11 +10,11 @@ import java.io.File
val knownHostsFile = "~/.ssh/known_hosts" val knownHostsFile = "~/.ssh/known_hosts"
fun Prov.gitClone(repo: String, path: String, pullIfExisting: Boolean = true): ProvResult = def { fun Prov.gitClone(repo: String, path: String, pullIfExisting: Boolean = true): ProvResult = task {
val dir = cmdNoEval("basename $repo .git").out?.trim() val dir = cmdNoEval("basename $repo .git").out?.trim()
if (dir == null) { if (dir == null) {
return@def ProvResult(false, err = "$repo is not a valid git repository") return@task ProvResult(false, err = "$repo is not a valid git repository")
} }
val pathToDir = if (path.endsWith("/")) path + dir else path + "/" + dir val pathToDir = if (path.endsWith("/")) path + dir else path + "/" + dir
@ -30,7 +30,7 @@ fun Prov.gitClone(repo: String, path: String, pullIfExisting: Boolean = true): P
} }
fun Prov.trustGithub() = def { fun Prov.trustGithub() = task {
// current fingerprints from https://docs.github.com/en/github/authenticating-to-github/githubs-ssh-key-fingerprints // current fingerprints from https://docs.github.com/en/github/authenticating-to-github/githubs-ssh-key-fingerprints
val fingerprints = setOf( val fingerprints = setOf(
"SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8 github.com", // (RSA) "SHA256:nThbg6kXUpJWGl7E1IGOCspRomTxdCARLviKw6E5SY8 github.com", // (RSA)
@ -42,7 +42,7 @@ fun Prov.trustGithub() = def {
} }
fun Prov.trustGitlab() = def { fun Prov.trustGitlab() = task {
// entries for known_hosts from https://docs.gitlab.com/ee/user/gitlab_com/ // entries for known_hosts from https://docs.gitlab.com/ee/user/gitlab_com/
val gitlabFingerprints = """ val gitlabFingerprints = """
gitlab.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAfuCHKVTjquxvt6CM6tdG4SLp1Btn/nOeHHE5UOzRdf gitlab.com ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAfuCHKVTjquxvt6CM6tdG4SLp1Btn/nOeHHE5UOzRdf
@ -59,9 +59,9 @@ fun Prov.trustGitlab() = def {
* Note: adding keys automatically is vulnerable to a man-in-the-middle attack and not considered secure. * Note: adding keys automatically is vulnerable to a man-in-the-middle attack and not considered secure.
*/ */
// todo: consider making function public and moving to ssh package // todo: consider making function public and moving to ssh package
private fun Prov.trustHost(host: String, fingerprintsOfKeysToBeAdded: Set<String>?) = def { private fun Prov.trustHost(host: String, fingerprintsOfKeysToBeAdded: Set<String>?) = task {
if (isHostKnown(host)) { if (isHostKnown(host)) {
return@def ProvResult(true, out = "Host already known") return@task ProvResult(true, out = "Host already known")
} }
if (!fileExists(knownHostsFile)) { if (!fileExists(knownHostsFile)) {
createDir(".ssh") createDir(".ssh")
@ -74,7 +74,7 @@ private fun Prov.trustHost(host: String, fingerprintsOfKeysToBeAdded: Set<String
// logic based on https://serverfault.com/questions/447028/non-interactive-git-clone-ssh-fingerprint-prompt // logic based on https://serverfault.com/questions/447028/non-interactive-git-clone-ssh-fingerprint-prompt
val actualKeys = findSshKeys(host) val actualKeys = findSshKeys(host)
if (actualKeys == null || actualKeys.size == 0) { if (actualKeys == null || actualKeys.size == 0) {
return@def ProvResult(false, out = "No valid keys found for host: $host") return@task ProvResult(false, out = "No valid keys found for host: $host")
} }
val actualFingerprints = getFingerprintsForKeys(actualKeys) val actualFingerprints = getFingerprintsForKeys(actualKeys)
for (fingerprintToBeAdded in fingerprintsOfKeysToBeAdded) { for (fingerprintToBeAdded in fingerprintsOfKeysToBeAdded) {
@ -88,7 +88,7 @@ private fun Prov.trustHost(host: String, fingerprintsOfKeysToBeAdded: Set<String
} }
} }
if (indexOfKeyFound == -1) { if (indexOfKeyFound == -1) {
return@def ProvResult( return@task ProvResult(
false, false,
err = "Fingerprint ($fingerprintToBeAdded) could not be found in actual fingerprints: $actualFingerprints" err = "Fingerprint ($fingerprintToBeAdded) could not be found in actual fingerprints: $actualFingerprints"
) )

View file

@ -11,7 +11,7 @@ private var aptInit = false
* *
* @param packages the packages to be installed, packages must be separated by space if there are more than one * @param packages the packages to be installed, packages must be separated by space if there are more than one
*/ */
fun Prov.aptInstall(packages: String): ProvResult = def { fun Prov.aptInstall(packages: String): ProvResult = task {
if (!aptInit) { if (!aptInit) {
cmd("sudo apt-get update") cmd("sudo apt-get update")
cmd("sudo apt-get install -qy apt-utils") cmd("sudo apt-get install -qy apt-utils")
@ -32,11 +32,10 @@ fun Prov.aptInstall(packages: String): ProvResult = def {
* *
* @param packages the packages to be installed, packages must be separated by space if there are more than one * @param packages the packages to be installed, packages must be separated by space if there are more than one
*/ */
// todo: add test fun Prov.snapInstall(packages: String, classic: Boolean = false): ProvResult = task {
fun Prov.snapInstall(packages: String, classic: Boolean = false): ProvResult = def {
val packageList = packages.split(" ") val packageList = packages.split(" ")
for (packg in packageList) { for (pkg in packageList) {
cmd("sudo snap install $packg" + if (classic) " --classic" else "") cmd("sudo snap install $pkg" + if (classic) " --classic" else "")
} }
ProvResult(true) // dummy ProvResult(true) // dummy
} }
@ -47,7 +46,7 @@ fun Prov.snapInstall(packages: String, classic: Boolean = false): ProvResult = d
* *
* @param packageName the package to install * @param packageName the package to install
*/ */
fun Prov.aptInstallFromPpa(launchPadUser: String, ppaName: String, packageName: String): ProvResult = def { fun Prov.aptInstallFromPpa(launchPadUser: String, ppaName: String, packageName: String): ProvResult = task {
aptInstall("software-properties-common") // for being able to use add-apt-repository aptInstall("software-properties-common") // for being able to use add-apt-repository
cmd("sudo add-apt-repository -y ppa:$launchPadUser/$ppaName") cmd("sudo add-apt-repository -y ppa:$launchPadUser/$ppaName")
aptInstall(packageName) aptInstall(packageName)

View file

@ -25,7 +25,7 @@ class KeyPairSource(val sourceType: SecretSourceType, val publicKey: String, val
/** /**
* provisions gpg and/or ssh keys for the current user * provisions gpg and/or ssh keys for the current user
*/ */
fun Prov.provisionKeys(gpgKeys: KeyPair? = null, sshKeys: KeyPair? = null) = requireAll { fun Prov.provisionKeys(gpgKeys: KeyPair? = null, sshKeys: KeyPair? = null) = task {
gpgKeys?.let { configureGpgKeys(it, true) } gpgKeys?.let { configureGpgKeys(it, true) }
sshKeys?.let { configureSshKeys(it) } sshKeys?.let { configureSshKeys(it) }
ProvResult(true) // dummy ProvResult(true) // dummy

View file

@ -17,7 +17,7 @@ import org.domaindrivenarchitecture.provs.framework.core.echoCommandForText
* @param gpgKeys * @param gpgKeys
* @param trust whether to trust keys with trust-level 5 (ultimate) * @param trust whether to trust keys with trust-level 5 (ultimate)
*/ */
fun Prov.configureGpgKeys(gpgKeys: KeyPair, trust: Boolean = false, skipIfExistin: Boolean = true) = requireAll { fun Prov.configureGpgKeys(gpgKeys: KeyPair, trust: Boolean = false, skipIfExistin: Boolean = true) = task {
aptInstall("gnupg") aptInstall("gnupg")
val fingerprint = gpgFingerprint(gpgKeys.publicKey.plain()) val fingerprint = gpgFingerprint(gpgKeys.publicKey.plain())
if (fingerprint == null) { if (fingerprint == null) {
@ -50,7 +50,7 @@ fun Prov.configureGpgKeys(gpgKeys: KeyPair, trust: Boolean = false, skipIfExisti
} }
private fun Prov.configureGPGAgent() = def { private fun Prov.configureGPGAgent() = task {
if (dirExists(".gnupg")) { if (dirExists(".gnupg")) {
createDir(".gnupg", "~/") createDir(".gnupg", "~/")
} }

View file

@ -1,7 +1,6 @@
package org.domaindrivenarchitecture.provs.framework.ubuntu.keys.base package org.domaindrivenarchitecture.provs.framework.ubuntu.keys.base
import org.domaindrivenarchitecture.provs.framework.core.Prov import org.domaindrivenarchitecture.provs.framework.core.Prov
import org.domaindrivenarchitecture.provs.framework.core.ProvResult
import org.domaindrivenarchitecture.provs.framework.ubuntu.filesystem.base.createDir import org.domaindrivenarchitecture.provs.framework.ubuntu.filesystem.base.createDir
import org.domaindrivenarchitecture.provs.framework.ubuntu.filesystem.base.createSecretFile import org.domaindrivenarchitecture.provs.framework.ubuntu.filesystem.base.createSecretFile
import org.domaindrivenarchitecture.provs.framework.ubuntu.keys.KeyPair import org.domaindrivenarchitecture.provs.framework.ubuntu.keys.KeyPair
@ -10,16 +9,10 @@ import org.domaindrivenarchitecture.provs.framework.ubuntu.keys.KeyPair
/** /**
* installs ssh keys for active user * installs ssh keys for active user
*/ */
fun Prov.configureSshKeys(sshKeys: KeyPair) = def { fun Prov.configureSshKeys(sshKeys: KeyPair) = task {
createDir(".ssh", "~/") createDir(".ssh", "~/")
createSecretFile("~/.ssh/id_rsa.pub", sshKeys.publicKey, "644") createSecretFile("~/.ssh/id_rsa.pub", sshKeys.publicKey, "644")
createSecretFile("~/.ssh/id_rsa", sshKeys.privateKey, "600") createSecretFile("~/.ssh/id_rsa", sshKeys.privateKey, "600")
configureSSHClient()
}
fun Prov.configureSSHClient() = def {
// TODO("Not yet implemented")
ProvResult(true)
} }
@ -30,7 +23,8 @@ fun Prov.configureSSHClient() = def {
* This method is NOT secure as a man-in-the-middle could compromise the connection. * This method is NOT secure as a man-in-the-middle could compromise the connection.
* Don't use this for critical systems resp. environments * Don't use this for critical systems resp. environments
*/ */
fun Prov.trustServer(hostOrIp: String) = def { @Suppress("unused")
fun Prov.trustServer(hostOrIp: String) = task {
cmd("ssh-keyscan $hostOrIp >> ~/.ssh/known_hosts") cmd("ssh-keyscan $hostOrIp >> ~/.ssh/known_hosts")
} }

View file

@ -27,7 +27,7 @@ fun Prov.createUser(
password: Secret? = null, password: Secret? = null,
sudo: Boolean = false, sudo: Boolean = false,
copyAuthorizedSshKeysFromCurrentUser: Boolean = false copyAuthorizedSshKeysFromCurrentUser: Boolean = false
): ProvResult = requireAll { ): ProvResult = task {
if (!userExists(userName)) { if (!userExists(userName)) {
cmd("sudo adduser --gecos \"First Last,RoomNumber,WorkPhone,HomePhone\" --disabled-password --home /home/$userName $userName") cmd("sudo adduser --gecos \"First Last,RoomNumber,WorkPhone,HomePhone\" --disabled-password --home /home/$userName $userName")
} }
@ -54,7 +54,7 @@ fun Prov.createUser(
* Installs and configures git for the user if gitEmail is provided in the config. * Installs and configures git for the user if gitEmail is provided in the config.
* Does NOT CREATE the user. * Does NOT CREATE the user.
*/ */
fun Prov.configureUser(config: UserConfig) = requireAll { fun Prov.configureUser(config: UserConfig) = task {
provisionKeys( provisionKeys(
config.gpg?.keyPair(), config.gpg?.keyPair(),
config.ssh?.keyPair() config.ssh?.keyPair()
@ -70,7 +70,7 @@ fun Prov.configureUser(config: UserConfig) = requireAll {
@Suppress("unused") @Suppress("unused")
fun Prov.deleteUser(userName: String, deleteHomeDir: Boolean = false): ProvResult = requireAll { fun Prov.deleteUser(userName: String, deleteHomeDir: Boolean = false): ProvResult = task {
val flagToDeleteHomeDir = if (deleteHomeDir) " -r " else "" val flagToDeleteHomeDir = if (deleteHomeDir) " -r " else ""
if (userExists(userName)) { if (userExists(userName)) {
cmd("sudo userdel $flagToDeleteHomeDir $userName") cmd("sudo userdel $flagToDeleteHomeDir $userName")
@ -89,7 +89,7 @@ fun Prov.makeUserSudoerWithNoSudoPasswordRequired(
userName: String, userName: String,
password: Secret? = null, password: Secret? = null,
overwriteFile: Boolean = false overwriteFile: Boolean = false
): ProvResult = def { ): ProvResult = task {
val userSudoFile = "/etc/sudoers.d/$userName" val userSudoFile = "/etc/sudoers.d/$userName"
if (!fileExists(userSudoFile) || overwriteFile) { if (!fileExists(userSudoFile) || overwriteFile) {
val sudoPrefix = if (password == null) "sudo" else "echo ${password.plain()} | sudo -S" val sudoPrefix = if (password == null) "sudo" else "echo ${password.plain()} | sudo -S"
@ -108,7 +108,7 @@ fun Prov.makeUserSudoerWithNoSudoPasswordRequired(
* IMPORTANT: Current user must already by sudoer when calling this function. * IMPORTANT: Current user must already by sudoer when calling this function.
*/ */
@Suppress("unused") // used externally @Suppress("unused") // used externally
fun Prov.makeUserSudoerWithNoSudoPasswordRequired(password: Secret) = def { fun Prov.makeUserSudoerWithNoSudoPasswordRequired(password: Secret) = task {
val currentUser = whoami() val currentUser = whoami()
if (currentUser != null) { if (currentUser != null) {
makeUserSudoerWithNoSudoPasswordRequired(currentUser, password, overwriteFile = true) makeUserSudoerWithNoSudoPasswordRequired(currentUser, password, overwriteFile = true)
@ -153,7 +153,7 @@ fun Prov.whoami(): String? {
* @hostPassword pw of hostUser on the remote system; * @hostPassword pw of hostUser on the remote system;
* ssh-key authentication will be used if hostPassword is null * ssh-key authentication will be used if hostPassword is null
*/ */
@Suppress("api") // use externally @Suppress("unused") // use externally
fun createRemoteUser( fun createRemoteUser(
host: InetAddress, host: InetAddress,
hostUser: String, hostUser: String,

View file

@ -13,7 +13,7 @@ internal class DevOpsKtTest {
@ExtensiveContainerTest @ExtensiveContainerTest
fun installKubectlAndTools() { fun installKubectlAndTools() {
// given // given
defaultTestContainer().def { defaultTestContainer().task {
createDirs("/etc/bash_completion.d", sudo = true) createDirs("/etc/bash_completion.d", sudo = true)
createDir(".bashrc.d") createDir(".bashrc.d")
} }

View file

@ -15,11 +15,11 @@ import java.io.PrintStream
internal class ProvTest { internal class ProvTest {
private fun Prov.def_returnungFalse() = def { private fun Prov.task_returningFalse() = task {
ProvResult(false) ProvResult(false)
} }
private fun Prov.def_returningTrue() = def { private fun Prov.task_returningTrue() = task {
ProvResult(true) ProvResult(true)
} }
@ -74,178 +74,178 @@ internal class ProvTest {
} }
@Test @Test
fun def_modeOptional_result_true() { fun task_modeOptional_result_true() {
// given // given
fun Prov.tst_def() = optional { fun Prov.tst_task() = optional {
def_returnungFalse() task_returningFalse()
def_returningTrue() task_returningTrue()
def_returnungFalse() task_returningFalse()
} }
// when // when
val res = testLocal().tst_def().success val res = testLocal().tst_task().success
// then // then
assert(res) assert(res)
} }
@Test @Test
fun def_modeLast_result_true() { fun task_modeLast_result_true() {
// given // given
fun Prov.tst_def() = requireLast { fun Prov.tst_task() = requireLast {
def_returnungFalse() task_returningFalse()
def_returningTrue() task_returningTrue()
} }
// when // when
val res = testLocal().tst_def().success val res = testLocal().tst_task().success
// then // then
assert(res) assert(res)
} }
@Test @Test
fun def_modeLast_result_false() { fun task_modeLast_result_false() {
// given // given
fun Prov.tst_def() = requireLast { fun Prov.tst_task() = requireLast {
def_returningTrue() task_returningTrue()
def_returnungFalse() task_returningFalse()
} }
// when // when
val res = testLocal().tst_def().success val res = testLocal().tst_task().success
// then // then
assert(!res) assert(!res)
} }
@Test @Test
fun def_mode_ALL_result_true() { fun task_mode_ALL_result_true() {
// given // given
fun Prov.tst_def_all_true_mode_ALL() = requireAll { fun Prov.tst_task_all_true_mode_ALL() = task {
def_returningTrue() task_returningTrue()
def_returningTrue() task_returningTrue()
} }
// when // when
val res = testLocal().tst_def_all_true_mode_ALL().success val res = testLocal().tst_task_all_true_mode_ALL().success
// then // then
assert(res) assert(res)
} }
// given // given
fun Prov.tst_def_one_false_mode_ALL() = requireAll { fun Prov.tst_task_one_false_mode_ALL() = task {
def_returningTrue() task_returningTrue()
def_returnungFalse() task_returningFalse()
def_returningTrue() task_returningTrue()
} }
@Test @Test
fun def_modeALL_resultFalse() { fun task_modeALL_resultFalse() {
// when // when
val res = testLocal().tst_def_one_false_mode_ALL().success val res = testLocal().tst_task_one_false_mode_ALL().success
// then // then
assert(!res) assert(!res)
} }
// given // given
fun Prov.tst_def_one_false_mode_ALL_nested() = requireAll { fun Prov.tst_task_one_false_mode_ALL_nested() = task {
def_returningTrue() task_returningTrue()
tst_def_one_false_mode_ALL() tst_task_one_false_mode_ALL()
def_returningTrue() task_returningTrue()
tst_ALL_returningTrue() tst_ALL_returningTrue()
} }
// given // given
fun Prov.tst_ALL_returningTrue() = requireAll { fun Prov.tst_ALL_returningTrue() = task {
ProvResult(true) ProvResult(true)
} }
@Test @Test
fun def_modeALLnested_resultFalse() { fun task_modeALLnested_resultFalse() {
// when // when
val res = testLocal().tst_def_one_false_mode_ALL_nested().success val res = testLocal().tst_task_one_false_mode_ALL_nested().success
// then // then
assert(!res) assert(!res)
} }
@Test @Test
fun def_mode_ALL_LAST_NONE_nested() { fun task_mode_ALL_LAST_NONE_nested() {
// given // given
fun Prov.tst_def_last() = def { fun Prov.tst_task_last() = task {
def_returningTrue() task_returningTrue()
def_returnungFalse() task_returningFalse()
} }
fun Prov.tst_def_one_false_mode_ALL() = requireAll { fun Prov.tst_task_one_false_mode_ALL() = task {
tst_def_last() tst_task_last()
def_returningTrue() task_returningTrue()
} }
// when // when
val res = testLocal().tst_def_one_false_mode_ALL().success val res = testLocal().tst_task_one_false_mode_ALL().success
// then // then
assert(!res) assert(!res)
} }
@Test @Test
fun def_mode_FAILEXIT_nested_false() { fun task_mode_FAILEXIT_nested_false() {
// given // given
fun Prov.tst_def_failexit_inner() = exitOnFailure { fun Prov.tst_task_failexit_inner() = exitOnFailure {
def_returningTrue() task_returningTrue()
def_returnungFalse() task_returningFalse()
} }
fun Prov.tst_def_failexit_outer() = exitOnFailure { fun Prov.tst_task_failexit_outer() = exitOnFailure {
tst_def_failexit_inner() tst_task_failexit_inner()
def_returningTrue() task_returningTrue()
} }
// when // when
val res = testLocal().tst_def_failexit_outer().success val res = testLocal().tst_task_failexit_outer().success
// then // then
assert(!res) assert(!res)
} }
@Test @Test
fun def_mode_FAILEXIT_nested_true() { fun task_mode_FAILEXIT_nested_true() {
// given // given
fun Prov.tst_def_failexit_inner() = exitOnFailure { fun Prov.tst_task_failexit_inner() = exitOnFailure {
def_returningTrue() task_returningTrue()
def_returningTrue() task_returningTrue()
} }
fun Prov.tst_def_failexit_outer() = exitOnFailure { fun Prov.tst_task_failexit_outer() = exitOnFailure {
tst_def_failexit_inner() tst_task_failexit_inner()
def_returningTrue() task_returningTrue()
} }
// when // when
val res = testLocal().tst_def_failexit_outer().success val res = testLocal().tst_task_failexit_outer().success
// then // then
assert(res) assert(res)
} }
@Test @Test
fun def_mode_multiple_nested() { fun task_mode_multiple_nested() {
// given // given
fun Prov.tst_nested() = def { fun Prov.tst_nested() = task {
requireAll { task {
def_returningTrue() task_returningTrue()
def { task {
def_returnungFalse() task_returningFalse()
def_returningTrue() task_returningTrue()
} }
def_returnungFalse() task_returningFalse()
def_returningTrue() task_returningTrue()
optional { optional {
def_returnungFalse() task_returningFalse()
} }
} }
} }
@ -428,7 +428,7 @@ internal class ProvTest {
addResultToEval(ProvResult(true)) addResultToEval(ProvResult(true))
} }
fun Prov.outer() = requireAll { fun Prov.outer() = task {
inner() inner()
ProvResult(true) ProvResult(true)
} }
@ -485,7 +485,7 @@ internal class ProvTest {
addResultToEval(ProvResult(false)) addResultToEval(ProvResult(false))
} }
fun Prov.outer() = requireAll { fun Prov.outer() = task {
inner() inner()
ProvResult(true) ProvResult(true)
} }
@ -505,19 +505,19 @@ internal class ProvTest {
val containerName = "provs_test" val containerName = "provs_test"
testLocal().provideContainer(containerName, "ubuntu") testLocal().provideContainer(containerName, "ubuntu")
fun Prov.inner() = def { fun Prov.inner() = task {
cmd("echo in container") cmd("echo in container")
} }
// then // then
fun Prov.outer() = def { fun Prov.outer() = task {
taskInContainer(containerName) { taskInContainer(containerName) {
inner() inner()
cmd("echo testfile > testfile.txt") cmd("echo testfile > testfile.txt")
} }
} }
val res = testLocal().def { outer() } val res = testLocal().task { outer() }
// then // then
assertEquals(true, res.success) assertEquals(true, res.success)
@ -530,12 +530,12 @@ internal class ProvTest {
val host = "192.168.56.135" val host = "192.168.56.135"
val remoteUser = "az" val remoteUser = "az"
fun Prov.inner() = def { fun Prov.inner() = task {
cmd("echo 'in testfile' > testfile.txt") cmd("echo 'in testfile' > testfile.txt")
} }
// then // then
val res = remote(host, remoteUser).def { val res = remote(host, remoteUser).task {
inner() // executed on the remote host inner() // executed on the remote host
taskInContainer("prov_default") { taskInContainer("prov_default") {
inner() // executed in the container on the remote host inner() // executed in the container on the remote host

View file

@ -18,7 +18,7 @@ internal class UbuntuHostDockerKtTest {
fun runAndCheckAndExitContainer() { fun runAndCheckAndExitContainer() {
// when // when
val containerName = "testContainer" val containerName = "testContainer"
val result = testLocal().requireAll { val result = testLocal().task {
runContainer(containerName) runContainer(containerName)
addResultToEval(ProvResult(containerRuns(containerName))) addResultToEval(ProvResult(containerRuns(containerName)))

View file

@ -35,7 +35,7 @@ internal class ProvisionFirewallKtTest {
) )
// when // when
val res = a.requireAll { val res = a.task {
aptInstall("iptables") aptInstall("iptables")
provisionFirewall() provisionFirewall()
} }

View file

@ -15,7 +15,7 @@ internal class ProvisionNexusKtTest {
val a = defaultTestContainer() val a = defaultTestContainer()
// when // when
val res = a.requireAll { val res = a.task {
provisionNexusWithDocker() provisionNexusWithDocker()
} }

View file

@ -34,7 +34,7 @@ internal class ProvisionNginxKtTest {
a.aptInstall("curl") a.aptInstall("curl")
// when // when
val res = a.requireAll { val res = a.task {
provisionNginxStandAlone(NginxConf(config)) provisionNginxStandAlone(NginxConf(config))
cmd("curl localhost") cmd("curl localhost")
} }
@ -51,7 +51,7 @@ internal class ProvisionNginxKtTest {
val a = defaultTestContainer() val a = defaultTestContainer()
// when // when
val res = a.requireAll { val res = a.task {
provisionNginxStandAlone() provisionNginxStandAlone()
} }
@ -65,7 +65,7 @@ internal class ProvisionNginxKtTest {
fun provisionNginxStandAlone_sslConfig() { fun provisionNginxStandAlone_sslConfig() {
// given // given
val a = defaultTestContainer() val a = defaultTestContainer()
a.def { a.task {
val file = "/etc/ssl/openssl.cnf" val file = "/etc/ssl/openssl.cnf"
if (fileExists(file)) { if (fileExists(file)) {
replaceTextInFile(file, "RANDFILE", "#RANDFILE") replaceTextInFile(file, "RANDFILE", "#RANDFILE")
@ -74,7 +74,7 @@ internal class ProvisionNginxKtTest {
} }
// when // when
val res = a.def { val res = a.task {
nginxCreateSelfSignedCertificate() nginxCreateSelfSignedCertificate()
provisionNginxStandAlone( provisionNginxStandAlone(

View file

@ -12,7 +12,7 @@ internal class FakturamaKtTest {
// given // given
val a = defaultTestContainer() val a = defaultTestContainer()
// when // when
val res = a.def { installFakturama() } val res = a.task { installFakturama() }
// then // then
assertTrue(res.success) assertTrue(res.success)
} }

View file

@ -47,7 +47,7 @@ internal class GopassBridgeKtTest {
// given // given
local().exitAndRmContainer("provs_test") local().exitAndRmContainer("provs_test")
val a = defaultTestContainer() val a = defaultTestContainer()
val preparationResult = a.def { val preparationResult = a.task {
aptInstallCurl() aptInstallCurl()
configureGpgKeys( configureGpgKeys(
KeyPair(Secret(publicGPGSnakeoilKey()), Secret(privateGPGSnakeoilKey())), KeyPair(Secret(publicGPGSnakeoilKey()), Secret(privateGPGSnakeoilKey())),
@ -65,7 +65,7 @@ internal class GopassBridgeKtTest {
assertTrue(preparationResult.success) assertTrue(preparationResult.success)
// when // when
val res = a.def { val res = a.task {
installGopassBridgeJsonApi() installGopassBridgeJsonApi()
configureGopassBridgeJsonApi() configureGopassBridgeJsonApi()
} }
@ -81,7 +81,7 @@ internal class GopassBridgeKtTest {
fun test_install_GopassBridgeJsonApi_with_incompatible_gopass_jsonapi_version_installed() { fun test_install_GopassBridgeJsonApi_with_incompatible_gopass_jsonapi_version_installed() {
// given // given
val a = defaultTestContainer(ContainerStartMode.CREATE_NEW_KILL_EXISTING) val a = defaultTestContainer(ContainerStartMode.CREATE_NEW_KILL_EXISTING)
val preparationResult = a.def { val preparationResult = a.task {
aptInstallCurl() aptInstallCurl()
configureGpgKeys( configureGpgKeys(
@ -100,7 +100,7 @@ internal class GopassBridgeKtTest {
assertTrue(preparationResult.success) assertTrue(preparationResult.success)
// when // when
val res = a.def { val res = a.task {
installGopassBridgeJsonApi() installGopassBridgeJsonApi()
configureGopassBridgeJsonApi() configureGopassBridgeJsonApi()
} }
@ -116,7 +116,7 @@ internal class GopassBridgeKtTest {
fun test_install_GopassBridgeJsonApi_with_incompatible_gopass_version_installed() { fun test_install_GopassBridgeJsonApi_with_incompatible_gopass_version_installed() {
// given // given
val a = defaultTestContainer(ContainerStartMode.CREATE_NEW_KILL_EXISTING) val a = defaultTestContainer(ContainerStartMode.CREATE_NEW_KILL_EXISTING)
val preparationResult = a.def { val preparationResult = a.task {
aptInstallCurl() aptInstallCurl()
configureGpgKeys( configureGpgKeys(
KeyPair(Secret(publicGPGSnakeoilKey()), Secret(privateGPGSnakeoilKey())), KeyPair(Secret(publicGPGSnakeoilKey()), Secret(privateGPGSnakeoilKey())),
@ -134,7 +134,7 @@ internal class GopassBridgeKtTest {
assertTrue(preparationResult.success) assertTrue(preparationResult.success)
// when // when
val res = a.def { val res = a.task {
installGopassBridgeJsonApi() installGopassBridgeJsonApi()
configureGopassBridgeJsonApi() configureGopassBridgeJsonApi()
} }
@ -143,7 +143,7 @@ internal class GopassBridgeKtTest {
assertFalse(res.success) assertFalse(res.success)
} }
private fun Prov.aptInstallCurl() = def { private fun Prov.aptInstallCurl() = task {
cmd("apt-get update", sudo = true) cmd("apt-get update", sudo = true)
aptInstall("curl") aptInstall("curl")
} }

View file

@ -79,7 +79,7 @@ internal class GopassKtTest {
val a = remote(host, user) val a = remote(host, user)
// when // when
val res = a.def { val res = a.task {
configureGpgKeys( configureGpgKeys(
KeyPair( KeyPair(
pubKey, pubKey,