GCP云功能-在路径上找不到kubectl [英] GCP cloud function - Could not find kubectl on the path

查看:177
本文介绍了GCP云功能-在路径上找不到kubectl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写此Google Cloud Function(Python)

def create_kubeconfig(request):
    subprocess.check_output("curl https://sdk.cloud.google.com | bash | echo "" ",stdin=subprocess.PIPE, shell=True )
    os.system("./google-cloud-sdk/install.sh")
    os.system("gcloud init")
    os.system("curl -LO https://storage.googleapis.com/kubernetes-release/release/v1.17.0/bin/linux/amd64/kubectl")

    os.system("gcloud container clusters get-credentials **cluster name** --zone us-west2-a --project **project name**")
    os.system("gcloud container clusters get-credentials **cluster name** --zone us-west2-a --project **project name**")
    conf = KubeConfig()
    conf.use_context('**cluster name**')

当我运行代码时,它给了我错误 无效的kube-config文件. 'kubernetes.config.config_exception.ConfigException:无效的kube-config文件.找不到配置.

请帮助我解决它

解决方案

您必须以编程方式访问K8S API.您在文档中具有 API的描述

但是执行起来并不容易.但是,这里提供了一些用于实现您想要的内容的输入.

首先,获取GKE主IP

然后,您可以轻松访问集群.在这里阅读部署

    import google.auth
    from google.auth.transport import requests
    credentials, project_id = google.auth.default()
    session = requests.AuthorizedSession(credentials)
    response = session.get('https://34.76.28.194/apis/apps/v1/namespaces/default/deployments', verify=False)
    response.raise_for_status()
    print(response.json())

要创建一个,您可以执行此操作

    import google.auth
    from google.auth.transport import requests
    credentials, project_id = google.auth.default()
    session = requests.AuthorizedSession(credentials)
    with open("deployment.yaml", "r") as f:
        data = f.read()
    response = session.post('https://34.76.28.194/apis/apps/v1/namespaces/default/deployments', data=data,
                            headers={'content-type': 'application/yaml'}, verify=False)
    response.raise_for_status()
    print(response.json())

根据要构建的对象,必须使用正确的文件定义和正确的API端点.我不知道一种仅在一个API调用中应用带有多个定义的整个yaml的方法.

最后,请务必提供正确的GKE角色到Cloud Function服务帐户

更新

另一种解决方案是使用Cloud Run.确实,有了Cloud Run并借助Container功能,您就可以安装和调用系统进程(它完全开放,因为

注意:图像云SDK图像很重:700Mb

内容示例(仅是一条快乐的路.我删除了错误管理,以及用于简化代码的stderr/stdout反馈)

    .......
// Example here: recover the yaml file into a bucket
    client,_ := storage.NewClient(ctx)
    reader,_ := client.Bucket("my_bucket").Object("deployment.yaml").NewReader(ctx)
    content,_:= ioutil.ReadAll(reader)
// You can store locally the file into /tmp directory. It's an in-memory file system. Don't forget to purge it to avoid any out of memory crash
    ioutil.WriteFile("/tmp/file.yaml",content, 0644)
// Execute external command
// 1st Recover the kube authentication
    exec.Command("gcloud","container","clusters","get-credentials","cluster-1","--zone=us-central1-c").Run()
// Then interact with the cluster with kubectl tools and simply apply your description file
    exec.Command("kubectl","apply", "-f","/tmp/file.yaml").Run()
    .......

i'm writing this Google Cloud Function (Python)

def create_kubeconfig(request):
    subprocess.check_output("curl https://sdk.cloud.google.com | bash | echo "" ",stdin=subprocess.PIPE, shell=True )
    os.system("./google-cloud-sdk/install.sh")
    os.system("gcloud init")
    os.system("curl -LO https://storage.googleapis.com/kubernetes-release/release/v1.17.0/bin/linux/amd64/kubectl")

    os.system("gcloud container clusters get-credentials **cluster name** --zone us-west2-a --project **project name**")
    os.system("gcloud container clusters get-credentials **cluster name** --zone us-west2-a --project **project name**")
    conf = KubeConfig()
    conf.use_context('**cluster name**')

when i run the code it gives me the error 'Invalid kube-config file. ' kubernetes.config.config_exception.ConfigException: Invalid kube-config file. No configuration found.

help me to solve it please

解决方案

You have to reach programmatically the K8S API. You have the description of the API in the documentation

But it's not easy and simple to perform. However, here some inputs for achieving what you want.

First, get the GKE master IP

Then you can access to the cluster easily. Here for reading the deployment

    import google.auth
    from google.auth.transport import requests
    credentials, project_id = google.auth.default()
    session = requests.AuthorizedSession(credentials)
    response = session.get('https://34.76.28.194/apis/apps/v1/namespaces/default/deployments', verify=False)
    response.raise_for_status()
    print(response.json())

For creating one, you can do this

    import google.auth
    from google.auth.transport import requests
    credentials, project_id = google.auth.default()
    session = requests.AuthorizedSession(credentials)
    with open("deployment.yaml", "r") as f:
        data = f.read()
    response = session.post('https://34.76.28.194/apis/apps/v1/namespaces/default/deployments', data=data,
                            headers={'content-type': 'application/yaml'}, verify=False)
    response.raise_for_status()
    print(response.json())

According with the object that you want to build, you have to use the correct file definition and the correct API endpoint. I don't know a way to apply a whole yaml with several definition in only one API call.

Last things, be sure to provide the correct GKE roles to the Cloud Function service Account

UPDATE

Another solution is to use Cloud Run. Indeed, with Cloud Run and thanks to the Container capability, you have the ability to install and to call system process (it's totally open because your container runs into a GVisor sandbox, but most of common usages are allowed)

The idea is the following: use a gcloud SDK base image and deploy your application on it. Then, code your app to perform system calls.

Here a working example in Go

Docker file

FROM golang:1.13 as builder

# Copy local code to the container image.
WORKDIR /app/
COPY go.mod .
ENV GO111MODULE=on
RUN go mod download

COPY . .

# Perform test for building a clean package
RUN go test -v ./...
RUN CGO_ENABLED=0 GOOS=linux go build -v -o server

# Gcloud capable image
FROM google/cloud-sdk

COPY --from=builder /app/server /server
CMD ["/server"]

Note: The image cloud-sdk image is heavy: 700Mb

The content example (only the happy path. I remove error management, and the stderr/stdout feedback for simplifying the code)

    .......
// Example here: recover the yaml file into a bucket
    client,_ := storage.NewClient(ctx)
    reader,_ := client.Bucket("my_bucket").Object("deployment.yaml").NewReader(ctx)
    content,_:= ioutil.ReadAll(reader)
// You can store locally the file into /tmp directory. It's an in-memory file system. Don't forget to purge it to avoid any out of memory crash
    ioutil.WriteFile("/tmp/file.yaml",content, 0644)
// Execute external command
// 1st Recover the kube authentication
    exec.Command("gcloud","container","clusters","get-credentials","cluster-1","--zone=us-central1-c").Run()
// Then interact with the cluster with kubectl tools and simply apply your description file
    exec.Command("kubectl","apply", "-f","/tmp/file.yaml").Run()
    .......

这篇关于GCP云功能-在路径上找不到kubectl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆