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

smf*_*ftr 3 openshift openshift-origin kubernetes

这是在kubernetes yaml(helloworld.yaml)中运行简单批处理的方法:

...
image: "ubuntu:14.04"
command: ["/bin/echo", "hello", "world"]
...
Run Code Online (Sandbox Code Playgroud)

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

$ kubectl create -f helloworld.yaml
Run Code Online (Sandbox Code Playgroud)

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

#!/bin/bash
echo "Please wait....";
sleep 5
Run Code Online (Sandbox Code Playgroud)

有没有办法将script.sh包含进去,kubectl create -f以便它可以运行脚本。现在假设helloworld.yaml像这样编辑:

...
image: "ubuntu:14.04"
command: ["/bin/bash", "./script.sh"]
...
Run Code Online (Sandbox Code Playgroud)

rul*_*web 15

正如这里所解释的,您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
Run Code Online (Sandbox Code Playgroud)

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

  • 你救了我的命!!! (2认同)

Ald*_*inn 5

我在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: {}
Run Code Online (Sandbox Code Playgroud)

  • 我只是想强调“restartPolicy: Never”的重要性,因为否则你可能会得到“CrashLoopBackOff”。[参见此处](/sf/answers/3555618811/)。 (4认同)