首页 > 解决方案 > Ansible 在远程 Ubuntu 机器上打开终端并运行程序

问题描述

我正在使用 Ansible 设置 Ubuntu 18.04(远程)实例并在用户环境中运行某些程序。我有一个命令我想在遥控器上的终端内执行,需要终端保持打开状态。

如果我在 Ubuntu 上运行以下命令,我会得到我所期望的。

# DISPLAY=:0 nohup gnome-terminal -- roscore
  1. 为用户使用当前显示
  2. nohup 所以如果父终端关闭,终端将不会关闭
  3. 启动一个新的 gnome-terminal 实例
  4. -- = 在新的 gnome-terminal 实例中运行命令
  5. roscore 可以替换为任何需要打开终端窗口的流的命令

尝试重新创建相同的命令时,我的 Ansible 任务看起来像这样

- name: Start terminal on remote machine
  shell:
  args:
    cmd: DISPLAY=:0 nohup gnome-terminal -- roscore
    executable: /bin/bash

运行此命令时,我得到以下详细输出

changed: [] => {
"changed": true,
"cmd": "DISPLAY=:0 nohup gnome-terminal -- roscore",
"delta": "0:00:00.243119",
"end": "",
"invocation": {
    "module_args": {
        "_raw_params": "DISPLAY=:0 nohup gnome-terminal -- roscore",
        "_uses_shell": true,
        "argv": null,
        "chdir": null,
        "creates": null,
        "executable": "/bin/bash",
        "removes": null,
        "stdin": null,
        "stdin_add_newline": true,
        "strip_empty_ends": true,
        "warn": true
    }
},
"rc": 0,
"start": "",
"stderr": "nohup: ignoring input",
"stderr_lines": [
    "nohup: ignoring input"
],
"stdout": "",
"stdout_lines": []
}

当我执行此操作时,终端似乎在远程机器上打开了一会儿,但它并没有保持打开状态。Ansible 在做什么会在运行命令后关闭远程终端会话?

我想要的是一个 Ansible 任务,它允许在远程 Ubuntu 18.04 机器上打开终端窗口。扩展目标是让命令在现在打开的终端中运行。

任何帮助将不胜感激,并很高兴在需要的地方澄清。谢谢!

标签: sshansibleubuntu-18.04gnome-terminal

解决方案


我决定走不同的方向,但想发表我学到的东西。

要从 Ansible 执行将在 Ubuntu 18.04(远程)机器上打开终端窗口的命令,需要以下命令:

- name: Start terminal on remote machine
  shell:
  args:
    cmd: DISPLAY=:0 nohup gnome-terminal </dev/null >/dev/null 2>&1 &
    executable: /bin/bash

注意</dev/null >/dev/null 2>&1 &. 这对于 Ansible 能够在允许终端在远程计算机上保持打开状态的同时拒绝进程是必要的。

在理论上,我还没有证明这一点,但在终端内运行命令需要额外的 gnome-terminal 参数-e

-e, --command=STRING
             Execute the argument to this option inside the terminal.

例子

- name: Start terminal on remote machine
  shell:
  args:
    cmd: DISPLAY=:0 nohup gnome-terminal -e "bash -c 'whoami'" </dev/null >/dev/null 2>&1 &
    executable: /bin/bash

推荐阅读