将命令输出重定向到文件(现有命令)

ToB*_*ced 6 bash ansible

要将命令的stdout(在本例中为echo hi)写入文件,您可以执行以下操作:

echo hi > outfile
Run Code Online (Sandbox Code Playgroud)

我想要一个命令而不是重定向或管道,这样我就不需要调用shell.这最终是用于调用python的Ansible subprocess.POpen.

我在寻找:

stdout-to-file outfile echo hi
Run Code Online (Sandbox Code Playgroud)

tee 使stdout很容易复制到文件,但它接受stdin,而不是单独的命令.

是否有一个通用的,可移植的命令来执行此操作?当然,编写一个很容易,但这不是问题.最后,在Ansible,我想做:

command: to-file /opt/binary_data base64 -d {{ base64_secret }}
Run Code Online (Sandbox Code Playgroud)

代替:

shell: base64 -d {{ base64_secret }} > /opt/binary_data
Run Code Online (Sandbox Code Playgroud)

编辑:寻找可用于RHEL 7,Fedora 21的命令

小智 9

您实际需要的是一个Ansible模块,它有两个参数,

  1. 实际的命令
  2. 用于重定向上述命令输出的文件

在这种情况下,您可以使用shell模块而不是command模块,它允许这样的重定向.

例如

- shell: /usr/bin/your_command >> output.log
Run Code Online (Sandbox Code Playgroud)

您可以在此处查看源代码和示例文档.

这是最简单的.我相信你知道这一点.我只是为了读取这个线程的shell /命令模块的新手来解决这个问题.

如果您不喜欢这样做,您仍然可以编写一个包装器模块,它接受"文件名"作为参数并将运行为,

- custommodule: output.log /usr/bin/your_command
Run Code Online (Sandbox Code Playgroud)

您可能需要做的就是拆开仓库,查看现有模块,并相应地自定义您的模块.


jhu*_*tar 5

Not sure if that is what you want, but in Ansible - Save registered variable to file I have found what I have needed:

- name: "Gather lsof"
  command: lsof
  register: lsof_command
- name: "Save lsof log"
  local_command:
    copy content="{{ lsof_command.stdout }}" dest="/root/lsof.log"
Run Code Online (Sandbox Code Playgroud)

Or, in my specific case (might be useful for you as well) playbook was running on system A, but I needed the log from B and having it saved to localhost (because A system is hitting B and I want to log B's state):

- name: "Gather lsof on B"
  delegate_to: B
  command: lsof
  register: lsof_command
  run_once: true
- name: "Save lsof log"
  local_action:
    copy content="{{ lsof_command.stdout }}" dest="/root/lsof.log"
  run_once: true
Run Code Online (Sandbox Code Playgroud)

IMO run_once: true is required in my case, as I want the log gathered only once per playbook run (not say 10 times if playbook is running on 10 systems).

改进的空间是保存 stderr 或可能在“保存 lsof 日志”任务不为空时失败。