Search code examples
mongodbpowershellshellkubectlpester

Get return value from kubectl exec out into powershell script


So I'm working on a powershell script that runs a pester test. The script connects to a Kubernetes pod with a Mongo database. The goal is to check whether or not a collection in the database is empty. I'm happy with the code up until the "return count" line. I'm aware there is no return command in shell, but I've put it in to illustrate.

I'm essentially trying to get the "count" value out from "kubectl exec" into the powershell code. Is this possible?

Context "Foo collection" {
It "should have no documents"{

    kubectl exec -it $podName -n mongo `
        -- mongosh -u root -p $mongoSecret `
        --eval "`
        db = db.getSiblingDB('thisOne')
        collection = db.getCollection('foo')
        count = collection.countDocuments({}, {limit: 1})

        return count
    "

    $docs = count
    $docs | Should -Be 0
}

}


Solution

  • Storing the return of kubectl in a variable did the trick. eval outputs the return of the final command in the script to stdout. However, the --quiet parameter was needed to get the return value without paragraphs of mongodb shell "noise".

    Context "Foo collection" {
        It "should have no documents"{
    
            $count = kubectl exec -it $podName -n mongo `
                -- mongosh --quiet -u root -p $mongoSecret `
                --eval "`
                db = db.getSiblingDB('thisOne')
                collection = db.getCollection('foo')
                collection.countDocuments({}, {limit: 1})
                "
    
            $count | Should -Be 0
        }
    }