示例#1
0
    def post(self, request, *args, **kwargs):
        data = request.data

        # 验证
        """
        hosts []
        hosts中的ip 必须要在/etc/ansible/hosts文件中注册过才行,否则忽略.
        """
        if not (isinstance(data['hosts'], list) and len(data['hosts']) < 100):
            # 安全风险考虑
            # TODO: 100 to config
            return json_api_response(code=-1,
                                     data=None,
                                     message="一次任务要执行的主机数量不能大于100台.")

        script_name = data["script_name"]
        if script_name.endswith("yaml"):
            # exec script
            task_data = {
                "playbook":
                File.get_join_path(settings.ANSIBLE_SCRIPT_PATH,
                                   data["script_name"]),
                "extra_vars": {
                    "host_list": data['hosts']
                },
                "forks":
                data.get("forks", 5),
            }
            result = playbook_task.delay(**task_data)
        else:
            # exec playbook
            task_data = {
                "hosts":
                data['hosts'],
                "forks":
                data.get("forks", 5),
                "module":
                "script",
                'args':
                File.get_join_path(settings.ANSIBLE_SCRIPT_PATH,
                                   data["script_name"]),
            }
            result = runner_task.delay(**task_data)

        return json_api_response(code=0, data=result.id, message=None)
示例#2
0
 def read_file(self, filename):
     """ 读文件内容 """
     file_path = File.get_join_path(settings.ANSIBLE_SCRIPT_PATH, filename)
     return File.read_file(file_path)