I am trying to run a series of commands to create and add the same type of user to multiple mongodbs.
Currently I make a connection to the pod I want: connect = os.system("kubectl exec -n epic-dev zerodtmongo-0 -it -- /bin/sh"
but my python script ends there and the new shell for that pod opens within the python terminal.
I would like to continue the python script to execute this block of code within multiple pods I have stored in a list.
# Create roles to create roles 'listDatabase' & 'readChangeStream'
mongo -u admin -p admin localhost:27017/admin <<-EOF
db.runCommand(
{
createRole: "listDatabases",
privileges: [
{
resource: {cluster : true},
actions: ["listDatabases"]
}
],
roles: []
}
);
db.runCommand(
{
createRole: "readChangeStream",
privileges: [
{
resource: { db: "", collection: ""},
actions: [ "find", "changeStream" ]
}
],
roles: []
});
EOF
# Create a debezium user
mongo -u admin -p admin localhost:27017/admin <<-EOF
db.createUser(
{
user: 'foo',
pwd: 'bar',
roles: [
{ role: "read", db: "admin" }
]
});
EOF
Something like:
for pods in list:
connect(pod)
add user
close connection
2
Answers
you should use the python Kubernetes client to leverage the maximum benefit.
kubernetes-client-python
Here is the working example that expects the Kube config already set up.
python3 k8_create_db.py
Using official K8s client,
Ref : https://github.com/kubernetes-client/python/blob/master/examples/pod_exec.py