Passing client IP information to Jenkins Job

偶尔善良 提交于 2020-01-17 14:32:17

问题


In Jenkins, I want to pass the ip of the client that initiated the build to the Jenkins job so I can access that information inside a class that extends "Builder" or as an environment variable, or anything that works.

So for example, in the console log of every build, I can print something like: "Job started by user1 from ip: 10.101.101.1"

I know I can get an audit trial by using the "Audit Trial" plugin for Jenkins, but I would like to print that information to the build console so it'll be more straight forward.

Thanks in advance.

Edit: I want the ip of the user/client that started the job/build, which is not necessarily the ip of the jenkins slave the job is running on.


回答1:


You can use the EnvInject plugin and use the "Prepare an environment for the run" option.

In the "Evaluated Groovy script" section, copy this code:

return [IP_ADDRESS: InetAddress.localHost.canonicalHostName]

Then, you use the $IP_ADDRESS in your build step section.

echo $IP_ADDRESS

Build log:

[EnvInject] - Loading node environment variables.
[EnvInject] - Preparing an environment for the build.
[EnvInject] - Keeping Jenkins system variables.
[EnvInject] - Keeping Jenkins build variables.
[EnvInject] - Evaluation the following Groovy script content: 
return [IP_ADDRESS: InetAddress.localHost.canonicalHostName]

[EnvInject] - Injecting contributions.
Building on master in workspace /var/lib/jenkins/jobs/Test Groovy IP address/workspace
[workspace] $ /bin/sh -xe /tmp/hudson6447343457570437614.sh
+ echo 172.16.203.72
172.16.203.72
Notifying upstream projects of job completion
Finished: SUCCESS



回答2:


Jenkins not able to pass the client IP to a variable at the moment , the Client IP you saw at the output log is remote cause message.

I would say it is indeed useful to get remote IP in a job to enable some callback functions . Alternatively you can pass the IP as parameter when make the remote call

  1. echo $ipaddr in your shell script of jenkins job

  2. Enable the string parameters in jenkins job https://wiki.jenkins-ci.org/display/JENKINS/Parameterized+Build

  3. Make the call

    curl -k -u user:apitoken -X POST https://jenkins.local/job/yourjob/build \ --data token=jobtoken \
    --data-urlencode json='{"parameter": [{"name":"ipaddr", "value":"x.x.x.x"}]}'



来源:https://stackoverflow.com/questions/29140130/passing-client-ip-information-to-jenkins-job

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!