如何获取Azure DevOps当前运行构建的进程ID以配置CodeQL间接构建追踪
如何获取Azure DevOps当前运行构建的进程ID以配置CodeQL间接构建追踪
我刚好碰到过类似的需求,下面给你几个简单可行的方案,帮你搞定Windows代理上CodeQL间接构建追踪的进程配置问题:
方案一:直接使用代理进程名称替代PID(最简单)
其实CodeQL的--trace-process-level参数不仅支持进程ID,还支持进程名称,这在Azure DevOps场景下更省心,不用特意获取PID。
你可以修改Python脚本里的Windows分支逻辑,直接指定代理的进程名称:
if 'windows' in agent_os.lower(): print('Windows Agent detected. Setting up tracing for Agent process.', flush=True) # 新版Azure DevOps代理进程名称是Agent.Listener.exe,旧版可能是VstsAgent.exe,根据你的环境调整 codeql_setup_command.append('--trace-process-level Agent.Listener.exe')
这样CodeQL会自动追踪该代理进程下的所有子构建进程,完全满足编译追踪的需求,还省去了获取PID的麻烦。
方案二:在YAML中提前获取进程ID并传入Python脚本
如果你确实需要用PID,也可以在YAML步骤里先获取当前构建任务的进程ID,再作为参数传给你的Python脚本:
- 在YAML中添加一个PowerShell步骤获取PID并设置为变量:
- powershell: | # 获取当前PowerShell进程的PID(它是Azure DevOps代理进程的子进程,CodeQL追踪它就能覆盖后续的编译任务) $buildPID = $PID # 将PID设置为流水线变量,供后续步骤使用 Write-Host "##vso[task.setvariable variable=BuildProcessPID]$buildPID" displayName: 'Capture Build Process PID'
- 修改PythonScript任务的arguments,新增
--build-pid $(BuildProcessPID):
arguments: '--github-token ${{ parameters.githubToken }} --build-type ${{ parameters.buildType }} --repository-name $(Build.Repository.Name) --repository-path $(Build.Repository.LocalPath) --agent-os $(agent.os) --codeql-db ${{ parameters.codeql_db }} --build-pid $(BuildProcessPID)'
- 在Python脚本中接收这个
--build-pid参数,然后传给CodeQL命令:
# 先在参数解析部分添加build_pid的接收(比如用argparse) # 然后修改Windows分支: codeql_setup_command.append(f'--trace-process-level {build_pid}')
方案三:在Python脚本内部获取父进程ID
如果不想修改YAML,也可以在Python脚本里直接获取当前脚本进程的父进程ID(也就是Azure DevOps任务执行的进程ID):
import os # ... 其他代码 ... if 'windows' in agent_os.lower(): print('Windows Agent detected. Using parent process ID for tracing.', flush=True) # 获取当前Python进程的父进程ID parent_pid = os.getppid() codeql_setup_command.append(f'--trace-process-level {parent_pid}')
这个方式无需额外YAML步骤,直接在Python内部处理,适合不想改动流水线结构的场景。
备注:内容来源于stack exchange,提问作者Ben
相关产品推荐
相关产品推荐

