[lxc-users] is there a lxc-attach -v switch equivalent in lxc python bindings ?

Stéphane Graber stgraber at ubuntu.com
Tue Mar 14 12:37:26 UTC 2017


On Tue, Mar 14, 2017 at 11:22:26AM +0100, Benoit Barthelet wrote:
> ultimately I'd like to do this in python:
> 
> lxc-attach --clear-env -n lxcws -v TERM=xterm
> 
> So far I managed to clear the env variables doing the following, but I
> didn't find a way to pass the TERM env variable.
> 
> container.attach_wait(lxc.attach_run_command,
>                       ["apt-get", "dist-upgrade", "-y"],
>                       env_policy=lxc.LXC_ATTACH_CLEAR_ENV)

Easiest I think is to use your own attach function instead of the
generic lxc.attach_run_command. In that function you can then set
os.environ as you want and call subprocess to run the command you want.

In the lxc-ci code we have something like this:

    def execute(self, cmd, cwd="/"):
        def run_command(args):
            cmd, cwd = args

            os.environ['PATH'] = '/usr/sbin:/usr/bin:/sbin:/bin'
            os.environ['HOME'] = '/root'
            if "env" in config and "proxy" in config['env']:
                os.environ["DEBIAN_FRONTEND"] = "noninteractive"
                os.environ['http_proxy'] = config['env']['proxy']
                os.environ['https_proxy'] = config['env']['proxy']

            return subprocess.call(cmd, cwd=cwd)

        if isinstance(cmd, str):
            pid = self.container.init_pid
            cmdpath = "/proc/%d/root/tmp/exec_script" % pid
            with open(cmdpath, "w+") as fd:
                fd.write(cmd)
            os.chmod(cmdpath, 0o755)
            cmd = ["/tmp/exec_script"]

        print(" ==> Executing: \"%s\" in %s" % (" ".join(cmd), cwd))
        return self.container.attach_wait(run_command,
                                          (cmd, cwd),
                                          env_policy=lxc.LXC_ATTACH_CLEAR_ENV)



-- 
Stéphane Graber
Ubuntu developer
http://www.ubuntu.com
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 801 bytes
Desc: not available
URL: <http://lists.linuxcontainers.org/pipermail/lxc-users/attachments/20170314/9b1c5c92/attachment.sig>


More information about the lxc-users mailing list