ansible - ansible playbook 的脚本输出与常规脚本输出不同
问题描述
剧本
---
- name: Transfer and execute a script.
hosts: all
tasks:
- name: Transfer the script
copy: src=test1.sh dest=/home/bhreddy mode=0777
- name: Execute the script
command: sh /home/bhreddy/test1.sh
register: validate1
- name: run cmd
shell: echo "{{ inventory_hostname }}"
register: validate
- name: Write results to logfile
blockinfile:
create: yes
path: "/var/log/ansible/log"
insertafter: BOF
block: "{{ validate.stdout }} | {{ validate.stderr }}"
block: "{{ validate1.stdout }} | {{ validate1.stderr }}"
marker: "# {{ inventory_hostname }} {mark}"
delegate_to: localhost
脚本
root@bhreddy-VirtualBox:/home/bhreddy# cat test1.sh
#!/bin/bash
pass="password"
echo $pass | sudo -S su -c "fdisk -l"
如果我运行上面的剧本,输出如下:
root@bhreddy-VirtualBox:~# cat /var/log/ansible/log
# 192.168.56.102 BEGIN
Disk /dev/sda: 10 GiB, 10737418240 bytes, 20971520 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x37eaf900
Device Boot Start End Sectors Size Id Type
/dev/sda1 * 2048 20969471 20967424 10G 83 Linux | [sudo] password for bhreddy:
# 192.168.56.102 ENDroot@bhreddy-VirtualBox:~#
如果我直接运行我的 shell 脚本,输出如下所示:
root@bhreddy-VirtualBox:/home/bhreddy# ./test1.sh
Disk /dev/sda: 10 GiB, 10737418240 bytes, 20971520 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x37eaf900
Device Boot Start End Sectors Size Id Type
/dev/sda1 * 2048 20969471 20967424 10G 83 Linux
我不确定为什么在执行剧本时会添加这些额外的单词。"| [sudo] bhreddy 的密码:"
请建议如何获得与我直接执行脚本时相同的输出。
解决方案
您看到了,因为您指示 Ansible在以下行中打印一个竖线字符,后跟任务的| [sudo] password for bhreddy:
:stderr
Execute the script
block: "{{ validate1.stdout }} | {{ validate1.stderr }}"
并且 stderr 包含来自sudo
命令的密码提示,因为您以用户身份执行脚本bhreddy
(这就是它要求输入bhreddy
密码的原因)。
但是,在您的 shell 示例中,您执行sudo
的是root
(如在发布的 shell prompt 中root@bhreddy-VirtualBox
),这不需要输入密码。
两种情况下的输出完全相同,您只需使用标准输出即可:
block: "{{ validate1.stdout }}"
推荐阅读
- oracle-apex - 如何使用自定义用户访问控制?
- redirect - 当输入带有表情符号的 URL 时,Python 请求模块崩溃。为什么?
- python - 如何在 matplotlib 中设置两个时间格式化程序?
- javascript - 在函数中初始化 nodejs 全局变量并使其等同于在外部调用它
- c# - 从桌面获取选定的文件
- wordpress - Azure Kubernetes 服务 (AKS) 上的 Wordpress 非常慢
- python - 有没有办法从屏幕上移除乌龟?
- methods - 在子组件中使用方法和计算属性
- rest - 有关 HERE api 响应的文档
- c# - 在 C# 中使用 google OAuth2 后如何获取电子邮件?