第二天,ansible源码学习(代码片段)

author author     2022-10-29     527

关键词:

按照我的理解,源码学习肯定是一边看代码,一边执行程序验证。执行的命令是:ansible sz003 -a "ls -l"

下面是ansible.py源码,学习分析以注释的形式出现

########################################################
from __future__ import (absolute_import, division, print_function)

# 表示基于type创建类,可以忽略
__metaclass__ = type

# __requires__ 要求按照的模块,可能是因为我没有使用ansible 提供的开发环境脚本的原因,要把这个注释掉才行
#__requires__ = [‘ansible‘]
try:
    import pkg_resources
except Exception:
    # Use pkg_resources to find the correct versions of libraries and set
    # sys.path appropriately when there are multiversion installs.  But we
    # have code that better expresses the errors in the places where the code
    # is actually used (the deps are optional for many code paths) so we don‘t
    # want to fail here.
    pass

import os
import shutil
import sys
import traceback

from ansible.errors import AnsibleError, AnsibleOptionsError, AnsibleParserError
from ansible.module_utils._text import to_text

# 用来显示信息
class LastResort(object):
    # OUTPUT OF LAST RESORT
    def display(self, msg, log_only=None):
        print(msg, file=sys.stderr)

    def error(self, msg, wrap_text=None):
        print(msg, file=sys.stderr)

if __name__ == ‘__main__‘:
    #
    # 从这里开始执行
    #
    display = LastResort()

    try:  # bad ANSIBLE_CONFIG or config options can force ugly stacktrace
        import ansible.constants as C
        from ansible.utils.display import Display
    except AnsibleOptionsError as e:
        display.error(to_text(e), wrap_text=False)
        sys.exit(5)

    #
    # cli 是用来存储ansible 执行命令的对象
    #
    cli = None

    #
    # 获取执行的文件名,在下面的代码中,根据文件名判断是实例adhoc 对象还是 playbook 对象
    # ansible-playbook 这部分代码是类似
    #
    me = os.path.basename(sys.argv[0])
    print("me:"+me)

    try:
        display = Display()
        display.debug("starting run")

        sub = None
        target = me.split(‘-‘)
        if target[-1][0].isdigit():
            # Remove any version or python version info as downstreams
            # sometimes add that
            target = target[:-1]

        if len(target) > 1:
            sub = target[1]
            myclass = "%sCLI" % sub.capitalize()
        elif target[0] == ‘ansible‘:
            sub = ‘adhoc‘
            myclass = ‘AdHocCLI‘
        else:
            raise AnsibleError("Unknown Ansible alias: %s" % me)

        try:
            #
            # 这里是获取 adhoc 还是 playbook
            #
            mycli = getattr(__import__("ansible.cli.%s" % sub, fromlist=[myclass]), myclass)
        except ImportError as e:
            # ImportError members have changed in py3
            if ‘msg‘ in dir(e):
                msg = e.msg
            else:
                msg = e.message
            if msg.endswith(‘ %s‘ % sub):
                raise AnsibleError("Ansible sub-program not implemented: %s" % me)
            else:
                raise

        try:
            #
            # 这里是处理参数,也就是执行命令时输入的 sz003 -a "ls -l"
            #
            args = [to_text(a, errors=‘surrogate_or_strict‘) for a in sys.argv]
        except UnicodeError:
            display.error(‘Command line args are not in utf-8, unable to continue.  Ansible currently only understands utf-8‘)
            display.display(u"The full traceback was:\n\n%s" % to_text(traceback.format_exc()))
            exit_code = 6
        else:
            #
            # 这里就是具体实例化了
            #
            cli = mycli(args)

            #
            # 整理参数
            #
            cli.parse()

            #
            # 执行命令
            #
            exit_code = cli.run()

            #
            # 下面大多数是处理异常代码,最后面有清理临时目录操作
            #

    except AnsibleOptionsError as e:
        cli.parser.print_help()
        display.error(to_text(e), wrap_text=False)
        exit_code = 5
    except AnsibleParserError as e:
        display.error(to_text(e), wrap_text=False)
        exit_code = 4
# TQM takes care of these, but leaving comment to reserve the exit codes
#    except AnsibleHostUnreachable as e:
#        display.error(str(e))
#        exit_code = 3
#    except AnsibleHostFailed as e:
#        display.error(str(e))
#        exit_code = 2
    except AnsibleError as e:
        display.error(to_text(e), wrap_text=False)
        exit_code = 1
    except KeyboardInterrupt:
        display.error("User interrupted execution")
        exit_code = 99
    except Exception as e:
        have_cli_options = cli is not None and cli.options is not None
        display.error("Unexpected Exception, this is probably a bug: %s" % to_text(e), wrap_text=False)
        if not have_cli_options or have_cli_options and cli.options.verbosity > 2:
            log_only = False
            if hasattr(e, ‘orig_exc‘):
                display.vvv(‘\nexception type: %s‘ % to_text(type(e.orig_exc)))
                why = to_text(e.orig_exc)
                if to_text(e) != why:
                    display.vvv(‘\noriginal msg: %s‘ % why)
        else:
            display.display("to see the full traceback, use -vvv")
            log_only = True
        display.display(u"the full traceback was:\n\n%s" % to_text(traceback.format_exc()), log_only=log_only)
        exit_code = 250
    finally:
        #
        # 最后如注释说的,清理临时目录
        #
        # Remove ansible tempdir
        shutil.rmtree(C.DEFAULT_LOCAL_TMP, True)

    sys.exit(exit_code)

明天就转到学习ansible具体执行命令的流程了,也就是下面代码段
cli = mycli(args)
cli.parse()
exit_code = cli.run()

vue学习第二天------临时笔记(代码片段)

学习链接:vue.js官方文档:  https://cn.vuejs.org/v2/guide/index.htmlvue.jsAPI:  https://cn.vuejs.org/v2/api/#选项-数据基础案例学习:  https://www.mingtern.com/lesson/861068/ 1.使用JavaScript表达式进行运算时,只能使用单个表达式或者链式调... 查看详情

开始学习python的第二天(代码片段)

一、练习题1.使用while循环输入1234568910#第一种方法count=0whilecount<10:count+=1#count=count+1ifcount==7:print(‘‘)else:print(count)#第二种count=0whilecount<10:count+=1#count=count+1ifcount==7:continueprint(count)2. 查看详情

springboot学习:第二天(代码片段)

三、日志1、日志框架小张;开发一个大型系统;  1、System.out.println("");前期将关键数据打印在控制台;去掉?写在一个文件?  2、后来框架来记录系统的一些运行时信息;日志框架;zhanglogging.jar;  3、再后来加高大上... 查看详情

python学习第二天(下)(代码片段)

继续上次的笔记 ####判断一个元素是否在列表中9innameprint(9inname)会返回一个True或False的结果 if9inname:#判断一个元素是否在列表中print("9isinname")####判断一个元素出现的次数count()方法 name=["Alex","Jack","Rain",9,4,3,5,634,34,89,"Eri... 查看详情

莫烦theano学习自修第二天激励函数(代码片段)

1.代码如下:#!/usr/bin/envpython#!_*_coding:UTF-8_*_importnumpyasnpimporttheano.tensorasTimporttheanox=T.dmatrix(‘x‘)#定义一个激励函数s=1/(1+T.exp(-x))logistic=theano.function([x],s)printlogistic([[0,1],[-2,-3]])# 查看详情

python学习第二天(上)(代码片段)

##课前思想###GENTLEMENCODE1* 着装得体* 每天洗澡* 适当用香水* 女士优先* 不随地吐痰、不乱扔垃圾、不在人群众抽烟* 不大声喧哗* 不插队、碰到别人要说抱歉* 不在地铁上吃东西* 尊重别人的职业... 查看详情

docker的学习第二天(代码片段)

Docker架构图 镜像:image,类似于模板的意思,通过这个模板创建容器服务,如tomcat镜像,---》run--->tomcat1容器,提供给服务器  通过这个镜像可以创建多个容器,最终服务运行或者项目就是在容器中容器:container:Docker... 查看详情

c语言学习第二天(代码片段)

常量字符串常量字符例如:\'f\',\'i\',\'z\',\'a\'编译器为每个字符分配空间。\'f\'\'i\'\'z\'\'a\'字符串例如:"hello"编译器为字符串里的每个字符分配空间以\'\\0\'结束。\'h\'\'e\'\'l\'\'l\'\'o\'\'\\0\'基本类型整数型:shortint,int,longint,longlongin... 查看详情

struts学习之路-第二天(action与servletapi)(代码片段)

Struts作为一款Web框架自然少不了与页面的交互,开发过程中我们最常用的request、application、session等struts都为我们进行了一定的封装与处理一、通过ActionContext获取方法说明voidput(Stringkey,Objectvalue)模拟HttpServletRequest中的setAttribute(... 查看详情

第二天学习进度--文本情感分类(代码片段)

昨天学习了简单的文本处理,之后在课后的练习中实现了包括了对tf-idf的处理和基于朴素贝叶斯简单的文本分类基于tf-idf的数据集在出现多个关键词的时候一般能够相对准确对文本进行分类,但是对于相对具有深层含义的内容,... 查看详情

从零开始学习c语言(第二天)(代码片段)

 今天我学习了C语言的常量分为:字面常量、const修饰的常量、#define定义的标识符常量、枚举常量。字符串、strlen、while字面常量:指的是输入程序中的值。表示数字如:3、5、100、3.14.....#include<stdio.h>intmain() inta&... 查看详情

学习打卡第二天(代码片段)

1importjava.io.IOException;23publicclassIOTest45publicstaticvoidmain(String[]args)6byte[]buffer=newbyte[1024];7try89intlen=System.in.read(buffer);10Strings=newString(buffer,0,len);11System.out.println("接收到了:"+len+"个字节");12System.out.println(s);13System.out.println("字符串长度为... 查看详情

leetcode剑指offer学习计划第二天题目(代码片段)

剑指Offer06.从尾到头打印链表输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。示例1:输入:head=[1,3,2]输出:[2,3,1]限制:0<=链表长度<=10000所给代码如下/**1.Defini... 查看详情

自动化运维-ansible(第二部)(代码片段)

Ansible命令应用基础之前的一篇文章讲到了Ansible的安装和作用,有兴趣的可以看看Ansible介绍与安装。学习ansible就是重新学习一次命令和语法。Ansible可以使用命令行进行自动化管理,基本语法如下:ansible<host-patterm>[-mmodule_nam... 查看详情

python3-基础语法篇(第二天)(代码片段)

本篇博文为Python3零基础学习第二天,本篇博文可以学习到如下知识:1.print输出功能2.input输入功能(包含类型转换)3.字符串的格式化4.range功能5.随机模块random6.流程控制语句(顺序语句,分支语句,循环语句–(while循环,break和continue关键... 查看详情

mycat学习第二天之性能监控,读写分离,集群搭建(代码片段)

MyCat1.MyCat性能监控1.1MyCat-web简介1.2MyCat-web下载安装配置1.3MyCat性能监控1.4Mycat-web之MySQL性能监控指标1.5Mycat-web之SQL监控2.MyCat读写分离搭建2.1MySQL主从复制原理2.2MySQL一主一从搭建2.3MyCat一主一从读写分离2.4MySQL双主双从搭建2.5MyCat双... 查看详情

程序老鸟c#学习:3天学会全部基础--第二天(代码片段)

👉关于作者众所周知,人生是一个漫长的流程,不断克服困难,不断反思前进的过程。在这个过程中会产生很多对于人生的质疑和思考,于是我决定将自己的思考,经验和故事全部分享出来,以此寻找... 查看详情

三天爆肝快速入门机器学习:knn算法朴素贝叶斯算法决策树第二天(代码片段)

三天爆肝快速入门机器学习【第二天】转换器与预估器KNN算法决策树随机森林个人总结转换器与预估器必须理解的转换器与估计器一转化器回想一下之前做的特征工程的步骤?实例化(实例化的是一个转换器类transformer)... 查看详情