如何包含脚本并将其运行到kubernetes yaml中?

时间:2017-01-16 10:20:12

标签: openshift kubernetes openshift-origin

如何在kubernetes yaml(helloworld.yaml)中运行简单批处理:

...
image: "ubuntu:14.04"
command: ["/bin/echo", "hello", "world"]
...

在Kubernetes中,我可以像这样部署:

$ kubectl create -f helloworld.yaml

假设我有一个像这样的批处理脚本(script.sh):

#!/bin/bash
echo "Please wait....";
sleep 5

是否可以将script.sh包含到kubectl create -f中,以便它可以运行脚本。假设现在helloworld.yaml编辑如下:

...
image: "ubuntu:14.04"
command: ["/bin/bash", "./script.sh"]
...

3 个答案:

答案 0 :(得分:4)

我在OpenShift中使用这种方法,所以它也适用于Kubernetes。

尝试将您的脚本放入configmap键/值,将此configmap作为卷安装并从卷中运行脚本。

apiVersion: batch/v1
kind: Job
metadata:
  name: hello-world-job
spec:
  parallelism: 1    
  completions: 1    
  template:         
    metadata:
      name: hello-world-job
    spec:
      volumes:
      - name: hello-world-scripts-volume
        configMap:
          name: hello-world-scripts
      containers:
      - name: hello-world-job
        image: alpine
        volumeMounts:
          - mountPath: /hello-world-scripts
            name: hello-world-scripts-volume
        env:
          - name: HOME
            value: /tmp
        command:
        - /bin/sh
        - -c
        - |
          echo "scripts in /hello-world-scripts"
          ls -lh /hello-world-scripts
          echo "copy scripts to /tmp"
          cp /hello-world-scripts/*.sh /tmp
          echo "apply 'chmod +x' to /tmp/*.sh"
          chmod +x /tmp/*.sh
          echo "execute script-one.sh now"
          /tmp/script-one.sh
      restartPolicy: Never
---
apiVersion: v1
items:
- apiVersion: v1
  data:
    script-one.sh: |
      echo "script-one.sh"
      date
      sleep 1
      echo "run /tmp/script-2.sh now"
      /tmp/script-2.sh
    script-2.sh: |
      echo "script-2.sh"
      sleep 1
      date
  kind: ConfigMap
  metadata:
    creationTimestamp: null
    name:  hello-world-scripts
kind: List
metadata: {}

答案 1 :(得分:0)

here所述,您也可以使用defaultMode: 0777属性,例如:

apiVersion: v1
kind: ConfigMap
metadata:
  name: test-script
data:
  test.sh: |
    echo "test1"
    ls
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: test
spec:
  selector:
    matchLabels:
      app: test
  template:
    metadata:
      labels:
        app: test
    spec:
      volumes:
      - name: test-script
        configMap:
          name: test-script
          defaultMode: 0777
      containers:
      - command:
        - sleep
        - infinity
        image: ubuntu
        name: locust
        volumeMounts:
          - mountPath: /test-script
            name: test-script

您可以进入容器外壳并执行脚本/test-script/test.sh

答案 2 :(得分:-1)

是的,这是可能的,但您需要构建一个包含脚本的docker容器。

我建议阅读this getting started guide

在本地获得有效的docker镜像后,将其推送到docker存储库(例如hub.docker.com),然后替换" image"使用我们自己的图像定义yaml文件,例如:

image: "my-custom-image:latest"

另外要记住的一点是,如果脚本是您想要执行一次的临时过程(即非Web服务),您可以考虑使用kubernetes job