I am creating a Kubernetes cronjob that needs to write files, for that purpose, I have a server with the directory /data where the files shall be created.
My deployment is using Terraform.
My PersistentVolume:
resource "kubernetes_persistent_volume" "cronjob-demo-pv" {
metadata {
name = "cronjob-demo-pv"
}
spec {
capacity = {
storage = "490Gi"
}
access_modes = ["ReadWriteOnce"]
storage_class_name = "standard"
persistent_volume_source {
host_path {
type = "DirectoryOrCreate"
path = "/data"
}
}
node_affinity {
required {
node_selector_term {
match_expressions {
key = "kubernetes.io/hostname"
operator = "In"
values = ["<server-ip>"] # Replace <server-ip> for the IP of my server
}
}
}
}
}
}
My PersistentVolumeClaim:
resource "kubernetes_persistent_volume_claim" "cronjob-demo-pvc" {
metadata {
name = "cronjob-demo-pvc"
namespace = "testing"
}
spec {
access_modes = ["ReadWriteOnce"]
resources {
requests = {
storage = "490Gi"
}
}
storage_class_name = "standard"
volume_name = "${kubernetes_persistent_volume.cronjob-demo-pv.metadata.0.name}"
}
}
My CronJob:
resource "kubernetes_cron_job" "demo" {
metadata {
name = "demo"
namespace = "testing"
}
spec {
concurrency_policy = "Replace"
failed_jobs_history_limit = 5
schedule = "* * * * *"
successful_jobs_history_limit = 10
job_template {
metadata {}
spec {
backoff_limit = 2
template {
metadata {}
spec {
volume {
name = "cronjob-demo-pv"
persistent_volume_claim {
claim_name = "${kubernetes_persistent_volume_claim.cronjob-demo-pvc.metadata.0.name}"
}
}
container {
name = "hello"
image = "busybox"
# command = ["/bin/sh", "-c", "echo 'Hello World'"]
# command = ["bin/sh", "-c", "touch /data/helloworld.txt; ls /data"]
command = ["bin/sh", "-c", "ls; pwd"]
volume_mount {
name = "mount-data-cronjob"
mount_path = "/data"
}
}
}
}
}
}
}
}
When I deploy this infrastructure, the command "ls" that I am running in the CronJob doesn't show my /data directory, which I need in order to write files.
What do I need to do to make my CronJob mount the volume /data successfully? Am I missing something or doing something wrong?
I tried using the "volume" and "volume_mount" in my CronJob definition, I don't know if there's something I am missing.
From what you’ve shared, I have a couple of suggestions.
Ensure the names in the volume
and volume_mount
sections are identical to establish the correct mount.
volume_mounts = [
{
name = "cronjob-demo-pv"
mount_path = "/data"
}
]
I’ll also advice you use the full path for shell commands and ensure the commands are correctly structured.
command = ["/bin/sh", "-c", "touch /data/helloworld.txt && ls /data"]
These changes should get your CronJob to mount the /data
volume correctly and execute your command within that directory.