job "mysql-backup" {
  datacenters = ["alo"]
  type = "batch"

  periodic {
    crons = ["23 23 * * * *"]
    prohibit_overlap = true
  }

  group "db" {
    # Run on primary storage node for fast local disk access
    constraint {
      attribute = "${meta.storage_role}"
      value     = "primary"
    }

    task "backup" {
      driver = "raw_exec"

      config {
        command = "/bin/sh"
        args = [ "local/script.sh" ]
      }

      template {
        destination = "local/script.sh"
        data = <<EOH
          set -e
          /run/current-system/sw/bin/nomad alloc exec -job -task=mysqld mysql \
            mysqldump -u root --password="$MYSQL_ROOT_PASS" --all-databases > /data/services/db-backups/mysql/backup.sql && \
          echo "last_success $(date +%s)" | \
          /run/current-system/sw/bin/curl --data-binary @- http://pushgateway.service.consul:9091/metrics/job/mysql_backup
        EOH
      }

      template {
        destination = "secrets/file.env"
        env = true
        data = <<EOH
          {{- with nomadVar "secrets/mysql" -}}MYSQL_ROOT_PASS="{{ .root_password }}"{{- end -}}
        EOH
      }
    }
  }
}
