Ansible playbook 上传和执行 python 脚本

nit*_*ins 8 ansible

我的剧本如下:

- hosts : mygroup
  user : user
  sudo : yes
  tasks :
  - name : Copy script
    copy : 'src=/home/user/Scripts/logchecker.py dest=/opt/root2/logchecker.py owner=root group=root mode=755'
  - name : Execute script
    command : '/usr/bin/python /opt/root2/logchecker.py'
Run Code Online (Sandbox Code Playgroud)

文件上传工作正常,但执行失败。即使我能够直接在服务器上执行脚本而没有任何问题。我做错了什么吗?

How*_*ord 6

我使用了一个类似的剧本,它按预期工作:

# playbook.yml
---
- hosts: ${target}
  sudo: yes

  tasks:
  - name: Copy file
    copy: src=../files/test.py dest=/opt/test.py owner=howardsandford group=admin mode=755

  - name: Execute script
    command: /opt/test.py
Run Code Online (Sandbox Code Playgroud)

和 test.py:

#!/usr/bin/python

# write to a file
f = open('/tmp/test_from_python','w')
f.write('hi there\n')
Run Code Online (Sandbox Code Playgroud)

运行剧本:

ansible-playbook playbook.yml --extra-vars "target=the_host_to_run_script_on"
Run Code Online (Sandbox Code Playgroud)

节目:

PLAY [the_host_to_run_script_on] ***************************************************************

GATHERING FACTS ***************************************************************
ok: [the_host_to_run_script_on]

TASK: [Copy file] *************************************************************
changed: [the_host_to_run_script_on]

TASK: [Execute script] ********************************************************
changed: [the_host_to_run_script_on]

PLAY RECAP ********************************************************************
the_host_to_run_script_on  : ok=3    changed=2    unreachable=0    failed=0
Run Code Online (Sandbox Code Playgroud)

在远程主机上:

$ cat /tmp/test_from_python
hi there
Run Code Online (Sandbox Code Playgroud)

我们的设置之间有几个区别:

  • 我在复制和命令参数周围没有单引号
  • shebang 设置 python 解释器,而不是从命令行指定 /usr/bin/python
  • 我将脚本的所有者设置为我自己的用户名和 sudoers 中的主要组,而不是 root

希望这可以为您指明可能存在差异的正确方向。