【Jenkins】通过jenkinsapi创建slave

因手动配置slave不够简单快捷,故希望直接通过python脚本创建slave。

使用模块

使用第三方模块jenkinsapi调用Jenkins rest接口:

from jenkinsapi.jenkins import Jenkins

具体介绍与实例可查看:https://pypi.org/project/jenkinsapi/

创建Jenkins对象

设置Jenkins地址,使用有足够权限的账号创建Jenkins对象。

jenkins_url = "http://xx.xx.xx.x/" # Jenkins地址
username = "XXX_XX" # Jenkins用户名
password = "xxxx" # Jenkins密码

# 创建Jenkins对象
jenkins = Jenkins(jenkins_url,
                  requester=Requester(username, password,
                                      baseurl=jenkins_url, ssl_verify=False))

创建节点

因是为了创建节点用于Android monkey测试,节点预期为Windows系统,故创建的是通过jnlp启动的节点。

# 远程工作目录
workspace = "C:\ProgramData\monkeyTest"
# 获取计算机名&用户名用于命名slave
PC_name = os.popen('hostname').read().strip()
user_name = getpass.getuser().strip()

# 创建 JNLP(Java Webstart) slave
def creatSlave ():
    #创建slave远程工作目录
    if os.path.exists(workspace):
        print("workspace目录已存在")
    else:
        os.mkdir(workspace)
        print("已创建workspace:"+workspace)
    #slave配置
    node_dict = {
        'num_executors': 1,                            # Number of executors
        'node_description': "monkey slave of "+PC_name,# Just a user friendly text
        'remote_fs': workspace,                        # Remote workspace location
        'labels': "monkey test node",                  # Space separated labels string
        'exclusive': True                              # Only run jobs assigned to it
    }
    new_slave = jenkins.nodes.create_node(user_name +"_"+ PC_name, node_dict)
    print("已创建节点"+new_slave.name)
    return new_slave

直接调用createSlave(),即可创建待链接Jenkins节点

猜你喜欢

转载自www.cnblogs.com/6970-9192/p/11273945.html