ansible playbook的脚本输出与常规脚本输出不同

问题描述 投票:0回答:2

剧本

---
- 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

我不确定为什么在执行playbook时会添加这些额外的单词。 “| [sudo]密码为bhreddy:”

请建议如何直接执行脚本时输出相同的输出。

ansible
2个回答
1
投票

你看到| [sudo] password for bhreddy:,因为你指示Ansible打印一个管道字符,然后是stderr任务的Execute the script,如下所示:

block: "{{ validate1.stdout }} | {{ validate1.stderr }}"

并且stderr包含来自sudo命令的密码提示,因为您以用户bhreddy执行脚本(这就是为什么它要求bhreddy的密码)。

但是,在shell示例中,您正在执行sudo作为root(如在发布的shell提示符root@bhreddy-VirtualBox中),这不需要输入密码。


两种情况下的输出完全相同,您只需要使用stdout:

block: "{{ validate1.stdout }}"

-1
投票

bhreddy的[sudo]密码:

来自脚本的stderr。

我建议你采用一种完全不同的方法,因为你不需要这个任务包装这个脚本来以root身份执行fdisk。

您用“替换脚本”和“执行脚本”替换

- name: list the partition
  command: /usr/sbin/fdisk
  become: true # to become root
  register: validate1
© www.soinside.com 2019 - 2024. All rights reserved.