【问题标题】:Ansible run recursive script or moduleAnsible 运行递归脚本或模块
【发布时间】:2022-11-30 23:40:51
【问题描述】:

在 Ansible 中,如果 python 脚本包含同一脚本中的代码,我可以运行它。 但是,如果我尝试使用

name: Restarting service on different nodes
  hosts: nodes
  connection: ssh
  tasks:
    - name: Restarting tomcat service
      script: main.py 1
      args:
        executable: python3

而 main.py 有 导入重启_tomcat (restart_tomcat.py 与 main.py 位于同一文件夹中) 它无法导入此模块,尽管存在于同一目录中。

如何让它理解 main.py 的其他支持文件存在于同一目录中。 注意:它失败了,当它试图在远程服务器上执行它时

【问题讨论】:

    标签: python jenkins ansible


    【解决方案1】:

    我认为你应该写一个自定义模块;请注意,当您运行任何脚本时,ansible 会将其副本创建到一个临时位置。所以你在导入中提供的任何相对路径都会被弄乱。您可以使用-vvv 运行剧本任务来确认这一点。

    这是设置自定义模块的示例(高级):

     tree 
    .
    ├── your_playbook.yml
    ├── library
    │   └── your_custom_module.py # write your code logic here         
    └── module_utils
        └── restart_tomcat.py     #this file contains common classes/functions
    

    在你的模块文件(your_custom_module.py)中,你可以这样导入:

    #!/usr/bin/python3
    from __future__ import (absolute_import, division, print_function)
    __metaclass__ = type
    from ansible.module_utils.basic import AnsibleModule 
    from ansible.module_utils.restart_tomcat.py import *  #this line will import the classes or functions present in the other file to the custom module
    

    您可以找到更多详细信息 here 和示例 here

    【讨论】:

      猜你喜欢
      • 2020-01-24
      • 1970-01-01
      • 1970-01-01
      • 2018-04-21
      • 1970-01-01
      • 2018-01-18
      • 2016-05-10
      • 2018-11-19
      • 2021-08-07
      相关资源
      最近更新 更多