在不使用kubectl cp的情况下将文件复制到kubernetes pod [英] Copy a file into kubernetes pod without using kubectl cp

查看:1067
本文介绍了在不使用kubectl cp的情况下将文件复制到kubernetes pod的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用例,其中,我的Pod以非root用户身份运行,并且运行python应用程序. 现在,我想将文件从主节点复制到正在运行的Pod.但是当我尝试运行

I have a use case where my pod is run as non-rootuser and its running a python app. Now I want to copy file from master node to running pod. But when I try to run

kubectl cp app.py 103000-pras-dev/simplehttp-777fd86759-w79pn:/tmp

此命令挂起,但是当我以root用户身份运行pod并运行相同的命令时 它执行成功.我正在查看kubectl cp的代码,其中它在内部使用tar命令.

This command hungs up but when i run pod as root user and then run the same command it executes successfully. I was going through the code of kubectl cp where it internally uses tar command.

Tar命令有多个标志,例如--overwrite --no-same-owner,--no-preserve和其他几个标志.现在,从kubectl cp中,我们无法将所有这些标志传递给tar.是否可以使用kubectl exec命令或其他任何方式复制文件.

Tar command has got multiple flags like --overwrite --no-same-owner, --no-preserve and few others. Now from kubectl cp we can't pass all those flag to tar. Is there any way by which I can copy file using kubectl exec command or any other way.

kubectl exec simplehttp-777fd86759-w79pn -- cp app.py /tmp/ **flags**

推荐答案

与此同时,我发现了一个黑客,免责声明,但这并不是确切的kubectl cp,只是一种解决方法.

Meanwhile I found a hack, disclaimer this is not the exact kubectl cp just a workaround.

我编写了一个go程序,在其中创建了一个goroutine来读取文件,并将其附加到stdin并运行带有适当标志的kubectl exec tar命令.这是我所做的

I have written a go program where I have created a goroutine to read file and attached that to stdin and ran kubectl exec tar command with proper flags. Here is what I did

reader, writer := io.Pipe()
copy := exec.CommandContext(ctx, "kubectl", "exec", pod.Name, "--namespace", pod.Namespace, "-c", container.Name, "-i",
    "--", "tar", "xmf", "-", "-C", "/", "--no-same-owner") // pass all the flags you want to
copy.Stdin = reader
go func() {
    defer writer.Close()

    if err := util.CreateMappedTar(writer, "/", files); err != nil {
        logrus.Errorln("Error creating tar archive:", err)
    }
}()

Helper函数定义

Helper function definition

func CreateMappedTar(w io.Writer, root string, pathMap map[string]string) error {
    tw := tar.NewWriter(w)
    defer tw.Close()

    for src, dst := range pathMap {
        if err := addFileToTar(root, src, dst, tw); err != nil {
            return err
        }

    }

    return nil
}

很明显,由于权限问题,这东西不起作用,但是*我能够传递tar标志

Obviously, this thing doesn't work because of permission issue but *I was able to pass tar flags

这篇关于在不使用kubectl cp的情况下将文件复制到kubernetes pod的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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