question
stringlengths 11
28.2k
| answer
stringlengths 26
27.7k
| tag
stringclasses 130
values | question_id
int64 935
78.4M
| score
int64 10
5.49k
|
---|---|---|---|---|
I have deleted jenkins all directories from different folders. But still when I access URL it is showing me jenkins login.
I want to uninstall jenkins completely. Have tried many commands from internet but still jenkins is there on server.
I have only command line access via putty so I tries whatever is possible via command to remove jenkins.
| If your jenkins is running as service instead of process you should stop it first using
sudo service jenkins stop
After stopping it you can follow the normal flow of removing it using commands respective to your linux flavour
For centos it will be
sudo yum remove jenkins
For ubuntu it will
sudo apt-get remove --purge jenkins
I hope this will solve your issue.
| Jenkins | 38,604,715 | 67 |
I have imported the jenkins jobs from existing jenkins server from another machine. But the problem is, it has the JDK referenced as per the old machines and I want to change it to use the JDK configured in my new jenkins. But I am unable to find any way of doing this. So, please if you have come across this situation and found a way then please help me too.
Thanks.
| There is a JDK dropdown in "job name" -> Configure in Jenkins web ui. It will list all JDKs available in Jenkins configuration.
As per @Derek comment below, n newer versions, you can find it in Manage Jenkins -> Global Tool Configuration -> JDK.
Note that you need the "Overall/Administer" permission to manage Jenkins.
| Jenkins | 28,810,477 | 67 |
What is the difference between Maven and Jenkins?
Both support automated builds and automated execution of JUnits.
If so, are they complimentary, or mutually exclusive? When should onebe used over the other?
| Maven is building tool/environment. Jenkins is a CI (continuous integration) tool.
Maven is more like a replacement for Ant.
It assists building of the project through plugins e.g build and version control, JUnit tests, etc...
It manages dependencies of your project.
you define how a project should be built(plugins), and what libraries are needed (dependencies) in a pom.xml file.
Jenkins as a smart job scheduler, can not assists you with tasks like version control or JUnit test, however it can indirectly assists you with all this, by making calls to the pom.xml file in your project. And Jenkins gives you the power to decide when to call the pom.xml file, based on what condition to call, and what you want to do with the outcome. and Jenkins can listen to different events, e.g svn commit, current time is midnight etc..
This is a powerful idea. For example, you can ask Jenkins to trigger a build or run through all JUnit tests whenever a new code is committed and then, if the unit tests are passed, deploy on a target machine. or schedule heavy tasks at midnight e.g unit tests.This is the basic idea of auto deployment or AKA continuous integration. CI for short if you like.
| Jenkins | 10,834,262 | 67 |
When I run the below Jenkins pipeline script:
def some_var = "some value"
def pr() {
def another_var = "another " + some_var
echo "${another_var}"
}
pipeline {
agent any
stages {
stage ("Run") {
steps {
pr()
}
}
}
}
I get this error:
groovy.lang.MissingPropertyException: No such property: some_var for class: groovy.lang.Binding
If the def is removed from some_var, it works fine. Could someone explain the scoping rules that cause this behavior?
| TL;DR
variables defined with def in the main script body cannot be accessed from other methods.
variables defined without def can be accessed directly by any method even from different scripts. It's a bad practice.
variables defined with def and @Field annotation can be accessed directly from methods defined in the same script.
Explanation
When groovy compiles that script it actually moves everything to a class that roughly looks something like this
class Script1 {
def pr() {
def another_var = "another " + some_var
echo "${another_var}"
}
def run() {
def some_var = "some value"
pipeline {
agent any
stages {
stage ("Run") {
steps {
pr()
}
}
}
}
}
}
You can see that some_var is clearly out of scope for pr() becuse it's a local variable in a different method.
When you define a variable without def you actually put that variable into a Binding of the script (so-called binding variables). So when groovy executes pr() method firstly it tries to find a local variable with a name some_var and if it doesn't exist it then tries to find that variable in a Binding (which exists because you defined it without def).
Binding variables are considered bad practice because if you load multiple scripts (load step) binding variables will be accessible in all those scripts because Jenkins shares the same Binding for all scripts. A much better alternative is to use @Field annotation. This way you can make a variable accessible in all methods inside one script without exposing it to other scripts.
import groovy.transform.Field
@Field
def some_var = "some value"
def pr() {
def another_var = "another " + some_var
echo "${another_var}"
}
//your pipeline
When groovy compiles this script into a class it will look something like this
class Script1 {
def some_var = "some value"
def pr() {
def another_var = "another " + some_var
echo "${another_var}"
}
def run() {
//your pipeline
}
}
| Jenkins | 50,571,316 | 66 |
Please note: the question is based on the old, now called "scripted" pipeline format. When using "declarative pipelines", parallel blocks can be nested inside of stage blocks (see Parallel stages with Declarative Pipeline 1.2).
I'm wondering how parallel steps are supposed to work with Jenkins workflow/pipeline plugin, esp. how to mix them with build stages. I know about the general pattern:
parallel(firstTask: {
// Do some stuff
}, secondTask: {
// Do some other stuff in parallel
})
However, I'd like to run couple of stages in parallel (on the same node, which has multiple executors), so I tried to add stages like this:
stage 'A'
// Do some preparation stuff
parallel(firstTask: {
stage 'B1'
// Do some stuff
}, secondTask: {
stage 'B2'
// Do some other stuff in parallel
})
stage 'C'
// Finalizing stuff
This does not work as expected. The "do stuff" tasks are executed in parallel, but the parallel stages end immediately and do not incorporate the stuff they should contain. As a consequence, the Stage View does not show the correct result and also does not link the logs.
Can I build different stages in parallel, or is the "parallel" step only meant to be used within a single stage?
| You may not place the deprecated non-block-scoped stage (as in the original question) inside parallel.
As of JENKINS-26107, stage takes a block argument. You may put parallel inside stage or stage inside parallel or stage inside stage etc. However visualizations of the build are not guaranteed to support all nestings; in particular
The built-in Pipeline Steps (a “tree table” listing every step run by the build) shows arbitrary stage nesting.
The Pipeline Stage View plugin will currently only display a linear list of stages, in the order they started, regardless of nesting structure.
Blue Ocean will display top-level stages, plus parallel branches inside a top-level stage, but currently no more.
JENKINS-27394, if implemented, would display arbitrarily nested stages.
| Jenkins | 36,872,657 | 66 |
Is there any way a Jenkins build can be aware of the Maven version number of a project after processing the POM?
I've got some projects where versioning is controlled by Maven, and in a post-build job we'd like to create a Debian package and call some shell scripts. What I need is for the version number that Maven used to be available as a Jenkins environment variable so I can pass it to post-build actions.
To be clear, I'm not needing to know how to get Jenkins to pass a version number to Maven; instead I want Maven to pass a version number to Jenkins!
| You can use the ${POM_VERSION} variable, which was introduced with https://issues.jenkins-ci.org/browse/JENKINS-18272
| Jenkins | 9,893,503 | 66 |
How do I trigger another job from hudson as a pre-build step?
| There is a Parameterized Trigger Plugin, which enables "Trigger/call builds on other projects" in "Add build step" menu.
| Jenkins | 5,487,104 | 66 |
I want to run multiple stages inside a lock within a declarative Jenkins pipeline:
pipeline {
agent any
stages {
lock(resource: 'myResource') {
stage('Stage 1') {
steps {
echo "my first step"
}
}
stage('Stage 2') {
steps {
echo "my second step"
}
}
}
}
}
I get the following error:
Started by user anonymous
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 10: Expected a stage @ line 10, column 9.
lock(resource: 'myResource') {
^
WorkflowScript: 10: Stage does not have a name @ line 10, column 9.
lock(resource: 'myResource') {
^
WorkflowScript: 10: Nothing to execute within stage "null" @ line 10, column 9.
lock(resource: 'myResource') {
^
3 errors
at org.codehaus.groovy.control.ErrorCollector.failIfErrors(ErrorCollector.java:310)
at org.codehaus.groovy.control.CompilationUnit.applyToPrimaryClassNodes(CompilationUnit.java:1085)
at org.codehaus.groovy.control.CompilationUnit.doPhaseOperation(CompilationUnit.java:603)
at org.codehaus.groovy.control.CompilationUnit.processPhaseOperations(CompilationUnit.java:581)
at org.codehaus.groovy.control.CompilationUnit.compile(CompilationUnit.java:558)
at groovy.lang.GroovyClassLoader.doParseClass(GroovyClassLoader.java:298)
at groovy.lang.GroovyClassLoader.parseClass(GroovyClassLoader.java:268)
at groovy.lang.GroovyShell.parseClass(GroovyShell.java:688)
at groovy.lang.GroovyShell.parse(GroovyShell.java:700)
at org.jenkinsci.plugins.workflow.cps.CpsGroovyShell.reparse(CpsGroovyShell.java:116)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.parseScript(CpsFlowExecution.java:430)
at org.jenkinsci.plugins.workflow.cps.CpsFlowExecution.start(CpsFlowExecution.java:393)
at org.jenkinsci.plugins.workflow.job.WorkflowRun.run(WorkflowRun.java:257)
at hudson.model.ResourceController.execute(ResourceController.java:97)
at hudson.model.Executor.run(Executor.java:405)
Finished: FAILURE
What's the problem here? The documentation explicitly states:
lock can be also used to wrap multiple stages into a single
concurrency unit
| It should be noted that you can lock all stages in a pipeline by using the lock option:
pipeline {
agent any
options {
lock resource: 'shared_resource_lock'
}
stages {
stage('will_already_be_locked') {
steps {
echo "I am locked before I enter the stage!"
}
}
stage('will_also_be_locked') {
steps {
echo "I am still locked!"
}
}
}
}
| Jenkins | 44,098,993 | 65 |
I'm using declarative Jenkins pipelines to run some of my build pipelines and was wondering if it is possible to define multiple agent labels.
I have a number of build agents hooked up to my Jenkins and would like for this specific pipeline to be able to be built by various agents that have different labels (but not by ALL agents).
To be more concrete, let's say I have 2 agents with a label 'small', 4 with label 'medium' and 6 with label 'large'. Now I have a pipeline that is very resource-low and I want it to be executed on only a 'small'- or 'medium'-sized agent, but not on a large one as it may cause larger builds to wait in the queue for an unnecessarily long time.
All the examples I've seen so far only use one single label.
I tried something like this:
agent { label 'small, medium' }
But it failed.
I'm using version 2.5 of the Jenkins Pipeline Plugin.
| You can see the 'Pipeline-syntax' help within your Jenkins installation and see the sample step "node" reference.
You can use exprA||exprB:
node('small||medium') {
// some block
}
| Jenkins | 43,321,026 | 65 |
I am working with jenkins and I would like to run the maven goals when there is a change in the svn repository. I've attached a picture with my current configuration.
I know that checking the repository every 5 min is crazy. I would like to run it only when there is a new change, but I could not find the way. Anyway, it is not checking the repository. What am I doing wrong?
| I believe best practice these days is H/5 * * * *, which means every 5 minutes with a hashing factor to avoid all jobs starting at EXACTLY the same time.
| Jenkins | 10,121,098 | 65 |
I have a few plugins in my Jenkins installation which I no longer need. I've already disabled the plugins (and my build still work), and I'd like to remove the plugins completely. What is the right process for completely removing a Jenkins (Hudson) plugin?
| As mentioned by Jesse Glick in his answer, if you are using Jenkins 1.487 or higher, then there is a native way to uninstall plugins in the Jenkins UI. See JENKINS-3070 for details.
If you are using a version of Jenkins earlier than 1.487, then you can try manually uninstalling the plugin. As some people point out in the comments, this may not work on some platforms (in those cases, upgrade to at least 1.487 so that you can use the official uninstall feature).
To manually uninstall a plugin, stop Hudson/Jenkins, go to your HUDSON_HOME/plugins directory and remove both the .hpi file and the folder with the same name. So, if you were going to remove the CVS plugin, you would remove both the cvs.hpi file and the cvs directory.
After that, restart Hudson/Jenkins and the plugin won't be there anymore.
| Jenkins | 4,965,235 | 65 |
I'm trying to use the result of Ansible find module, which return list of files it find on a specific folder.
The problem is, when I iterate over the result, I do not have the file names, I only have their full paths (including the name).
Is there an easy way to use the find_result items below to provide the file_name in the second command as shown below?
- name: get files
find:
paths: /home/me
file_type: "file"
register: find_result
- name: Execute docker secret create
shell: docker secret create <file_name> {{ item.path }}
run_once: true
with_items: "{{ find_result.files }}"
| basename filter?
{{ item.path | basename }}
There are also dirname, realpath, relpath filters.
| Jenkins | 45,564,899 | 64 |
How can I run a job created in Jenkins every one minute ? Am I missing anything?
PS: I'm trying not to use: */1 * * * *
| Try * * * * * to run every minute.
Unfortunately H/1 * * * * does not work due to open defect.
Defect: https://issues.jenkins-ci.org/browse/JENKINS-22129
| Jenkins | 29,975,655 | 64 |
I installed jenkins on Centos 7 using the following:
sudo wget -O /etc/yum.repos.d/jenkins.repo http://pkg.jenkins.io/redhat-stable/jenkins.repo
sudo rpm --import http://pkg.jenkins.io/redhat-stable/jenkins.io.key
yum install jenkins
as described on the official documentation
However when I run:
service start jenkins
I get the following error message:
Starting jenkins (via systemctl): Job for jenkins.service failed because the control process exited with error code. See "systemctl status jenkins.service" and "journalctl -xe" for details.
[FAILED]
Running systemctl status jenkins.service gives me this:
● jenkins.service - LSB: Jenkins Continuous Integration Server
Loaded: loaded (/etc/rc.d/init.d/jenkins)
Active: failed (Result: exit-code) since Wed 2016-09-21 16:45:28 BST; 3min 59s ago
Docs: man:systemd-sysv-generator(8)
Process: 2818 ExecStart=/etc/rc.d/init.d/jenkins start (code=exited, status=1/FAILURE)
Sep 21 16:45:28 webstack.local.caplib jenkins[2818]: at com.sun.akuma.JavaVMArguments.of(JavaVMArguments...04)
Sep 21 16:45:28 webstack.local.caplib jenkins[2818]: at com.sun.akuma.JavaVMArguments.current(JavaVMArgu...92)
Sep 21 16:45:28 webstack.local.caplib jenkins[2818]: at com.sun.akuma.Daemon.daemonize(Daemon.java:106)
Sep 21 16:45:28 webstack.local.caplib jenkins[2818]: at com.sun.akuma.Daemon.all(Daemon.java:88)
Sep 21 16:45:28 webstack.local.caplib jenkins[2818]: ... 6 more
Sep 21 16:45:28 webstack.local.caplib systemd[1]: jenkins.service: control process exited, code=exited s...s=1
Sep 21 16:45:28 webstack.local.caplib systemd[1]: Failed to start LSB: Jenkins Continuous Integration Server.
Sep 21 16:45:28 webstack.local.caplib systemd[1]: Unit jenkins.service entered failed state.
Sep 21 16:45:28 webstack.local.caplib systemd[1]: jenkins.service failed.
Sep 21 16:45:28 webstack.local.caplib jenkins[2818]: [FAILED]
Hint: Some lines were ellipsized, use -l to show in full.
and running journalctl -xe gives me this:
Sep 21 16:45:28 webstack.local.caplib jenkins[2818]: at com.sun.akuma.JavaVMArguments.of(JavaVMArguments.java:
Sep 21 16:45:28 webstack.local.caplib jenkins[2818]: at com.sun.akuma.JavaVMArguments.current(JavaVMArguments.
Sep 21 16:45:28 webstack.local.caplib jenkins[2818]: at com.sun.akuma.Daemon.daemonize(Daemon.java:106)
Sep 21 16:45:28 webstack.local.caplib jenkins[2818]: at com.sun.akuma.Daemon.all(Daemon.java:88)
Sep 21 16:45:28 webstack.local.caplib jenkins[2818]: ... 6 more
Sep 21 16:45:28 webstack.local.caplib runuser[2819]: pam_unix(runuser:session): session closed for user jenkin
Sep 21 16:45:28 webstack.local.caplib systemd[1]: jenkins.service: control process exited, code=exited status=
Sep 21 16:45:28 webstack.local.caplib systemd[1]: Failed to start LSB: Jenkins Continuous Integration Server.
-- Subject: Unit jenkins.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit jenkins.service has failed.
--
-- The result is failed.
Sep 21 16:45:28 webstack.local.caplib systemd[1]: Unit jenkins.service entered failed state.
Sep 21 16:45:28 webstack.local.caplib systemd[1]: jenkins.service failed.
Sep 21 16:45:28 webstack.local.caplib jenkins[2818]: [FAILED]
Sep 21 16:45:28 webstack.local.caplib polkitd[1392]: Unregistered Authentication Agent for unix-process:2813:8
Sep 21 16:45:28 webstack.local.caplib dhclient[1390]: DHCPREQUEST on eno16777984 to 192.168.15.254 port 67 (xi
Sep 21 16:45:28 webstack.local.caplib dhclient[1390]: DHCPACK from 192.168.15.254 (xid=0x2ab6e6bc)
Sep 21 16:45:30 webstack.local.caplib dhclient[1390]: bound to 192.168.15.120 -- renewal in 865 seconds.
Sep 21 16:45:36 webstack.local.caplib systemd[1]: Starting Cleanup of Temporary Directories...
-- Subject: Unit systemd-tmpfiles-clean.service has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit systemd-tmpfiles-clean.service has begun starting up.
Sep 21 16:45:36 webstack.local.caplib systemd[1]: Started Cleanup of Temporary Directories.
-- Subject: Unit systemd-tmpfiles-clean.service has finished start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit systemd-tmpfiles-clean.service has finished starting up.
--
-- The start-up result is done.
Both of which is really unhelpful. How do I fix this issue?
| Similar problem on Ubuntu 16.04.
Setting up jenkins (2.72) ...
Job for jenkins.service failed because the control process exited with error code. See "systemctl status jenkins.service" and "journalctl -xe" for details.
invoke-rc.d: initscript jenkins, action "start" failed.
● jenkins.service - LSB: Start Jenkins at boot time
Loaded: loaded (/etc/init.d/jenkins; bad; vendor preset: enabled)
Active: failed (Result: exit-code) since Tue 2017-08-01 05:39:06 UTC; 7ms ago
Docs: man:systemd-sysv-generator(8)
Process: 3700 ExecStart=/etc/init.d/jenkins start (code=exited, status=1/FAILURE)
Aug 01 05:39:06 ip-0 systemd[1]: Starting LSB: Start Jenkins ....
Aug 01 05:39:06 ip-0 jenkins[3700]: ERROR: No Java executable ...
Aug 01 05:39:06 ip-0 jenkins[3700]: If you actually have java ...
Aug 01 05:39:06 ip-0 systemd[1]: jenkins.service: Control pro...1
Aug 01 05:39:06 ip-0 systemd[1]: Failed to start LSB: Start J....
Aug 01 05:39:06 ip-0 systemd[1]: jenkins.service: Unit entere....
Aug 01 05:39:06 ip-0 systemd[1]: jenkins.service: Failed with....
To fix the issue manually install Java Runtime Environment:
JDK version 9:
sudo apt install openjdk-9-jre
JDK version 8:
sudo apt install openjdk-8-jre
Open Jenkins configuration file:
sudo vi /etc/init.d/jenkins
Finally, append path to the new java executable (line 16):
PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/lib/jvm/java-8-openjdk-amd64/bin/
| Jenkins | 39,621,263 | 63 |
I installed the Promoted Build Plugin from Jenkins and now I'm facing some troubles to promote a build from an existing job. Here is the scenario:
There is an existing Nightly Build job that runs every night running all the tests and metrics needed;
There is an existing Deploy Build that accepts a parameter ${BUILD_NUMBER} and deploys the build that has the corresponding ${BUILD_NUMBER} from the Nightly Build
Say the [Nightly Build] ran and successfully built the artifact #39
Now I can just run the [Deploy Build] passing in #39 as a parameter
The artifacts from [Nightly Build] #39 are going to be deployed
So far so good. Now is the part where I want to add the Build Promotions...
Is there a way to promote the Nightly Build #39 (notice that it was already built before) from the Deploy Build? Or maybe even from somewhere else, quite frankly I`m kind of lost here :(
I don`t see them with a clear Upstream/Downstream relationship, because they don't have a: always runs this build and then the other during the execution - the [Deploy Build] is executed sometimes only and not always after the [Nightly Build].
| Update as of version 2.23 of Parameterized Trigger Plugin:
With version 2.23+ behavior changed (thanks AbhijeetKamble for pointing out). Any parameter that is being passed by Predefined Parameters section of calling (build) job has to exist in the called (deploy) job. Furthermore, the restrictions of called job's parameters apply, so if the called job's parameter is a choice, it has to have all possible values (from promotions) pre-populated. Or just use Text parameter type.
Solution
Yes, I have the exact same setup: a build job (based on SVN commits) and manually executed deploy job. When the user selects any build from the build job (including older builds), they can then go to Promotion Status link and execute various deploy promotions, for example Deploy to DEV, Deploy to QA, etc
Here is how to setup the promotion on build job:
You will need these plugins: Parameterized Trigger Plugin, Promoted Builds Plugin
You will also need to setup default Archive the Artifacts post-build action on this build job.
Check mark Promote builds when
Define Name "Deploy to DEV"
Under Criteria check mark Only when manually approved
Under Actions use Trigger/call builds on other projects
In Projects to build enter the name to your deploy job here
Check mark Block until the triggered projects finish their builds
Mark this build as failure if the triggered build is worse or equal to: FAILURE (adjust according to statuses of your deploy job)
Predefined parameters (Code A)
Code A:
Server=IP_of_my_dev_server`
Job=$PROMOTED_JOB_NAME`
BuildSelection=<SpecificBuildSelector><buildNumber>$PROMOTED_NUMBER</buildNumber></SpecificBuildSelector>
Above, in the Predefined parameters section, the name to the left of = are the parameters that are defined in your deploy job. And to the right of = are the values that will be assigned to those parameters when this promotion executes. Defines three parameters Server, Job and BuildSelection.
The parameter Server= is my own, as my deploy job can deploy to multiple servers. However if your deploy job is hardcoded to always deploy to a specific location, you won't need that.
The Job= parameter is required, but the name of the param depends on what you've setup in your deploy job (I will explain configuration there). The value $PROMOTED_JOB_NAME has to remain as is. This is an environment variable that the promotion process is aware of and refers back to the name of your build job (the one where promotion process is configured)
The BuildSelection= parameter is required. This whole line has to remain as is. The value passed is $PROMOTED_NUMBER, which once again the promotion is aware of. In your example, it would be #39.
The Block until the triggered projects finish their builds check mark will make the promotion process wait until the deploy job finished. If not, the promotion process will trigger the deployment job and quit with success. Waiting for the deploy job to finish has the benefit that if the deploy job fails, the promotion star will be marked with failure too.
(One little note here: the promotion star will appear successful while the deploy job is running. If there is a deploy failure, it will only change to failure after the deploy job finished. Logical... but can be a bit confusing if you look at the promotion star before the deployment completed)
Here is how to setup deploy job
You will need Copy Artifacts plugin
Under This build is parameterized
Configure a parameter of type Choice (or Text) with name Server (this name has to match with configuration in promotion's Predefined Parameters in previous section)
Choices: Enter list of possible server IPs that would be used by the promotion's Predefined Parameters in previous section (see update note below)
Configure a parameter of type Choice (or Text) with name Job (this name has to match with configuration in promotion's Predefined Parameters in previous section)
Choices: Enter the name of your build job as default. This is only needed if you trigger the deploy job manually. When the deploy job is triggered from promotion, the promotion will supply the value (the Job= from Predefined parameters that we configured). Also, if there is no value passed from promotion's Predefined parameters, the first choice value will be used. If you have a 1-to-1 relationship between the build and deploy jobs, you can omit the Job= parameter in promotion's configuration.
Update: since version 2.23 of Parameterized Trigger, the available choices in the deploy job configuration have to have all possible values coming from the promotion's predefined parameters. If you don't want that limit, use "Text" instead of "Choice"
Configure a parameter of type Build selector for Copy Artifact with name: BuildSelection
Default Selector: Latest successful build
Under Build steps
Configure Copy artifacts from another project
In Project name enter ${Job}
At Which build choose Specified by a build parameter
In Parameter Name enter BuildSelection (without ${...}!)
Configure the rest accordingly for your artifacts that will be copied from build job to deploy job's workspace
Use the copied artifacts inside the deploy job as you need in order to deploy
So now, with the above deploy job, you can run it manually and select which build number from build job you want to deploy (last build, last successful, by build number, etc). You probably already have it configured very similarly. The promotion on the build job will basically execute the same thing, and supply the build number, based on what promotion was executed.
Let me know if you got any issues with the instructions.
| Jenkins | 15,126,059 | 63 |
We have a Jenkins server which has successfully built our code over 200 times - until a couple of days ago.
We are now getting an error to indicate that Jenkins was unable to delete the workspace (full message to follow with identifying elements redacted.)
I have checked through the recent code changes, and can see nothing which may have contributed to this issue, and nothing on that server has changed for weeks.
The stack trace suggests that "the context class hudson.FilePath is missing", but the config has not been changed from the config which worked over 200 times.
Can anybody suggest steps which could be taken to fix this ?
Started by user <REDACTED>
> git rev-parse --is-inside-work-tree # timeout=10
Setting origin to https://<REDACTED>@bitbucket.org/<REDACTED>/<REDACTED>.git
> git config remote.origin.url
https://<REDACTED>@bitbucket.org/<REDACTED>/<REDACTED>.git # timeout=10
Fetching origin...
Fetching upstream changes from origin
> git --version # timeout=10
using GIT_ASKPASS to set credentials <REDACTED>@bitbucket
> git fetch --tags --progress origin +refs/heads/*:refs/remotes/origin/*
Seen branch in repository origin/master
Seen branch in repository origin/temp
Seen 2 remote branches
Obtained code/Jenkinsfile from <REDACTED>
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] node
Running on Jenkins in /var/lib/jenkins/workspace/<REDACTED>
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Declarative: Checkout SCM)
[Pipeline] checkout
Cloning the remote Git repository
Cloning with configured refspecs honoured and without tags
Cloning repository https://<REDACTED>@bitbucket.org/<REDACTED>/<REDACTED>.git
ERROR: Failed to clean the workspace
java.io.IOException: Unable to delete '/var/lib/jenkins/workspace/<REDACTED>. Tried 3 times (of a maximum of 3) waiting 0.1 sec between attempts.
at hudson.Util.deleteContentsRecursive(Util.java:252)
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$2.execute(CliGitAPIImpl.java:555)
at hudson.plugins.git.GitSCM.retrieveChanges(GitSCM.java:1120)
at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1160)
at org.jenkinsci.plugins.workflow.steps.scm.SCMStep.checkout(SCMStep.java:113)
at org.jenkinsci.plugins.workflow.steps.scm.SCMStep$StepExecutionImpl.run(SCMStep.java:85)
at org.jenkinsci.plugins.workflow.steps.scm.SCMStep$StepExecutionImpl.run(SCMStep.java:75)
at org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution$1$1.call(AbstractSynchronousNonBlockingStepExecution.java:47)
at hudson.security.ACL.impersonate(ACL.java:290)
at org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution$1.run(AbstractSynchronousNonBlockingStepExecution.java:44)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.nio.file.FileSystemException: /var/lib/jenkins/workspace/<REDACTED>/code/<REDACTED>-query/target/classes/application.properties: Operation not permitted
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:91)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
at sun.nio.fs.UnixFileAttributeViews$Posix.setMode(UnixFileAttributeViews.java:238)
at sun.nio.fs.UnixFileAttributeViews$Posix.setPermissions(UnixFileAttributeViews.java:260)
at java.nio.file.Files.setPosixFilePermissions(Files.java:2045)
at hudson.Util.makeWritable(Util.java:332)
at hudson.Util.tryOnceDeleteFile(Util.java:292)
at hudson.Util.tryOnceDeleteRecursive(Util.java:383)
at hudson.Util.tryOnceDeleteContentsRecursive(Util.java:402)
at hudson.Util.tryOnceDeleteRecursive(Util.java:382)
at hudson.Util.tryOnceDeleteContentsRecursive(Util.java:402)
at hudson.Util.tryOnceDeleteRecursive(Util.java:382)
at hudson.Util.tryOnceDeleteContentsRecursive(Util.java:402)
at hudson.Util.tryOnceDeleteRecursive(Util.java:382)
at hudson.Util.tryOnceDeleteContentsRecursive(Util.java:402)
at hudson.Util.tryOnceDeleteRecursive(Util.java:382)
at hudson.Util.tryOnceDeleteContentsRecursive(Util.java:402)
at hudson.Util.deleteContentsRecursive(Util.java:247)
... 14 more
ERROR: Error cloning remote repo 'origin'
hudson.plugins.git.GitException: Failed to delete workspace
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$2.execute(CliGitAPIImpl.java:558)
at hudson.plugins.git.GitSCM.retrieveChanges(GitSCM.java:1120)
at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1160)
at org.jenkinsci.plugins.workflow.steps.scm.SCMStep.checkout(SCMStep.java:113)
at org.jenkinsci.plugins.workflow.steps.scm.SCMStep$StepExecutionImpl.run(SCMStep.java:85)
at org.jenkinsci.plugins.workflow.steps.scm.SCMStep$StepExecutionImpl.run(SCMStep.java:75)
at org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution$1$1.call(AbstractSynchronousNonBlockingStepExecution.java:47)
at hudson.security.ACL.impersonate(ACL.java:290)
at org.jenkinsci.plugins.workflow.steps.AbstractSynchronousNonBlockingStepExecution$1.run(AbstractSynchronousNonBlockingStepExecution.java:44)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.io.IOException: Unable to delete '/var/lib/jenkins/workspace/<REDACTED>'. Tried 3 times (of a maximum of 3) waiting 0.1 sec between attempts.
at hudson.Util.deleteContentsRecursive(Util.java:252)
at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$2.execute(CliGitAPIImpl.java:555)
... 13 more
Caused by: java.nio.file.FileSystemException: /var/lib/jenkins/workspace/<REDACTED>/code/<REDACTED>-query/target/classes/application.properties: Operation not permitted
at sun.nio.fs.UnixException.translateToIOException(UnixException.java:91)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:102)
at sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:107)
at sun.nio.fs.UnixFileAttributeViews$Posix.setMode(UnixFileAttributeViews.java:238)
at sun.nio.fs.UnixFileAttributeViews$Posix.setPermissions(UnixFileAttributeViews.java:260)
at java.nio.file.Files.setPosixFilePermissions(Files.java:2045)
at hudson.Util.makeWritable(Util.java:332)
at hudson.Util.tryOnceDeleteFile(Util.java:292)
at hudson.Util.tryOnceDeleteRecursive(Util.java:383)
at hudson.Util.tryOnceDeleteContentsRecursive(Util.java:402)
at hudson.Util.tryOnceDeleteRecursive(Util.java:382)
at hudson.Util.tryOnceDeleteContentsRecursive(Util.java:402)
at hudson.Util.tryOnceDeleteRecursive(Util.java:382)
at hudson.Util.tryOnceDeleteContentsRecursive(Util.java:402)
at hudson.Util.tryOnceDeleteRecursive(Util.java:382)
at hudson.Util.tryOnceDeleteContentsRecursive(Util.java:402)
at hudson.Util.tryOnceDeleteRecursive(Util.java:382)
at hudson.Util.tryOnceDeleteContentsRecursive(Util.java:402)
at hudson.Util.deleteContentsRecursive(Util.java:247)
... 14 more
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] stage
[Pipeline] { (Declarative: Post Actions)
[Pipeline] step
Required context class hudson.FilePath is missing
Perhaps you forgot to surround the code with a step that provides this, such as: node
[Pipeline] }
[Pipeline] // stage
[Pipeline] End of Pipeline
ERROR: Error cloning remote repo 'origin'
Finished: FAILURE
| I finally found the solution that explains everything.
Cause:
I was using docker within Jenkins and mounted Jenkins work directory in Docker (-v pwd:/code:rw).
During runtime my program generate few files that also goes in to Jenkins work directory as it is mounted. but the user is docker root not Jenkins user, because of that Jenkins user is unable to delete those files and cause this error.
Solution:
you can also share Jenkins user with docker, So all file created is same as file created by Jenkins itself.
docker run --user "$(id -u):$(id -g)" -i --rm -v /etc/passwd:/etc/passwd:ro -v `pwd`:/code:rw docker_image:tag
So Adding This basically solve the issue by Using Jenkins user inside docker.
--user "$(id -u):$(id -g)" -v /etc/passwd:/etc/passwd:ro
| Jenkins | 50,782,740 | 62 |
I'm trying to use the following code to execute builds, and in the end, execute post build actions when builds were successful. Still, I get a MultipleCompilationErrorsException, saying that my try block is Not a valid section definition. Please help, I tried a lot reorganize the block but can't seem to be able to solve the issue.
pipeline{
agent any
try {
stages{
stage("Parallel 1") {
steps {
parallel (
'firstTask' : {
build( "DSL-Controll-Demo-Fibonacci-1" )
},
'secondTask' : {
build( "DSL-Controll-Demo-Fibonacci-2" )
}
)
}
}
stage("Feature") {
steps {
build( "DSL-Controll-Demo-Fibonacci-5" )
build( "DSL-Controll-Demo-Fibonacci-6" )
}
}
stage("Parallel 2") {
steps{
parallel (
"thirdTask" : {
build( "DSL-Controll-Demo-Fibonacci-3" )
},
"forthTask" : {
build( "DSL-Controll-Demo-Fibonacci-4" )
}
)
}
}
}
}
catch(all) {
currentBuild.result = 'FAILURE'
}
if(currentBuild.result != 'FAILURE') {
stages{
stage("Post Build") {
steps {
build("DSL-Controll-Demo-Fibonacci-7")
}
}
}
}
}
| try like this (no pun intended btw)
script {
try {
sh 'do your stuff'
} catch (Exception e) {
echo 'Exception occurred: ' + e.toString()
sh 'Handle the exception!'
}
}
The key is to put try...catch in a script block in declarative pipeline syntax. Then it will work. This might be useful if you want to say continue pipeline execution despite failure (eg: test failed, still you need reports..)
| Jenkins | 44,003,788 | 62 |
My problem is how to run google chrome in docker container for e2e testing.
I create a Dockerfile from official Jenkins image, but when try to run google chrome, it crashes and show the error:
Failed to move to new namespace: PID namespaces supported, Network namespace supported, but failed: errno = Operation not permitted
Trace/breakpoint trap (core dumped)
The Jenkins docker image uses Debian jessie.
I can run google chrome with --headless flag and the X server is not needed.
This is my docker file:
https://github.com/ripper2hl/jenkinswithchrome
Jenkins official image:
https://github.com/jenkinsci/docker
The repo a person runs google chrome with GUI from docker:
https://github.com/jessfraz/dockerfiles/blob/master/chrome/stable/Dockerfile
My first approach is to use xvbf, but the process is more simple when used --headless flag.
https://gist.github.com/addyosmani/5336747
I can run chrome in Ubuntu server with the same commands for installation, but in docker it fails.
After other intents, I used --no-sandbox flag, but docker images shows the next error.
[0427/180929.595479:WARNING:audio_manager.cc(295)] Multiple instances of AudioManager detected
[0427/180929.595537:WARNING:audio_manager.cc(254)] Multiple instances of AudioManager detected
libudev: udev_has_devtmpfs: name_to_handle_at on /dev: Operation not permitted
Actually I ran this command:
google-chrome-stable --headless --disable-gpu --no-sandbox http://www.google.com
| Just launch chrome with --no-sandbox that s resolves the problem
| Jenkins | 43,665,276 | 62 |
I wanted to show the user who triggered a Jenkins job in the post job email. This is possible by using the plugin Build User Vars Plugin and the env variable BUILD_USER.
But this variable do not get initialized when the job is triggered by a scheduler.
How can we achieve this? I know we have a plugin called - EnvInject Plugin, and that can be used...
But I just want to know how we can use this and achieve the solution...
| SIMPLE SOLUTIONS (NO PLUGINS) !!
METHOD 1: Via Shell
BUILD_TRIGGER_BY=$(curl -k --silent ${BUILD_URL}/api/xml | tr '<' '\n' | egrep '^userId>|^userName>' | sed 's/.*>//g' | sed -e '1s/$/ \//g' | tr '\n' ' ')
echo "BUILD_TRIGGER_BY: ${BUILD_TRIGGER_BY}"
METHOD 2: Via Groovy
node('master') {
BUILD_TRIGGER_BY = sh ( script: "BUILD_BY=\$(curl -k --silent ${BUILD_URL}/api/xml | tr '<' '\n' | egrep '^userId>|^userName>' | sed 's/.*>//g' | sed -e '1s/\$/ \\/ /g'); if [[ -z \${BUILD_BY} ]]; then BUILD_BY=\$(curl -k --silent ${BUILD_URL}/api/xml | tr '<' '\n' | grep '^shortDescription>' | sed 's/.*user //g;s/.*by //g'); fi; echo \${BUILD_BY}", returnStdout: true ).trim()
echo "BUILD_TRIGGER_BY: ${BUILD_TRIGGER_BY}"
}
METHOD 3: Via Groovy (Recommended this method for security reasons)
BUILD_TRIGGER_BY = currentBuild.getBuildCauses()[0].shortDescription + " / " + currentBuild.getBuildCauses()[0].userId
echo "BUILD_TRIGGER_BY: ${BUILD_TRIGGER_BY}"
OUTPUT:
Started by user Admin / [email protected]
Note: Output will be both User ID and User Name
| Jenkins | 36,194,316 | 62 |
I added the Archive Artifacts post-build option to my project. I can see the artifacts from the web browser interface, but I cannot find them in the filesystem.
Where are they located?
| It is being archived on the master server (even if the build were on a slave) in the following folder:
$JENKINS_HOME/jobs/<job>/builds/<build>/archive
But you can configure a different location using the 'Advanced' setting of the job (where you can set a different workspace folder) or using plugins that are made for this purpose such as Copy Artifact Plugin
| Jenkins | 35,890,952 | 62 |
Suppose I have a Groovy script in Jenkins that contains a multi-line shell script. How can I set and use a variable within that script? The normal way produces an error:
sh """
foo='bar'
echo $foo
"""
Caught: groovy.lang.MissingPropertyException: No such property: foo for class: groovy.lang.Binding
| You need to change to triple single quotes ''' or escape the dollar \$
Then you'll skip the groovy templating which is what's giving you this issue
| Jenkins | 35,047,481 | 62 |
I have a git repository hosted on BitBucket, and have set up SSH authentication between the repository and my Jenkins server. I can build on Jenkins manually, but cannot get the Jenkins service on BitBucket to trigger builds.
Jenkins configuration:
- Project Name: [my_jenkins_job]
- Build Triggers:
--Trigger Builds Remotely:
---Token: [token]
BitBucket configuration:
- Endpoint: http://[my_jenkins_address]/job/[my_jenkins_job]/build (I've also tried build?token=[token])
- Project Name: [my_jenkins_job]
- Module Name: [blank]
- Token: [token]
Visiting http://{my_jenkins_address}/job/{my_jenkins_job}/build?token={token} kicks off a build properly.
Why doesn't pushing a change to BitBucket cause Jenkins to initiate a build?
| Due to the Jenkins Hook of Bitbucket is not working at all for me and I have different Jenkins projects for different branches I had come to this solution:
Install Bitbucket Plugin at your Jenkins
Add a normal Post as Hook to your Bitbucket repository (Settings -> Hooks) and use following url:
https://YOUR.JENKINS.SERVER:PORT/bitbucket-hook/
and if you have setup authentication on jenkins then URL must be like
https://USERNAME:[email protected]:PORT/bitbucket-hook/
Configure your Jenkins project as follows:
under build trigger enable Build when a change is pushed to BitBucket
under Source Code Management select GIT; enter your credentials and define Branches to build (like **feature/*)
By this way I have three build projects, one for all features, one for develop and one for release branch. Make sure to include the slash ('/') on the end of the URL or the hook won't work.
And best of it, you don't have to ad new hooks for new Jenkins projects.
| Jenkins | 11,231,064 | 62 |
My JenkinsFile looks like:
pipeline {
agent {
docker {
image 'node:12.16.2'
args '-p 3000:3000'
}
}
stages {
stage('Build') {
steps {
sh 'node --version'
sh 'npm install'
sh 'npm run build'
}
}
stage ('Deliver') {
steps {
sh 'readlink -f ./package.json'
}
}
}
}
I used to have Jenkins locally and this configuration worked, but I deployed it to a remote server and get the following error:
WorkflowScript: 3: Invalid agent type "docker" specified. Must be one of [any, label, none] @ line 3, column 9.
docker {
I could not find a solution to this problem on the Internet, please help me
| You have to install 2 plugins: Docker plugin and Docker Pipeline.
Go to Jenkins root page > Manage Jenkins > Manage Plugins > Available and search for the plugins. (Learnt from here).
| Jenkins | 62,253,474 | 61 |
I can ask this question in many ways, like
How to configure Jenkins credentials with Github Personal Access Token
How to clone Github repo in Jenkins using Github Personal Access Token
So this is the problem
The alternate solution that I am aware of
SSH connection
username password configuration in Jenkins. However,
use of a password with the GitHub API is now deprecated.
But My question is how to setup Github connection with Jenkins using Personal Access Token
| [UPDATE]
The new solution proposed by git is
https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/
Which says:
Beginning August 13, 2021, we will no longer accept account passwords
when authenticating Git operations and will require the use of
token-based authentication, such as a personal access token (for
developers) or an OAuth or GitHub App installation token (for
integrators) for all authenticated Git operations on GitHub.com. You
may also continue using SSH keys where you prefer.
What you need to do:
https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/#what-you-need-to-do-today
Basically, change the add URL as
https://<access token>@github.com/<userName>/<repository>.git
Something like this
https://<access token>@github.com/dupinder/NgnixDockerizedDevEnv.git
and set the credentials to none.
Thanks to @Gil Stal
[OLD Technique]
After many discussion on multiple threads from Stackoverflow
I found one thread that is useful.
Refer to this answer:
https://stackoverflow.com/a/61104603/5108695
Basically
Personal access token can be used as a password, as far as Jenkins is concerned at least. I added new credentials to the credential manager.
Go to Jenkins
Go to credentials > System > Global credentials > Add credentials a page will open.
In Kind drop-down select Username and password.
In User put a non-existing username like jenkins-user or user.
Add Personal Access Token in the password field
Now start configuring your project.
source code management tab, select new configured credentials from Drop-down near credential Under Repository URL
So this is how we can configure or setup Authentication between Jenkins and Github using Personal Access Token
References:
Git Clone in Jenkins with Personal Access Token idles forever
Change jenkins pipeline to use github instead of gitlab
| Jenkins | 61,105,368 | 61 |
I am gaining knowledge about Docker and I have the following questions
Where are Dockerfile's kept in a project?
Are they kept together with the source?
Are they kept outside of the source? Do you have an own Git repository just for the Dockerfile?
If the CI server should create a new image for each build and run that on the test server, do you keep the previous image? I mean, do you tag the previous image or do you remove the previous image before creating the new one?
I am a Java EE developer so I use Maven, Jenkins etc if that matter.
| The only restriction on where a Dockerfile is kept is that any files you ADD to your image must be beneath the Dockerfile in the file system. I normally see them at the top level of projects, though I have a repo that combines a bunch of small images where I have something like
top/
project1/
Dockerfile
project1_files
project2/
Dockerfile
project2_files
The Jenkins docker plugin can point to an arbitrary directory with a Dockerfile, so that's easy. As for CI, the most common strategy I've seen is to tag each image built with CI as 'latest'. This is the default if you don't add a tag to a build. Then releases get their own tags. Thus, if you just run an image with no arguments you get the last image built by CI, but if you want a particular release it's easy to say so.
| Jenkins | 27,387,811 | 61 |
I do not want new users to be able to sign up. So in Jenkin's Configuration, I disabled "Allow users to sign up" with using Jenkin's own user database.
But how can I manually add users now?
Also, is there a default admin user I should take care of?
| There is "Create Users" in "Manage Jenkins".
| Jenkins | 12,056,851 | 61 |
I'm using Scriptler plugin, so I can run a groovy script as a build step. My Jenkins slaves are running on windows in service mode. With scriptler, I don't need to use windows batch scripts.
But I have trouble to get the environment variables in a build step... This is working:
System.getenv("BASE")
Where BASE is part of the env-vars on jenkins startup. However, I would like to get
%JOB_NAME%
If I'm adding an "Execute Windows batch command" build step:
echo %JOB_NAME%
It works.
If I'm adding a scriptler script as a build step with the same settings:
println "JOB_NAME: " + System.getenv("JOB_NAME")
I'm getting:
JOB_NAME: null
So how can I reach the injected environment variables from a groovy script as a build step?
| build and listener objects are presenting during system groovy execution. You can do this:
def myVar = build.getEnvironment(listener).get('myVar')
| Jenkins | 21,236,268 | 60 |
These have all been mentioned (for example in this SO question) for cleaning up the workspace in Jenkinsfile. However, it seems that some are obsolete or have slightly different function and I would like to understand which to use.
Of these, deleteDir is the most commonly mentioned, and apparently the others are just different syntaxes for invoking the Jenkins Workspace Cleanup Plugin.
What is the functional difference? Which is recommended?
deleteDir()
cleanWs()
step([$class: 'WsCleanup'])
| From the official documentation:
deleteDir: Recursively delete the current directory from the workspace.
Recursively deletes the current directory and its contents. Symbolic links and junctions will not be followed but will be removed. To delete a specific directory of a workspace wrap the deleteDir step in a dir step.
So, deleteDir is a method of Workflow Basic Steps plugin (which is a component of Pipeline Plugin).
cleanWs: Delete workspace when build is done.
Seems to be that cleanWs() is just a new version of step([$class: 'WsCleanup']) from Workspace Cleanup Plugin.
As I understand, between deleteDir and cleanWs is a slightly difference: cleanWs has more options (like cleanWhenAborted, cleanWhenFailure, etc.) and it's more flexible to use, but it's recommended to use only when build is done (not sure if we can use it at the beginning of build execution). On the other side, we can use deleteDir step to wipe the workspace before build execution.
UPDATE 1:
The post build cleanWs step can also take into account the build status, that's why it should be used only after the build execution.
However, under ws-cleanup plugin there is preBuildCleanup step as well. You can check an example (DSL) with both preBuildCleanup and cleanWs on the plugin page.
UPDATE 2:
@aaron-d-marasco pointed out that it's better not to use deleteDir in a docker image.
You can check the details in this open bug.
| Jenkins | 54,019,121 | 60 |
quite frustrating I can't find an example of this. How do I set the default choice?
parameters {
choice(
defaultValue: 'bbb',
name: 'param1',
choices: 'aaa\nbbb\nccc',
description: 'lkdsjflksjlsjdf'
)
}
defaultValue is not valid here. I want the choice to be optional and a default value to be set if the pipeline is run non-manually (via a commit).
| You can't specify a default value in the option. According to the documentation for the choice input, the first option will be the default.
The potential choices, one per line. The value on the first line will be the default.
You can see this in the documentation source, and also how it is invoked in the source code.
return new StringParameterValue(
getName(),
defaultValue == null ? choices.get(0) : defaultValue, getDescription()
);
| Jenkins | 47,873,401 | 60 |
I am running Multibranch pipeline for my project.
The behaviour of Jenkinsfile should change according to the trigger.
There are two events that triggeres the pipeline 1. Push event 2. Pull Request.
I am trying to check Environment variable 'CHANGE_ID' ('CHANGE_ID' will be available for Pull Request only).Reference .
So if pipeline is triggred by Push event and If check the 'CHANGE_ID' variable it throws exception (code works fine if pipeline gets triggered by Pull Request).
Code:
stage('groovyTest'){
node('mynode1') {
if (CHANGE_ID!=NULL){
echo "This is Pull request"
}else{
echo "This is Push request"
}
}
}
Error:
groovy.lang.MissingPropertyException: No such property: CHANGE_ID for class: groovy.lang.Binding
at groovy.lang.Binding.getVariable(Binding.java:63)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:224)
at org.kohsuke.groovy.sandbox.impl.Checker$4.call(Checker.java:241)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:238)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:221)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:221)
at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.getProperty(SandboxInvoker.java:28)
at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:20)
at WorkflowScript.run(WorkflowScript:5)
at ___cps.transform___(Native Method)
How can I check the 'CHANGE_ID' variable exist or not in Jenkinsfile?
| You may check it before use it:
if (env.CHANGE_ID) {
...
From the doc
Environment variables accessible from Scripted Pipeline, for example: env.PATH or env.BUILD_ID. Consult the built-in Global Variable Reference for a complete, and up to date, list of environment variables available in Pipeline.
| Jenkins | 45,758,597 | 60 |
My Jenkins jobs are running out of memory, giving java.lang.OutOfMemoryError messages in the build log. But I used the Ubuntu Package Manager, aptitude, or apt-get to install Jenkins, and I don't know where to look to change the amount of heap space allocated to Jenkins.
| There are two types of OutOfMemoryError messages that you might encounter while a Jenkins job runs:
java.lang.OutOfMemoryError: Heap space – this means that you
need to increase the amount of heap space allocated to Jenkins when
the daemon starts.
java.lang.OutOfMemoryError: PermGen space – this means you need to increase the
amount of generation space allocated to store Java object metadata. Increasing
the value of the -Xmx parameter will have no affect on this error.
On Ubuntu 12.04 LTS, uncomment the JAVA_ARGS setting on line ten of /etc/default/jenkins:
To add more Java heap space, increase the value of the -Xmx Java parameter. That sets the maximum size of the memory allocation pool (the garbage collected heap).
To add more PermGen space, add the parameter XX:MaxPermSize=512m (replace 512 with something else if you want more. The permanent generation heap holds meta information about user classes.
For example, this extract is from the default /etc/default/jenkins after a fresh install of Jenkins:
# arguments to pass to java
#JAVA_ARGS="-Xmx256m"
This is how it would look if you set the heap space to be 1 GB:
# arguments to pass to java
JAVA_ARGS="-Xmx1048m"
Be careful not to set the heap size too large, as whatever you allocate reduces the amount of memory available to the operating system and other programs, which could cause excessive paging (memory swapped back and forth between RAM and the swap disc, which will slow your system down).
If you also set MaxPermSpace, you need to add a space between the parameters):
# arguments to pass to java
JAVA_ARGS="-Xmx1048m -XX:MaxPermSize=512m"
After making a change, restart Jenkins gracefully from the Jenkins web interface, or force an immediate restart from the command-line with sudo /etc/init.d/jenkins restart.
I found the following site useful for understanding Java maximum and permanent generation heap sizes: http://www.freshblurbs.com/blog/2005/05/19/explaining-java-lang-outofmemoryerror-permgen-space.html.
| Jenkins | 14,762,162 | 60 |
I need to run a shell script in Jenkins as root instead of the default user. What do I need to change?
My sudoers file is like this:
# User privilege specification
root ALL=(ALL) ALL
igx ALL=(ALL) ALL
%wheel ALL=(ALL) ALL
# Allow members of group sudo to execute any command
# (Note that later entries override this, so you might need to move
%sudo ALL=(ALL) ALL
#
#includedir /etc/sudoers.d
# Members of the admin group may gain root privileges
%admin ALL=(ALL) NOPASSWD:ALL
root ALL=(ALL) ALL
jenkins ALL=NOPASSWD: /var/lib/jenkins/workspace/ing00112/trunk/source/
jenkins ALL=(ALL) NOPASSWD:ALL
#Defaults:jenkins !requiretty
| You must run the script using sudo:
sudo /path/to/script
But before you must allow jenkins to run the script in /etc/sudoers.
jenkins ALL = NOPASSWD: /path/to/script
| Jenkins | 11,880,070 | 60 |
I am new to Jenkins, and I'm not sure if this is possible, but I would like to set up a web interface where somebody could click "Start Job" and this will tell Jenkins to start a particular build job.
Does Jenkins have a webservice that would allow such a thing? If so, what would be a simple example?
| Here is a link to the documentation: Jenkins Remote Access API.
Check out the Submitting jobs section.
In your job configuration you setup a token and then create a POST request to JENKINS_URL/job/JOBNAME/build?token=TOKEN. That's probably the most basic usage.
| Jenkins | 8,512,807 | 60 |
I'm using Jenkins, Maven 3.1, and Java 1.6. I have the following Maven job set up in Jenkins with the following goals and options ...
clean install -U -P cloudbees -P qa
below is my pom.xml surefire configuration ...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.17</version>
<configuration>
<reuseForks>true</reuseForks>
<argLine>-Xmx2048m -XX:MaxPermSize=512M </argLine>
<skipTests>false</skipTests>
</configuration>
</plugin>
However, when my unit tests fail, the Jenkins console output still says "BUILD SUCCESS" and the build is marked as "unstable" instead of outright failing. How do I configure things in Jenkins (or Maven if taht's what it turns out to be) so that my build fails (not becomes unstable or passes) if any of the unit tests fail?
Below is what the console output says
17:08:04 MyProjectOrganizationControllerTest.testRecoverFromError » IllegalState Failed to...
17:08:04 MyProjectOrganizationControllerTest.testVerifyDistrictListPopulated » IllegalState
17:08:04 MyProjectOrganizationControllerTest.testUpdateSchool » IllegalState Failed to loa...
17:08:04 MyProjectOrganizationControllerTest.testDeleteSchool » IllegalState Failed to loa...
17:08:04 MyProjectOrganizationControllerTest.testVerifyOrgListPopulatedPrivateSchoolOrgType » IllegalState
17:08:04 MyProjectOrganizationControllerTest.testSubmitMultipleParams » IllegalState Faile...
17:08:04
17:08:04 Tests run: 155, Failures: 0, Errors: 154, Skipped: 1
17:08:04
17:08:04 [ERROR] There are test failures.
17:08:04
17:08:04 Please refer to /scratch/jenkins/workspace/MyProject/MyProject/target/surefire-reports for the individual test results.
17:08:04 [JENKINS] Recording test results
17:08:07 log4j:WARN No appenders could be found for logger (org.apache.commons.beanutils.converters.BooleanConverter).
17:08:07 log4j:WARN Please initialize the log4j system properly.
17:08:14 [INFO]
17:08:14 [INFO] --- maven-war-plugin:2.4:war (default-war) @ MyProject ---
17:08:15 [INFO] Packaging webapp
17:08:15 [INFO] Assembling webapp [MyProject] in [/scratch/jenkins/workspace/MyProject/MyProject/target/MyProject]
17:08:15 [INFO] Processing war project
17:08:15 [INFO] Copying webapp resources [/scratch/jenkins/workspace/MyProject/MyProject/src/main/webapp]
17:08:15 [INFO] Webapp assembled in [662 msecs]
17:08:15 [INFO] Building war: /scratch/jenkins/workspace/MyProject/MyProject/target/MyProject.war
17:08:20 [INFO]
17:08:20 [INFO] --- maven-failsafe-plugin:2.17:integration-test (default) @ MyProject ---
17:08:20 [JENKINS] Recording test results
17:08:25 [INFO]
17:08:25 [INFO] --- maven-failsafe-plugin:2.17:verify (default) @ MyProject ---
17:08:25 [INFO] Failsafe report directory: /scratch/jenkins/workspace/MyProject/MyProject/target/failsafe-reports
17:08:25 [JENKINS] Recording test results[INFO]
17:08:25 [INFO] --- maven-install-plugin:2.4:install (default-install) @ MyProject ---
17:08:25
17:08:25 [INFO] Installing /scratch/jenkins/workspace/MyProject/MyProject/target/MyProject.war to /home/jenkins/.m2/repository/org/mainco/subco/MyProject/76.0.0-SNAPSHOT/MyProject-76.0.0-SNAPSHOT.war
17:08:25 [INFO] Installing /scratch/jenkins/workspace/MyProject/MyProject/pom.xml to /home/jenkins/.m2/repository/org/mainco/subco/MyProject/76.0.0-SNAPSHOT/MyProject-76.0.0-SNAPSHOT.pom
17:08:26 Started calculate disk usage of build
17:08:26 Finished Calculation of disk usage of build in 0 seconds
17:08:26 Started calculate disk usage of workspace
17:08:26 Finished Calculation of disk usage of workspace in 0 seconds
17:08:26 [INFO] ------------------------------------------------------------------------
17:08:26 [INFO] BUILD SUCCESS
17:08:26 [INFO] ------------------------------------------------------------------------
17:08:26 [INFO] Total time: 11:00.616s
17:08:26 [INFO] Finished at: Mon Feb 23 17:08:26 UTC 2015
17:08:27 [INFO] Final Memory: 90M/414M
17:08:27 [INFO] ------------------------------------------------------------------------
17:08:27 Waiting for Jenkins to finish collecting data
17:08:28 [JENKINS] Archiving /scratch/jenkins/workspace/MyProject/MyProject/pom.xml to org.mainco.subco/MyProject/76.0.0-SNAPSHOT/MyProject-76.0.0-SNAPSHOT.pom
17:08:28 [JENKINS] Archiving /scratch/jenkins/workspace/MyProject/MyProject/target/MyProject.war to org.mainco.subco/MyProject/76.0.0- SNAPSHOT/MyProject-76.0.0-SNAPSHOT.war
17:08:31 channel stopped
17:08:31 Started calculate disk usage of build
17:08:31 Finished Calculation of disk usage of build in 0 seconds
17:08:31 Started calculate disk usage of workspace
17:08:31 Finished Calculation of disk usage of workspace in 0 seconds
17:08:31 Finished: UNSTABLE
| You can add -Dmaven.test.failure.ignore=false to the MAVEN_OPTS if you click on Advanced button in the Build section of your Jenkins Job.
See Maven Surefire Plugin - surefire:test options for reference.
| Jenkins | 28,683,518 | 59 |
I would like to mark a Jenkins build to fail on one scenario for example:
if [ -f "$file" ]
then
echo "$file found."
else
echo "$file not found."
#Do Jenkins Build Fail
fi
Is it possible via Shell Script?
Answer: If we exit with integer 1, Jenkins build will be marked as failed. So I replaced the comment with exit 1 to resolve this.
| All you need to do is exit 1.
if [ -f "$file" ]
then
echo "$file found."
else
echo "$file not found."
exit 1
fi
| Jenkins | 20,845,381 | 59 |
Goal
Run multiple stages of a declarative Jenkins pipeline on the same node.
Setup
This is just a minimal example to show the problem. There are 2 Windows nodes "windows-slave1" and "windows-slave2" both labeled with the label "windows".
NOTE: My real Jenkinsfile cannot use a global agent because there are groups of stages that require to run on different nodes (e.g. Windows vs. Linux).
Expected Behaviour
Jenkins selects one of the nodes in "Stage 1" based on the label and uses the same node in "Stage 2" because the variable windowsNode was updated to the node selected in "Stage 1".
Actual Behaviour
"Stage 2" sometimes runs on the same and sometimes on a different node than "Stage 1". See the output below.
Jenkinsfile
#!groovy
windowsNode = 'windows'
pipeline {
agent none
stages {
stage('Stage 1') {
agent {
label windowsNode
}
steps {
script {
// all subsequent steps should be run on the same windows node
windowsNode = NODE_NAME
}
echo "windowsNode: $windowsNode, NODE_NAME: $NODE_NAME"
}
}
stage('Stage 2') {
agent {
label windowsNode
}
steps {
echo "windowsNode: $windowsNode, NODE_NAME: $NODE_NAME"
}
}
}
}
Output
[Pipeline] stage
[Pipeline] { (Stage 1)
[Pipeline] node
Running on windows-slave2 in C:\Jenkins\workspace\test-agent-allocation@2
[Pipeline] {
[Pipeline] script
[Pipeline] {
[Pipeline] }
[Pipeline] // script
[Pipeline] echo
windowsNode: windows-slave2, NODE_NAME: windows-slave2
[Pipeline] }
[Pipeline] // node
[Pipeline] }
[Pipeline] // stage
[Pipeline] stage
[Pipeline] { (Stage 2)
[Pipeline] node
Running on windows-slave1 in C:\Jenkins\workspace\test-agent-allocation
[Pipeline] {
[Pipeline] echo
windowsNode: windows-slave2, NODE_NAME: windows-slave1
[Pipeline] }
[Pipeline] // node
[Pipeline] }
[Pipeline] // stage
[Pipeline] End of Pipeline
Finished: SUCCESS
Any ideas what's wrong with the setup? I guess it's how the Jenkinsfile is parsed and executed.
Other suggestions? Maybe there is a Jenkins API to select a node based on the "windows" label when setting windowsNode initially.
| Since version 1.3 of Declarative Pipeline plugin, this is officially supported.
It's officially called "Sequential Stages".
pipeline {
agent none
stages {
stage("check code style") {
agent {
docker "code-style-check-image"
}
steps {
sh "./check-code-style.sh"
}
}
stage("build and test the project") {
agent {
docker "build-tools-image"
}
stages {
stage("build") {
steps {
sh "./build.sh"
}
}
stage("test") {
steps {
sh "./test.sh"
}
}
}
}
}
}
Official announcement here: https://jenkins.io/blog/2018/07/02/whats-new-declarative-piepline-13x-sequential-stages/
| Jenkins | 44,870,978 | 58 |
I am getting started with Jenkins declarative Pipeline. From some of the examples I have seen, I notice that the Jenkinsfile is setup with the Pipeline directive:
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'make'
}
}
stage('Test'){
steps {
sh 'make check'
junit 'reports/**/*.xml'
}
}
stage('Deploy') {
steps {
sh 'make publish'
}
}
}
}
In other examples, I notice that the Jenkinsfile is setup with a node directive:
node {
stage 'Checkout'
checkout scm
stage 'Build'
bat 'nuget restore SolutionName.sln'
bat "\"${tool 'MSBuild'}\" SolutionName.sln /p:Configuration=Release /p:Platform=\"Any CPU\" /p:ProductVersion=1.0.0.${env.BUILD_NUMBER}"
stage 'Archive'
archive 'ProjectName/bin/Release/**'
}
I haven't been able to find solid documentation on exactly when / why to use each of these. Does anybody have any information on why these differ and when it is appropriate to use either of them?
I'm not sure but I belive the 'node' directive is used in scripted pipeline as opposed to declarative pipeline.
Thanks in advance for any guidance.
| yes, a top-level node implies scripted pipeline, and a top-level pipeline implies declarative pipeline.
declarative appears to be the more future-proof option and the one that people recommend, like in this jenkins user list post where a core contributor says "go declarative." it's the only one the Visual Pipeline Editor can support. it supports validation. and it ends up having most of the power of scripted since you can fall back to scripted in most contexts. occasionally someone comes up with a use case where they can't quite do what they want to do with declarative, but this is generally people who have been using scripted for some time, and these feature gaps are likely to close in time. and finally, if you really have to bail on one or the other, writing a programmatic translator from declarative to scripted would be easier than the other way around (sort of by definition, since the grammar is more tightly constrained).
more context on pros of declarative from the general availability blog post: https://jenkins.io/blog/2017/02/03/declarative-pipeline-ga/
the most official docs i could find that mention both (as of June 21, 2017): https://jenkins.io/doc/book/pipeline/syntax/
| Jenkins | 44,657,896 | 58 |
I am trying to create a Jenkins workflow using a Jenkinsfile. All I want it to do is monitor the 'develop' branch for changes. When a change occurs, I want it to git tag and merge to master. I am using the GitSCM Step but the only thing that it appears to support is git clone. I don't want to have to shell out to do the tag / merge but I see no way around it. Does anyone know if this is possible? I am using BitBucket (on-prem) for my Git server.
| If what you're after are the git credentials you can use the SSH Agent plugin like in this link: https://issues.jenkins-ci.org/browse/JENKINS-28335?focusedCommentId=260925&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-260925
sshagent(['git-credentials-id']) {
sh "git push origin master"
}
| Jenkins | 38,769,976 | 58 |
I am studying capabilities of Jenkins Pipeline:Multibranch. It is said that a recently introduced properties step might be useful there, but I can't catch how it works and what is its purpose.
Its hint message doesn't seem to be very clear:
Updates the properties of the job which runs this step. Mainly useful from multibranch workflows, so that Jenkinsfile itself can encode what would otherwise be static job configuration.
So I created a new Pipeline with this as a script (pasted directly into Jenkins not in SCM):
properties [[$class: 'ParametersDefinitionProperty',
parameterDefinitions: [[$class: 'StringParameterDefinition',
defaultValue: '', description: '', name: 'PARAM1']]
]]
I ran it and nothing happened, job didn't received a new parameter and even if it did I don't get why I might need this. Could anyone please explain?
UPDATE1: I tried putting a dummy Pipeline with properties step into my git repo, then configured a multibranch job.
println 1
properties [[$class: 'ParametersDefinitionProperty', parameterDefinitions: [[$class: 'StringParameterDefinition', defaultValue: 'str1', description: '', name: 'PARAM1']]], [$class: 'RebuildSettings', autoRebuild: false, rebuildDisabled: false]]
println 2
It found my branch, created a job but the build failed with:
groovy.lang.MissingPropertyException: No such property: properties for class: groovy.lang.Binding
at groovy.lang.Binding.getVariable(Binding.java:62)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:185)
at org.kohsuke.groovy.sandbox.impl.Checker$4.call(Checker.java:241)
at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:238)
at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.getProperty(SandboxInvoker.java:23)
at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:17)
at WorkflowScript.run(WorkflowScript:2)
at ___cps.transform___(Native Method)
at com.cloudbees.groovy.cps.impl.PropertyishBlock$ContinuationImpl.get(PropertyishBlock.java:62)
at com.cloudbees.groovy.cps.LValueBlock$GetAdapter.receive(LValueBlock.java:30)
at com.cloudbees.groovy.cps.impl.PropertyishBlock$ContinuationImpl.fixName(PropertyishBlock.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
at com.cloudbees.groovy.cps.impl.ConstantBlock.eval(ConstantBlock.java:21)
at com.cloudbees.groovy.cps.Next.step(Next.java:58)
at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:154)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$001(SandboxContinuable.java:19)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable$1.call(SandboxContinuable.java:33)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable$1.call(SandboxContinuable.java:30)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox.runInSandbox(GroovySandbox.java:106)
at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:30)
at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:164)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:277)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$000(CpsThreadGroup.java:77)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:186)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:184)
at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:47)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:112)
at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334)
at java.util.concurrent.FutureTask.run(FutureTask.java:166)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
at java.lang.Thread.run(Thread.java:722)
UPDATE2: when I put the same script (as in UPD1) back into Jenkins and runs it, it asked for new permission method groovy.lang.GroovyObject getProperty java.lang.String. I approved it, the build went green, however, still no changes to the job configuration appeared.
My env is: Jenkins 1.625.3, Pipeline+Multibranch 1.13
| Using properties with explicit method syntax will work, i.e.:
properties( [ ... ] ) rather than properties [ ... ]
Alternatively, it will work without if you specify the parameter name, e.g.:
properties properties: [ ... ]
For example defining three properties is as easy as :
properties([
parameters([
string(name: 'submodule', defaultValue: ''),
string(name: 'submodule_branch', defaultValue: ''),
string(name: 'commit_sha', defaultValue: ''),
])
])
/* Accessible then with : params.submodule, params.submodule_branch... */
| Jenkins | 35,370,810 | 58 |
Jenkins had 600+ plugins, in the real system, we are used to install lots of plugins.
And sometimes, we want to remove some plugins to make system more clean or replace with another mature plugin (different name).
This needs to make sure no one/no job use those plugins or I need to notify them.
Are there any ways in configuration or somewhere in Jenkins system to know whether the plugin is used by any jobs ?
UPDATE 2013
Based on the answer below, I maintain the simple "plugin:keyword" mapping, like
plugin_keys = {
"git":'scm class="hudson.plugins.git.GitSCM"',
"copyartifact":"hudson.plugins.copyartifact.CopyArtifact",
# and more
}
And search the plugin keyword from the config.xml, all the information (plugins,jobs,config) can be fetched via jenkins remote API
it works for me.
UPDATE 2014.04.26
Later jenkins version, it seems the config.xml is changed to have plugin name there directly
Like
<com.coravy.hudson.plugins.github.GithubProjectProperty plugin="[email protected]">
<hudson.plugins.throttleconcurrents.ThrottleJobProperty plugin="[email protected]">
<hudson.plugins.disk__usage.DiskUsageProperty plugin="[email protected]"/>
<scm class="hudson.plugins.git.GitSCM" plugin="[email protected]">
Therefore I just check this plugin="<plugin name>" in config.xml, it works again
UPDATE 2014.05.05
See complete script in gist jenkins-stats.py
UPDATE 2018.6.7
There is plugin usage plugin support this (no REST API yet)
| Here are 2 ways to find that information.
The easiest is probably to to grep the job config files:
E.g. when you know the class name (or package name) of your plugin (e.g. org.jenkinsci.plugins.unity3d.Unity3dBuilder):
find $JENKINS_HOME/jobs/ -name config.xml -maxdepth 2 | xargs grep Unity3dBuilder
Another is to use something like the scriptler plugin, but then you need more information about where the plugin is used in the build.
import hudson.model.*
import hudson.maven.*
import hudson.tasks.*
for(item in Hudson.instance.items) {
//println("JOB : "+item.name);
for (builder in item.builders){
if (builder instanceof org.jenkinsci.plugins.unity3d.Unity3dBuilder) {
println(">>" + item.name.padRight(50, " ") + "\t UNITY3D BUILDER with " + builder.unity3dName);
}
}
}
}
Update: here's a small scriplet script that might ease you finding the relevant class names. It can certainly be improved:
import jenkins.model.*;
import hudson.ExtensionFinder;
List<ExtensionFinder> finders = Jenkins.instance.getExtensionList(ExtensionFinder.class);
for (finder in finders) {
println(">>> " + finder);
if (finder instanceof hudson.ExtensionFinder.GuiceFinder) {
println(finder.annotations.size());
for (key in finder.annotations.keySet()) {
println(key);
}
} else if (finder instanceof ruby.RubyExtensionFinder) {
println(finder.parsedPlugins.size());
for (plugin in finder.parsedPlugins) {
for (extension in plugin.extensions) {
println("ruby wrapper for " + extension.instance.clazz);
}
}
} else if (finder instanceof hudson.cli.declarative.CLIRegisterer) {
println(finder.discover(Jenkins.instance));
for (extension in finder.discover(Jenkins.instance)) {
println("CLI wrapper for " + extension.instance.class);
// not sure what to do with those
}
} else {
println("UNKNOWN FINDER TYPE");
}
}
(inlined scriplet from my original listJenkinsExtensions submission to http://scriptlerweb.appspot.com which seems down)
Don't forget to backup!
| Jenkins | 18,138,361 | 58 |
How to go about renaming a job in jenkins?
Is there another way than to create a new job and destroying the old one?
| In Jenkins v2, in your dashboard or job overview, click right button on the job and select rename:
| Jenkins | 12,779,189 | 58 |
When I go to mydomain.example:8080 there is no authorization mechanism by default. I have had look at the configuration area but cannot find anywhere to add a basic username and password
| Go to Manage Jenkins > Configure Global Security and select the Enable Security checkbox.
For the basic username/password authentication, I would recommend selecting Jenkins Own User Database for the security realm and then selecting Logged in Users can do anything or a matrix based strategy (in case when you have multiple users with different permissions) for the Authorization.
| Jenkins | 10,825,614 | 58 |
With this code i got an error in Jenkins pipeline. I don`t get it why?
Am I missing something?
node {
stage 'test'
def whatThe = someFunc('textToFunc')
{def whatThe2 = someFunc2('textToFunc2')}
}
def someFunc(String text){
echo text
text
}
def someFunc2(String text2){
echo text2
text2
}
Error:
java.lang.NoSuchMethodError: **No such DSL method 'someFunc'** found among [archive, bat, build, catchError, checkout, deleteDir, dir, echo, emailext, emailextrecipients, error, fileExists, git, input, isUnix, load, mail, node, parallel, properties, pwd, readFile, readTrusted, retry, sh, sleep, stage, stash, step, svn, timeout, timestamps, tool, unarchive, unstash, waitUntil, withCredentials, withEnv, wrap, writeFile, ws]
at org.jenkinsci.plugins.workflow.cps.DSL.invokeMethod(DSL.java:124)
at org.jenkinsci.plugins.workflow.cps.CpsScript.invokeMethod(CpsScript.java:117)
at groovy.lang.MetaClassImpl.invokeMethodOnGroovyObject(MetaClassImpl.java:1280)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1174)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1024)
at org.codehaus.groovy.runtime.callsite.PogoMetaClassSite.call(PogoMetaClassSite.java:42)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:48)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:113)
at com.cloudbees.groovy.cps.sandbox.DefaultInvoker.methodCall(DefaultInvoker.java:15)
at WorkflowScript.run(WorkflowScript:4)
at ___cps.transform___(Native Method)
at com.cloudbees.groovy.cps.impl.ContinuationGroup.methodCall(ContinuationGroup.java:55)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.dispatchOrArg(FunctionCallBlock.java:106)
at com.cloudbees.groovy.cps.impl.FunctionCallBlock$ContinuationImpl.fixArg(FunctionCallBlock.java:79)
at sun.reflect.GeneratedMethodAccessor878.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
at com.cloudbees.groovy.cps.impl.ClosureBlock.eval(ClosureBlock.java:40)
at com.cloudbees.groovy.cps.Next.step(Next.java:58)
at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:154)
at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:164)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:360)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$100(CpsThreadGroup.java:80)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:236)
at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:226)
at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:47)
at java.util.concurrent.FutureTask.run(Unknown Source)
at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:112)
at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Finished: FAILURE
| remove the extra brackets from around the sumfunc2 invocation:
node {
stage 'test'
def whatThe = someFunc('textToFunc')
def whatThe2 = someFunc2('textToFunc2')
}
def someFunc(String text){
echo text
text
}
def someFunc2(String text2){
echo text2
text2
}
Update:
In Groovy if a method's last argument is of type Closure, then when calling the method the closure can be outside of the brackets like:
def foo(whatever, Closure c) {}
// Can be invoked as
foo(whatever, {
// This is the second argument of foo of type Closure
})
// It is also the same as writing
foo(whatever) {
// This is the second argument of foo of type Closure
}
The reason that the original throws is because the following code
def whatThe = someFunc('textToFunc')
{def whatThe2 = someFunc2('textToFunc2')}
is the same code as
def whatThe = someFunc('textToFunc') {
def whatThe2 = someFunc2('textToFunc2')
}
This means that what the interpreter will be looking for is
someFunc(String text, Closure c)
and there is no such method
| Jenkins | 38,895,509 | 57 |
I am getting the warning Missing blame information for the following files during analysis by SonarQube.
[INFO] [22:19:57.714] Sensor SCM Sensor
[INFO] [22:19:57.715] SCM provider for this project is: git
[INFO] [22:19:57.715] 48 files to be analyzed
[INFO] [22:19:58.448] 0/48 files analyzed
[WARN] [22:19:58.448] Missing blame information for the following files:
(snip 48 lines)
[WARN] [22:19:58.449] This may lead to missing/broken features in SonarQube
[INFO] [22:19:58.449] Sensor SCM Sensor (done) | time=735ms
I am using SonarQube 5.5, analysis is done by Maven in a Jenkins job, on a multi-module Java project.
Git plugin 1.2 is installed.
Manually running git blame in a bash shell, on any of the offending files, gives an expected output.
Related questions I found were all about SVN, my issue is with Git.
How do I get git blame information on Sonarqube?
| The cause was a JGit bug. JGit does not support .gitattributes. I had ident in my .gitattributes. Plain console git checked out the source, applied ident on $Id$ macros, but then JGit ignored that and saw a difference that wasn't committed, where there actually wasn't one.
The friendly people on the SonarQube mailing list helped me out, and suggested debugging with the standalone JGit command line distribution:
chmod +x /where/is/org.eclipse.jgit.pgm-<version>-r.sh
/where/is/org.eclipse.jgit.pgm-<version>-r.sh blame -w /path/to/offending/file
This particular JGit bug has not been solved for over 5 years and I have no hope that it will be solved anytime soon, so I removed the $Id$ macros from all my sources.
This is the (Bash) code I used, to remove all $Id$ macros:
find */src -name "*.java" | xargs -n 1 sed -i '/$Id.*$/d'
find */src -name "*.java" | xargs git add
git commit -m "Remove $Id$ macros"
git push
| Jenkins | 37,432,290 | 57 |
We're trying to deploy a war file with Jenkins, but nothing seems to happen.
The project is built successfully, and we're using Jenkins deploy plugin. It is configured with the following options:
Post steps are set to "run regardless of build result".
I have checked that the credentials are correct, as I can acces the manager page in my browser.
Here is the last part that Jenkins (Maven) outputs:
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1:24.506s
[INFO] Finished at: Tue Feb 14 12:10:45 UTC 2012
[INFO] Final Memory: 22M/52M
[INFO] ------------------------------------------------------------------------
channel stopped
Finished: SUCCESS
I can also change WAR/EAR file to something that doesn't exist, and it will not give me errors, which is kind of strange. What am I doing wrong here?
| I was having the same problem, and in my case the (relative) path to the WAR file was incorrect. Apparently if you don't have it exactly correct (it needs to be relative to the workspace root) then the deploy plugin will silently fail. In my case the path was:
target/whatever.war
Once that was fixed, I ran into a different problem in that the plugin expects to connect to the manager/text version of Tomcat Manager, rather than the manager/html version that I usually configure by default. You'll need a line in your tomcat-users.xml file like the following:
<user username="tomcat" password="pencil" roles="manager-script"/>
(This is in addition to the "manager-gui" role you probably already have set up.)
Once those changes were made, the build and deployment worked just fine.
| Jenkins | 9,277,223 | 57 |
I'm new to Jenkins Pipeline jobs, and I'm facing an issue I cannot solve.
I have a stage with a hardcoded sleep seconds value:
stage ("wait_prior_starting_smoke_testing") {
echo 'Waiting 5 minutes for deployment to complete prior starting smoke testing'
sleep 300 // seconds
}
But I would like to provide the time argument via a job (string) parameter SLEEP_TIME_IN_SECONDS. But whatever I have tried, I am not able to get it to work.
How do you convert a string parameter to the int time argument?
| small improve for this page:
You also can use sleep(time:3,unit:"SECONDS") if you are interested in specifying time unit of your sleep
https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/#sleep-sleep
| Jenkins | 43,912,821 | 55 |
I have handled the Jenkins pipeline steps with try catch blocks. I want to throw an exception manually for some cases. but it shows the below error.
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use new java.io.IOException java.lang.String
I checked the scriptApproval section and there is no pending approvals.
| If you want to abort your program on exception, you can use pipeline step error to stop the pipeline execution with an error. Example :
try {
// Some pipeline code
} catch(Exception e) {
// Do something with the exception
error "Program failed, please read logs..."
}
If you want to stop your pipeline with a success status, you probably want to have some kind of boolean indicating that your pipeline has to be stopped, e.g:
boolean continuePipeline = true
try {
// Some pipeline code
} catch(Exception e) {
// Do something with the exception
continuePipeline = false
currentBuild.result = 'SUCCESS'
}
if(continuePipeline) {
// The normal end of your pipeline if exception is not caught.
}
| Jenkins | 42,718,785 | 55 |
I'm trying to connect jenkins on a github repo.
When I specify the Repo URL jenkins return the following error message:
Failed to connect to repository : Command "git ls-remote -h [email protected]:adolfosrs/jenkins-test.git HEAD" returned status code 128:
stdout:
stderr: Host key verification failed.
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
When using the HTTPS:// Url jenkins returns:
Failed to connect to repository : Failed to connect to
https://github.com/adolfosrs/jenkins-test.git (status = 407)
I could successfully clone the repo at the same machine where jenkins is running and I also run the git ls-remote -h [email protected]:adolfosrs/jenkins-test.git HEAD command. So I have the right SSH at github.
| The problem was that somehow I created the ssh files with the root user.
So the files owner was root.
The solution was just change the ownership to the jenkins user.
chown jenkins id_rsa.pub
chown jenkins id_rsa
| Jenkins | 21,557,998 | 55 |
I'm trying to get Jenkins up and running with a GitHub hosted repository (using the Jenkins Git plugin). The repository has multiple git submodules, so I'm not sure I want to try and manage multiple deploy keys.
My personal GitHub user account is a collaborator of each of the projects I wish to pull in with Jenkins, so I've generated an SSH key within /var/lib/jenkins/.ssh and added it to my personal GitHub account.
However, when I try and add the repository URL to my Jenkins project configuration, I get:
Failed to connect to repository : Command "git ls-remote -h [email protected]:***/***.git HEAD" returned status code 128:
stdout:
stderr: Host key verification failed.
fatal: The remote end hung up unexpectedly
Likewise, when I schedule a build I get:
stderr: Host key verification failed.
fatal: The remote end hung up unexpectedly
I've also tried setting up an SSH config file as outlined here, but to no avail.
Can anyone shed any light? Thanks
EDIT
I should add that I'm running CentOS 5.8
| It looks like the github.com host which jenkins tries to connect to is not listed under the Jenkins user's $HOME/.ssh/known_hosts. Jenkins runs on most distros as the user jenkins and hence has its own .ssh directory to store the list of public keys and known_hosts.
The easiest solution I can think of to fix this problem is:
# Login as the jenkins user and specify shell explicity,
# since the default shell is /bin/false for most
# jenkins installations.
sudo su jenkins -s /bin/bash
cd SOME_TMP_DIR
# git clone YOUR_GITHUB_URL
# Allow adding the SSH host key to your known_hosts
# Exit from su
exit
| Jenkins | 15,314,760 | 55 |
I was wondering how one could change Jenkins' default port 8080. Using linux or windows, this is simply done with the configuration file. But the Mac config file of Jenkins looks completely different from the other ones.
Of course one could pass the --httpPort parameter when starting the server, but I want to do this within a config file.
Is there an option for that?
PS: Passing the Jenkins instance through apache would kinda solve the problem, but I want to change the Jenkins port.
Thanks!
| it looks like the default way is:
#add the default parameters - this will edit /Library/Preferences/org.jenkins-ci.plist
sudo defaults write /Library/Preferences/org.jenkins-ci httpPort 7070
#stop
sudo launchctl unload /Library/LaunchDaemons/org.jenkins-ci.plist
#start
sudo launchctl load /Library/LaunchDaemons/org.jenkins-ci.plist
| Jenkins | 7,139,338 | 55 |
We need to integrate Karma test runner into TeamCity and for that I'd like to give sys-engineers small script (powershell or whatever) that would:
pick up desired version number from some config file (I guess I can put it as a comment right in the karma.conf.js)
check if the defined version of karma runner installed in npm's global repo
if it's not, or the installed version is older than desired: pick up and install right version
run it: karma start .\Scripts-Tests\karma.conf.js --reporters teamcity --single-run
So my real question is: "how can one check in a script, if desired version of package installed?". Should you do the check, or it's safe to just call npm -g install everytime?
I don't want to always check and install the latest available version, because other config values may become incompatible
| To check if any module in a project is 'old':
npm outdated
'outdated' will check every module defined in package.json and see if there is a newer version in the NPM registry.
For example, say xml2js 0.2.6 (located in node_modules in the current project) is outdated because a newer version exists (0.2.7). You would see:
[email protected] node_modules/xml2js current=0.2.6
To update all dependencies, if you are confident this is desirable:
npm update
Or, to update a single dependency such as xml2js:
npm update xml2js
To update package.json version numbers, append the --save flag:
npm update --save
| TeamCity | 16,525,430 | 912 |
Visual Studio 2010 has a Publish command that allows you to publish your Web Application Project to a file system location. I'd like to do this on my TeamCity build server, so I need to do it with the solution runner or msbuild. I tried using the Publish target, but I think that might be for ClickOnce:
msbuild Project.csproj /t:Publish /p:Configuration=Deploy
I basically want to do exactly what a web deployment project does, but without the add-in. I need it to compile the WAP, remove any files unnecessary for execution, perform any web.config transformations, and copy the output to a specified location.
My Solution, based on Jeff Siver's answer
<Target Name="Deploy">
<MSBuild Projects="$(SolutionFile)"
Properties="Configuration=$(Configuration);DeployOnBuild=true;DeployTarget=Package"
ContinueOnError="false" />
<Exec Command=""$(ProjectPath)\obj\$(Configuration)\Package\$(ProjectName).deploy.cmd" /y /m:$(DeployServer) -enableRule:DoNotDeleteRule"
ContinueOnError="false" />
</Target>
| I got it mostly working without a custom msbuild script. Here are the relevant TeamCity build configuration settings:
Artifact paths: %system.teamcity.build.workingDir%\MyProject\obj\Debug\Package\PackageTmp
Type of runner: MSBuild (Runner for MSBuild files)
Build file path: MyProject\MyProject.csproj
Working directory: same as checkout directory
MSBuild version: Microsoft .NET Framework 4.0
MSBuild ToolsVersion: 4.0
Run platform: x86
Targets: Package
Command line parameters to MSBuild.exe: /p:Configuration=Debug
This will compile, package (with web.config transformation), and save the output as artifacts. The only thing missing is copying the output to a specified location, but that could be done either in another TeamCity build configuration with an artifact dependency or with an msbuild script.
Update
Here is an msbuild script that will compile, package (with web.config transformation), and copy the output to my staging server
<?xml version="1.0" encoding="utf-8" ?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Release</Configuration>
<SolutionName>MySolution</SolutionName>
<SolutionFile>$(SolutionName).sln</SolutionFile>
<ProjectName>MyProject</ProjectName>
<ProjectFile>$(ProjectName)\$(ProjectName).csproj</ProjectFile>
</PropertyGroup>
<Target Name="Build" DependsOnTargets="BuildPackage;CopyOutput" />
<Target Name="BuildPackage">
<MSBuild Projects="$(SolutionFile)" ContinueOnError="false" Targets="Rebuild" Properties="Configuration=$(Configuration)" />
<MSBuild Projects="$(ProjectFile)" ContinueOnError="false" Targets="Package" Properties="Configuration=$(Configuration)" />
</Target>
<Target Name="CopyOutput">
<ItemGroup>
<PackagedFiles Include="$(ProjectName)\obj\$(Configuration)\Package\PackageTmp\**\*.*"/>
</ItemGroup>
<Copy SourceFiles="@(PackagedFiles)" DestinationFiles="@(PackagedFiles->'\\build02\wwwroot\$(ProjectName)\$(Configuration)\%(RecursiveDir)%(Filename)%(Extension)')"/>
</Target>
</Project>
You can also remove the SolutionName and ProjectName properties from the PropertyGroup tag and pass them to msbuild.
msbuild build.xml /p:Configuration=Deploy;SolutionName=MySolution;ProjectName=MyProject
Update 2
Since this question still gets a good deal of traffic, I thought it was worth updating my answer with my current script that uses Web Deploy (also known as MSDeploy).
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Build" ToolsVersion="4.0">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Release</Configuration>
<ProjectFile Condition=" '$(ProjectFile)' == '' ">$(ProjectName)\$(ProjectName).csproj</ProjectFile>
<DeployServiceUrl Condition=" '$(DeployServiceUrl)' == '' ">http://staging-server/MSDeployAgentService</DeployServiceUrl>
</PropertyGroup>
<Target Name="VerifyProperties">
<!-- Verify that we have values for all required properties -->
<Error Condition=" '$(ProjectName)' == '' " Text="ProjectName is required." />
</Target>
<Target Name="Build" DependsOnTargets="VerifyProperties">
<!-- Deploy using windows authentication -->
<MSBuild Projects="$(ProjectFile)"
Properties="Configuration=$(Configuration);
MvcBuildViews=False;
DeployOnBuild=true;
DeployTarget=MSDeployPublish;
CreatePackageOnPublish=True;
AllowUntrustedCertificate=True;
MSDeployPublishMethod=RemoteAgent;
MsDeployServiceUrl=$(DeployServiceUrl);
SkipExtraFilesOnServer=True;
UserName=;
Password=;"
ContinueOnError="false" />
</Target>
</Project>
In TeamCity, I have parameters named env.Configuration, env.ProjectName and env.DeployServiceUrl. The MSBuild runner has the build file path and the parameters are passed automagically (you don't have to specify them in Command line parameters).
You can also run it from the command line:
msbuild build.xml /p:Configuration=Staging;ProjectName=MyProject;DeployServiceUrl=http://staging-server/MSDeployAgentService
| TeamCity | 3,097,489 | 236 |
I would like to ask you which automated build environment you consider better, based on practical experience. I'm planning to do some .Net and some Java development, so I would like to have a tool that supports both these platforms.
I've been reading around and found out about CruiseControl.NET, used on stackoverflow development, and TeamCity with its support for build agents on different OS-platforms and based on different programming languages. So, if you have some practical experience on both of those, which one do you prefer and why?
Currently, I'm mostly interested in the ease of use and management of the tool, much less in the fact that CC is open source, and TC is a subject to licensing at some point when you have much projects to run (because, I need it for a small amount of projects).
Also, if there is some other tool that meets the above-mentioned and you believe it's worth a recommendation - feel free to include it in the discussion.
| I have worked on and with Continuous Integration tools since the one that spawned Cruise Control (java version). I've tried almost all of them at some point. I've never been happier than I am with TeamCity. It is very simple to set up and still provides a great deal of power. The build statistics page that shows build times, unit test count, pass rate etc. is very nice. TeamCity's project home page is also very valuable.
For simple .NET projects you can just tell TeamCity where the solution is and what assemblies have tests and that is all it needs (other than source control location). We have also used some complicated MSBuild scripts with it and done build chaining.
I have also gone through two TeamCity upgrades and they were painless.
CruiseControl.NET also works well. It is trickier to set up but it has a longer history so it is easy to find solutions on the web. Since CruiseControl.NET is open source you also have the option of adding or changing whatever you like. I had used CruiseControl.NET since its release and wrote some of the early code for cc.tray (thankfully re-written by someone who knew better).
Cruise, from ThoughtWorks, also looks quite good but I don't see a compelling reason for me to switch. If I were starting a new project I might give it a try, but TeamCity has done a great job of making the simple things simple while making the complex quite painless.
Edit:
We just upgraded to TeamCity 5.0 a few weeks ago and it was another painless upgrade. It let us take advantage of the improved code coverage capabilities and GIT support. We are also now using the personal build and pre-tested commit features that have been in for a while. I just thought I should update the answer to indicate that TeamCity keeps improving and is still easy to use.
| TeamCity | 195,835 | 117 |
I use TeamCity which in turn invokes msbuild (.NET 4). I have a strange issue in that after a build is complete (and it doesn't seem to matter if it was a successful build or not), msbuild.exe stays open, and locks one of the files, which means every time TeamCity tries to clear its work directory, it fails, and can't continue.
This happens almost every time.
I'm really lost on this one, so I'll try to provide as much detail as possible.
Server is an Intel Core i7, 2 GB ram, with Windows Server 2008 standard 64-bit SP2.
In TeamCity, the msbuild runner is configured with the /m command-line parameter (which means to use multiple cores)
The file in question is ALWAYS the same external DLL that is referenced in one of the .NET projects, in the path External Tools\Telerik\Telerik.Reporting.Dll. (There are several other .DLL files included in the External Tools dir in a similar path structure which never cause this problem). Currently this is with the trial version of Telerik reports, in case that makes any difference.
When the issue happens, there are always several msbuild.exe *32 processes listed in Task manager: I believe there are 7. Using Process Explorer, they all look like top-level processes (no parents). They're all using from 20-50MB ram, and 0.0% CPU.
If I wait 1-3 minutes, the msbuild.exe processes exit on their own, and TeamCity can then update the work directory properly.
If I manually terminate the msbuild processes, TeamCity's update will work again immediately.
Indexing services are turned off in Windows (though the prior two points pretty much confirm it's msbuild.exe causing the problem).
There are no special properties on Telerik.reporting.dll. The only SVN property is svn:mime-type = application/octet-stream
Has anyone run across this before?
| Use msbuild with /nr:false.
Briefly: MSBuild tries to do lots of things to be fast, especially with parallel builds. It will spawn lots of "nodes" - individual msbuild.exe processes that can compile projects, and since processes take a little time to spin up, after the build is done, these processes hang around (by default, for 15 minutes, I think), so that if you happen to build again soon, these nodes can be "reused" and save the process setup cost. But you can disable that behavior by turning off nodeReuse with the aforementioned command-line option.
See also:
MSBuild and ConHost remain in memory after parallel build
MSBuild Command-Line Reference
Parallel builds that don't lock custom MSBuild task DLLs
Node Reuse in MultiProc MSBuild
| TeamCity | 3,919,892 | 109 |
A few projects in my client's solution have a post-build event: xcopy the build output to a specific folder. This works fine when building locally. However, in TeamCity, I occasionally get
xcopy [...] exited with code 2
If I use regular copy, it exits with code 1. I expect this has something to do with file locks, although the specific files being copied are not the same, so perhaps just locking on the shared destination directory. I use /y to not prompt on overwriting files.
Why this fails in TeamCity but not locally?
| Even if you provide the /Y switch with xcopy, you'll still get an error when xcopy doesn't know if the thing you are copying is a file or a directory. This error will appear as "exited with code 2". When you run the same xcopy at a command prompt, you'll see that xcopy is asking for a response of file or directory.
To resolve this issue with an automated build, you can echo in a pre-defined response with a pipe.
To say the thing you are copying is a file, echo in F:
echo F|xcopy /y ...
To say the thing you are copying is a directory, echo in D:
echo D|xcopy /y ...
Sometimes the above can be resolved by simply using a copy command instead of xcopy:
copy /y ...
However, if there are non-existent directories leading up to the final file destination, then an "exited with code 1" will occur.
Remember: use the /C switch and xcopy with caution.
| TeamCity | 7,835,304 | 106 |
We have several build machines, each running a single TeamCity build agent. Each machine is very strong, and we'd like to run several build agents on the same machine.
Is this possible, without using virtualization? Are there quality alternatives to TeamCity that support this?
| Yes, it's possible:
Several agents can be installed on a single machine. They function as separate agents and TeamCity works with them as different agents, not utilizing the fact that they share the same machine.
After installing one agent you can install additional one, providing the following conditions are met:
the agents are installed in the separate directories
they have distinctive work and temp directories
buildAgent.properties is configured to have different values for name and ownPort properties
Make sure, there are no build configurations that have absolute checkout directory specified (alternatively, make sure such build configurations have "clean checkout" option enabled and they cannot be run in parallel).
Under Windows, to install additional agents as services, modify [agent dir]\launcher\conf\wrapper.conf
to change the properties to have distinct name within the computer:
wrapper.console.title
wrapper.ntservice.name
wrapper.ntservice.displayname
wrapper.ntservice.description
| TeamCity | 1,789,212 | 87 |
I have a TeamCity server setup to do my CI builds. I'm building and testing a C# solution and running some custom MSBuild tasks. One of these tasks is printing a warning in my build output...
MSBuild command line parameters contains "/property:" or "/p:" parameters. Please use Build Parameteres instead.
I don't understand what this means or how to remove it. It doesn't Google well (with or without the typo). I ran the task from the command line (with /verbosity:diagnostic) and it doesn't appear, so I believe it's a TeamCity message.
The MSBuild task is
<Target Name="InstallDb">
<MakeDir Directories="$(DbPath)" />
<Exec Command="sqlcmd -S .\sqlexpress -i db\OmnyxDatabaseDrop.sql" />
<Exec Command="sqlcmd -S .\sqlexpress -i db\OmnyxDatabaseCreate.sql -v DbPath="$(DbPath)"" />
<Exec Command="sqlcmd -S .\sqlexpress -i db\OmnyxDatabaseProgrammability.sql" />
</Target>
And the relevant TeamCity step information is
MSBuild version: 4.0
MSBuild ToolsVersion: 4.0
Run platform: x64
Targets: InstallDb
Command line parameters: /property:DbPath=%env.DB_PATH%
| You have to add Build Parameters under Properties and environment variables in the configuration
`
So in the command line parameters in the Build Step for MSBUild, remove any property that is specified as /p: and add each of those to the Build Parameters ( screenshot above) and give the values
| TeamCity | 6,218,486 | 80 |
I've got a PowerShell script as follows
##teamcity[progressMessage 'Beginning build']
# If the build computer is not running the appropriate version of .NET, then the build will not run. Throw an error immediately.
if( (ls "$env:windir\Microsoft.NET\Framework\v4.0*") -eq $null ) {
throw "This project requires .NET 4.0 to compile. Unfortunately .NET 4.0 doesn't appear to be installed on this machine."
##teamcity[buildStatus status='FAILURE' ]
}
##teamcity[progressMessage 'Setting up variables']
# Set up variables for the build script
$invocation = (Get-Variable MyInvocation).Value
$directorypath = Split-Path $invocation.MyCommand.Path
$v4_net_version = (ls "$env:windir\Microsoft.NET\Framework\v4.0*").Name
$nl = [Environment]::NewLine
Copy-Item -LiteralPath "$directorypath\packages\NUnit.2.6.2\lib\nunit.framework.dll" "$directorypath\Pandell.Tests\bin\debug" -Force
##teamcity[progressMessage 'Using msbuild.exe to build the project']
# Build the project using msbuild.exe.
# Note we've already determined that .NET is already installed on this computer.
cmd /c C:\Windows\Microsoft.NET\Framework\$v4_net_version\msbuild.exe "$directorypath\Pandell.sln" /p:Configuration=Release
cmd /c C:\Windows\Microsoft.NET\Framework\$v4_net_version\msbuild.exe "$directorypath\Pandell.sln" /p:Configuration=Debug
# Break if the build throws an error.
if(! $?) {
throw "Fatal error, project build failed"
##teamcity[buildStatus status='FAILURE' ]
}
##teamcity[progressMessage 'Build Passed']
# Good, the build passed
Write-Host "$nl project build passed." -ForegroundColor Green
##teamcity[progressMessage 'running tests']
# Run the tests.
cmd /c $directorypath\build_tools\nunit\nunit-console.exe $directorypath\Pandell.Tests\bin\debug\Pandell.Tests.dll
# Break if the tests throw an error.
if(! $?) {
throw "Test run failed."
##teamcity[buildStatus status='FAILURE' ]
}
##teamcity[progressMessage 'Tests passed']
From what I'm lead to believe, an uncaught Throw will result in an exit code of 1, but unfortunately TeamCity is saying otherwise.
[19:32:20]Test run failed.
[19:32:20]At C:\BuildAgent\work\e903de7564e599c8\build.ps1:44 char:2
[19:32:20]+ throw "Test run failed."
[19:32:20]+ ~~~~~~~~~~~~~~~~~~~~~~~~
[19:32:20] + CategoryInfo : OperationStopped: (Test run failed.:String) [],
[19:32:20] RuntimeException
[19:32:20] + FullyQualifiedErrorId : Test run failed.
[19:32:20]
[19:32:20]Process exited with code 0
[19:32:20]Publishing internal artifacts
[19:32:20][Publishing internal artifacts] Sending build.finish.properties.gz file
[19:32:20]Build finished
It might also be important to note that my Execution Mode is set to Execute .ps1 script with "-File" argument.
I tried changing it to Put script into PowerShell stdin with "-Command -" arguments, but then it failed with an exit code of 1 even with passing tests. I'm sure that running it as -File is going to be the right way.
If I open up the script located at C:\BuildAgent\work\e903de7564e599c8\build.ps1 and run it manually in CMD, it does the same thing... I.e., the failing tests fail, and the %errorlevel% is still 0.
Yet, if I run it in PowerShell and call $LASTEXITCODE, it returns the right code every time.
| This is a known issue with PowerShell. Executing a script with -file returns an exit code of 0 when it shouldn't.
(Update: The links below no longer work. Please look for, or report, this problem on PowerShell: Hot (1454 ideas) – Windows Server)
https://connect.microsoft.com/PowerShell/feedback/details/777375/powershell-exe-does-not-set-an-exit-code-when-file-is-used
https://connect.microsoft.com/PowerShell/feedback/details/750653/powershell-exe-doesn-t-return-correct-exit-codes-when-using-the-file-option
Since using -command wasn't working for you, you could try adding a trap at the top of the script:
trap
{
write-output $_
##teamcity[buildStatus status='FAILURE' ]
exit 1
}
The above should result in a proper exit code when an exception is thrown.
| TeamCity | 15,777,492 | 79 |
I'm setting up TeamCity as my build server.
I have my project set up, it is updating correctly from subversion, and building ok.
So what's next?
Ideally, I'd like to have it auto deploy to a test server, with a manual deploy to a live/staging server.
What's the best way to go about this?
Since I am using C#/ASP.Net, should I add a Web Deployment project to my solution?
| This article explains how to call Microsoft's WebDeploy tool from TeamCity to deploy a web application to a remote web server. I've been using it to deploy to a test web server and run selenium tests on check-in.
http://www.mikevalenty.com/automatic-deployment-from-teamcity-using-webdeploy/
Install WebDeploy
Enable Web config transforms
Configure TeamCity BuildRunner
Configure TeamCity Build Dependencies
The MSBuild arguments that worked for my application were:
/p:Configuration=QA
/p:OutputPath=bin
/p:DeployOnBuild=True
/p:DeployTarget=MSDeployPublish
/p:MsDeployServiceUrl=https://myserver:8172/msdeploy.axd
/p:username=myusername
/p:password=mypassword
/p:AllowUntrustedCertificate=True
/p:DeployIisAppPath=ci
/p:MSDeployPublishMethod=WMSVC
| TeamCity | 1,987,507 | 76 |
New to TeamCity. I have multiple build steps. Step 3 generates an id that is needed in step 4. What is the best way to pass the id (a string) between step 3 and step 4? The build steps are written in Ruby. Can I set an environment variable?
| Yes, you can set an environment variable in one build step and use it in the following step. You will need to use a service message in your build script as described here http://confluence.jetbrains.net/display/TCD65/Build+Script+Interaction+with+TeamCity#BuildScriptInteractionwithTeamCity-AddingorChangingaBuildParameterfromaBuildStep to dynamically update a build parameter, which you can use in the next step. Note, that it won't be available in the step that generates it, only in the next one.
Note that to set the variable, it must be written out somehow (echo for bash command-line, write-host for Powershell), in quotes. Example:
echo "##teamcity[setParameter name='env.ENV_AAA' value='aaaaaaaaaa']"
and to use this variable write %env.ENV_AAA% in the box in the next build step (Atleast in TeamCity 9.1.7))
| TeamCity | 8,219,493 | 75 |
Is there a way to restart a TeamCity server running on Windows from its web interface? I haven't found a button or documentation whether this is possible.
| This is now available in 2017.2 via the Diagnostics page of the admin area:
Now there is also the server Restart button on the Administration | Diagnostics page.
/admin/admin.html?item=diagnostics#serverRestart
| TeamCity | 28,473,774 | 75 |
I have an ASP.NET Core project that builds properly with Visual Studio, but it doesn't build under MSBuild.
It doesn't find all the common libraries (system, etc.).
I'm using TeamCity and part of the build process is a nuget restore.
I tried to do the same steps as TeamCity, but manually with MSBuild, and it failed, not finding the libraries.
I added a dotnet restore step and then it worked.
So, what is the difference between a nuget restore and a dotnet restore?
| Both nuget restore and dotnet restore are roughly the same: They perform a NuGet restore operation.
The only difference: dotnet restore is a convenience wrapper to invoke dotnet msbuild /t:Restore which invokes an MSBuild-integrated restore. This only works on MSBuild distributions that include NuGet, such as Visual Studio 2017 (full Visual Studio, build tools) or Mono 5.2+ (=> msbuild /t:Restore) and the .NET Core SDK which provides this convenience command.
At the moment, there are two ways of how NuGet packages can be used in projects (three actually, but let's ignore project.json on UWP for the moment):
packages.config: The "classic" way of referencing NuGet packages. This assumes NuGet is a separate tool and MSBuild doesn't know anything about NuGet. A NuGet client such as nuget.exe or Visual Studio-integrated tooling sees the packages.config file and downloads the referenced packages into a local folder on restore. A package install modifies the project to reference assets out of this local folder. So a restore for a packages.config project only downloads the files.
PackageReference: The project contains MSBuild items that reference a NuGet package. Unlike packages.config, only the direct dependencies are listed and the project file does not directly reference any assets (DLL files, content files) out of packages. On restore, NuGet figures out the dependency graph by evaluating the direct and transitive dependencies, makes sure all packages are downloaded into the user's global package cache (not solution-local so it is only downloaded once) and write an assets file into the obj folder that contains a list of all packages and assets that the project uses, as well as additional MSBuild targets if any package contains build logic that needs to be added to a project. So a NuGet restore may download packages if they are not already in the global cache and create this assets file. In addition to package references, the project can also reference CLI tools, which are NuGet packages containing additional commands that will be available for the dotnet in the project directory.
The msbuild-integrated restore only works for PackageReference type projects (.NET Standard, .NET Core by default, but it is opt-in for any .NET project) and not for packages.config projects. If you use a new version of nuget.exe(e.g. 4.3.0), it is able to restore both project types.
Your error about missing types is a bit more interesting: The "reference assemblies" (libraries that are passed as input to the compiler) are not installed on the system but come via NuGet packages. So as long as the NuGet packages are missing from the global package cache or the obj/project.assets.json file has not been generated by a restore operation, fundamental types like System.Objectwill not be available to the compiler.
| TeamCity | 45,897,271 | 75 |
I have a VS 2012 web project /sln that I am trying to build in TeamCity. it uses .NET 4.5 which is installed on TeamCity.
The TeamCity server has VS 2010 installed only.
I get this error when the build runs:
C:\BuildAgent\work\d5bc4e1b8005d077\CUSAAdmin.Web\CUSAAdmin.Web.csproj(799, 3):
error MSB4019:
The imported project
"C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\WebApplications\Microsoft.WebApplication.targets" was not found.
Confirm that the path in the <Import> declaration is correct, and that the file exists on disk. Project CUSAAdmin.Web\CUSAAdmin.Web.csproj failed.
Project CUSAAdmin.sln failed.
It is trying to use Visual Studio 2012 (v11.0) to build.
I have set the VisualStudioVersion to be 10 in the build.xml though??
<Target Name="BuildPackage">
<MSBuild Projects="CUSAAdmin.sln" ContinueOnError="false"
Targets="Rebuild"
Properties="Configuration=$(Configuration); VisualStudioVersion=10.0" />
As well inside the project it is defaulting to VS2010
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
<VSToolsPath
Condition="'$(VSToolsPath)' == ''">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath>
| Actually, you don't need to install Visual Studio on your CI server. You only need to copy a few folders from a development machine to the same location on the CI server.
VS 2015:
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\Web
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v14.0\WebApplications
VS 2013:
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\Web
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\WebApplications
VS 2012:
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\Web
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\WebApplications
VS 2010:
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\WebApplications
.NET 4.6:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6
.NET 4.5.2:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.2
.NET 4.5.1:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.1
.NET 4.5:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5
.NET 4.0.1:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0.1
.NET 4.0:
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0
Or, as Matt suggested, you could copy them into a subdirectory of your project and alter the <MSBuildExtensionsPath32> location in your MSBuild (typically .csproj or .vbproj) file.
Once you have done this, your project will compile. You should still set the VisualStudioVersion explicitly to the one you are using just to be sure it is set right.
NOTE: This solution works for all project types (including web projects). For a web site (that has no project file), I ended up installing the Windows SDK matching the .NET SDK version I am using, because there were missing registry keys that were causing it not to build.
| TeamCity | 15,419,610 | 72 |
I have put a library that my team uses into a nuget package that is deployed from TeamCity into a network folder. I cannot debug into this code though! SymbolSource is one solution I have read about but I would much rather find some way to have access to the .pdb/source files directly from TeamCity. Does anyone know how to do this?
Edit. When I check 'Include Symbols and Source' in the Nuget Pack build step, TeamCity creates a .Symbol.nupkg in addition to the .nupkg file in the network folder. The .Symbol.nupkg contains the src and the .pdb file.
Edit. I unchecked 'Include Symbols and Source' on TeamCity and added the following to my nuspec file:
<files>
<file src="..\MyLibrary\bin\release\MyLibrary.dll" target="lib\net40" />
<file src="..\MyLibrary\bin\release\MyLibrary.pdb" target="lib\net40" />
<file src="..\MyLibrary\*.cs" target="src" />
<file src="..\MyLibrary\**\*.cs" target="src" />
</files>
This added the dll, the pdb, and the source files for my library in the nuget package and didn't generate a .Symbols file which I think is only needed for symbol servers.
| Traditional method
Put the pdb in the NuGet package alongside the dll.
Add the source code to the Debug Source Files for the solution that references the package.
This means you'll be able to step through code and view exceptions, but you might have to find a file on disk and open it before you can set a breakpoint. Obviously you need to be careful that the source is at the right revision.
More detail on step
If you're currently packaging without a Nuspec, you'll need to create a Nuspec, then add the pdb to the list of files in the lib folder "NuGet spec" may be a useful command for generating the initial spec as defined in NuGet docs. Then ensure the Team City Nuget Pack step is referencing your new nuspec.
More detail on step 2
When you have a solution open, right click on Solution, select Properties...Common Properties...Debug Source Files, and add the root source directory for the relevant binary reference. Or see MSDN.
Note, you can't open the solution properties while debugging.
Still not hitting breakpoints?
Try disabling this from Tools->Options:
Modern way for public or private repos
To ensure the exact version of the source is available, embed it at build time.
From Visual Studio 2017 15.5+ you can add the EmbedAllSources property:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<EmbedAllSources>true</EmbedAllSources>
Modern way for public repos
To keep your nuget and library size small, you can use the sourcelink package.
It generates a pdb that directs the debugger to the correct version of the file from your VCS provider (e.g. GitHub, BitBucket).
| TeamCity | 21,857,780 | 71 |
I installed TeamCity and got it working against my project. However, I have since realized that I don't want it the administration page to be configured on port 80. I'm going to have other websites on that server that I want on the default port. How do I change the configured port?
I wandered around the configurations a bit and looked through the administration settings but couldn't figure it out.
|
The port number can be edited in the <TeamCity home>/conf/server.xml file, line <Connector port="8111" protocol="HTTP/1.1".
from Installing and Configuring the TeamCity server
| TeamCity | 2,387,375 | 71 |
I need to recover/reset the admin password for JetBrain's TeamCity.
I have full RDP access to the server so no problems there. It's just been 2 months since we used it so now I have forgotten my login - my usual ones don't work.
It is setup without a database at the moment, so was hoping the usernames would just be in a file somewhere, but no luck finding it so far.
| From TeamCity 8 you can log in as a super user and change the password that way. You just need to use an empty username and last occurrence of the "super user authentication token" found in the logs\teamcity-server.log file as your password.
Please see the following for more information:
TeamCity 8 - http://confluence.jetbrains.com/display/TCD8/Super+User
TeamCity 9 - http://confluence.jetbrains.com/display/TCD9/Super+User
TeamCity 10 - https://confluence.jetbrains.com/display/TCD10/Super+User
| TeamCity | 506,115 | 69 |
I've got a set of test cases, some of which are expected to throw exceptions. Because of this, I have have set the attributes for these tests to expect exceptions like so:
[ExpectedException("System.NullReferenceException")]
When I run my tests locally all is good. However when I move my tests over to the CI server running TeamCity, all my tests that have expected exceptions fail. This is a known bug.
I am aware that there is also the Assert.Throws<> and Assert.Throws methods that NUnit offers.
My question is how can I make use of these instead of the attribute I'm currently using?
I've had a look around StackOverflow and tried a few things none of which seem to work for me.
Is there a simple 1 line solution to using this?
| I'm not sure what you've tried that is giving you trouble, but you can simply pass in a lambda as the first argument to Assert.Throws. Here's one from one of my tests that passes:
Assert.Throws<ArgumentException>(() => pointStore.Store(new[] { firstPoint }));
Okay, that example may have been a little verbose. Suppose I had a test
[Test]
[ExpectedException("System.NullReferenceException")]
public void TestFoo()
{
MyObject o = null;
o.Foo();
}
which would pass normally because o.Foo() would raise a null reference exception.
You then would drop the ExpectedException attribute and wrap your call to o.Foo() in an Assert.Throws.
[Test]
public void TestFoo()
{
MyObject o = null;
Assert.Throws<NullReferenceException>(() => o.Foo());
}
Assert.Throws "attempts to invoke a code snippet, represented as a delegate, in order to verify that it throws a particular exception." The () => DoSomething() syntax represents a lambda, essentially an anonymous method. So in this case, we are telling Assert.Throws to execute the snippet o.Foo().
So no, you don't just add a single line like you do an attribute; you need to explicitly wrap the section of your test that will throw the exception, in a call to Assert.Throws. You don't necessarily have to use a lambda, but that's often the most convenient.
| TeamCity | 3,407,765 | 66 |
I'm starting a small open source project, myself being the sole contributor for the time. Still, I think a continuous integration setup would be useful to detect whether I broke the build.
Is there a free, hosted continuous integration server that is suitable for very small projects? Googling turned up CodeBetter, but I'm not sure they'll accept a one-man project that is just starting up.
I prefer TeamCity, but I'm open to suggestions.
Note - a hosted solution is a must for me. I don't want to setup and maintain a continuous integration server, so answers like "TeamCity" or "CruiseControl" are simply irrelevant.
Specific requirements:
I am hosting my project at GitHub, so the continuous integration server needs Git integration
I would like the continuous integration server to run .NET integration (unit) tests
Nice to have - I also need access to a MySQL server (although I could modify the tests to use embedded SQLite, they currently run against an external MySQL server).
| AppVeyor is well integrated with Github, free for open-source projects and really easy to set up.
Builds are configured using YAML or UI. Free accounts are limited to one build at a time. Deployment to NuGet is supported, as well as project and account feeds. It is deeply integrated with GitHub, for example allows creating releases. It supports build matrices, AssemblyInfo patching, rolling builds, build prioritization, status badges, build notifications etc.
Travis is well-known CI (and seems to be the most popular hosted CI by far), now it supports building C#, F# and VB projects too. The caveat is that it supports only Linux and Mono and it's in beta ("may be removed or altered at any time").
MyGet is a hosted package server, but now it supports Build Services too (currently preview) and other features. It's free for public feeds (500 MB max) and has slightly better features for approved open-source projects (bigger storage and gallery). Build service is optimized for packages: NuGet feed, MyGet feeds, SymbolSource integration etc.
| TeamCity | 1,991,071 | 66 |
I've got an asp.net mvc deployment package that I'm trying to build with team city. The package builds without any problems, but the bin folder contains file that are not needed (and cause the site to fail when present).
If I build the same package from visual studio the additional files are not present.
The additional files are:
Microsoft.VisualBasic.Activities.Compiler.dll
mscorlib.dll
normidna.nlp
normnfc.nlp
normnfd.nlp
normnfkc.nlp
normnfkd.nlp
System.Data.dll
System.Data.OracleClient.dll
System.EnterpriseServices.dll
System.EnterpriseServices.Wrapper.dll
System.Transactions.dll
What can I do to prevent these additional assemblies and .nlp files from being included in the package?
UPDATE
After a bit more digging through log files I've found that the _CopyFilesMarkedCopyLocal build task is copying the files into the bin directory. The odd thing is that the assemblies are not marked as copy local.
| After a bunch more digging around I noticed that the build server had the .Net framework on, but not the framework SDK. After installing the SDK on the build server the additional assemblies were no longer added.
| TeamCity | 5,604,221 | 63 |
I'm looking to set up a TeamCity server for continuously building a .NET web application. I already have hosting, so I don't want to get a whole new hosting account such as AppHarbor.
I don't maintain my own physical server, nor do I want to.
I also don't want to have to pay $50 or more per month for an entire dedicated Windows machine, just to host TeamCity.
I really don't care if it's slow and on a shared machine, as it's just continuous build which will be running in the background.
I'll want to have the outputs automatically deployed to a server of my choice through FTP.
Is there anyone on the market providing hosted TeamCity environments?
| AppVeyor CI provides hosted continuous integration for .NET developers.
Disclaimer: I'm the developer of this service.
| TeamCity | 7,884,213 | 62 |
I'm wondering how to select the branch to build against using Team City 8.1.
My VCS root (Git) is set to Default: "master" and Branch specifications are
+:refs/heads/develop
+:refs/heads/feature/*
+:refs/heads/hotfix/*
+:refs/heads/master
+:refs/heads/release/*
I have a CI build set up that automatically builds anything that is checked in, which is working exactly how I want.
What I'd like to do is create a scheduled QA build/deployment against the "develop" branch. I see that if I click the ellipsis next to the run button, I can choose the branch on the "Changes" tab, but I'm unable to determine how to make this "stick". Is this possible, or am I going about this wrong?
Thanks,
Joe
| Based on @biswajit-86 's feedback and some other information I found while googling this, I was able to get this to work. Here's what I did (image-heavy, sorry). It's based on Team City 8.2 which seems to be set up a little differently than the examples I came across.
1) Set up a VCS root. Key here is the %BranchName% parameter.
2) Create a Build template and use the VCS root that was just created. I also added an MSBuild step as all of my builds need to run this.
3) Create a new build, based on the template. As you can see here, the %BrachName% parameter that was created in step 1 is available.
4) If you need to change this later, it's available here
And that's pretty much it. For my CI build, I left the branch name empty so any branch that is checked in triggers the MSBuild step. For my QA build, I pass in "develop" as shown here and I have this set up on a daily schedule. I also have a "release" build set up, but based on our naming conventions it looks like I need to update the build to point to the specific branch per release.
| TeamCity | 23,415,704 | 61 |
We are a mostly MS shop at work doing .NET LOB development. We also use MS Dynamics for our CRM app... all the devs are currently using VS/SQL Server 2008. We also use VSS, but everyone hates it at work and that is quickly on its way out.
We are begining our initiative for TDD implementation across the team (~dozen ppl). I've gotten TeamCity setup and have my first automated builds running succesfully using the 2008 sln builder and also using SVN that a co-worker had setup who is doing the source control analysis. When demoing to managament, I think they started to buy into my snake oil and threw out the suggestions of looking into TFS.
This threw a wrench in what I had planned for our TDD architecture; In a good way though, because I had always assumed that TFS was just too expensive and not worth it for our team (and i've seen the same in other shops i've worked at / know of). I do feel like MS is years behind in the TDD/CI area and that the third party products were probably much better and more mature... I still need to do a lot of research, but I figured I'd come here to see if anyone has actually used both systems.
I realize the TFS encompasses a lot more then just a build server... but I didn't want to make this too broad of a question at least on purpose. What are the practical pros/cons of using TFS/TFB instead of TeamCity - e.g. which benefits would we lose/gain? Has anyone here actually used both systems (TFS for TDD/CI and TeamCity/SVN) and can speak from practical standpoint?
I've done some searching on this topic, and one post I found here on SO mentioned that the cons of TFB was it only supported MSBuild. I was planning on using FinalBuilder with TeamCity; and it appears it also supports TFS as well...
Thanks for any advice
EDIT: Has anyone used TFS as their Build/CI server and can tell of success/failure stories?
| We are a small development shop, and decided that Team Foundation Server carries too much overhead for us. We used to write custom MSBuild scripts to run from the command line, but after we discovered TeamCity, we moved our entire build process over to it.
We've found TeamCity to be easy to use and configure, and JetBrains provides excellent support and documentation. They are also on a much faster release and update cycle than Microsoft.
Their support for SVN source control is excellent, and we like the fact that they support both MSTest and NUnit for unit testing.
We also liked the fact that the TeamCity Professional edition was free, so we could evaluate it to see if it worked for us. We haven't hit the number of project configurations (20) that would require us to upgrade to the Enterprise edition.
| TeamCity | 2,239,249 | 60 |
I've got an existing C# 4 project which I've checked the test coverage for by using TestDriven.Net and the Visual Studio coverage feature, i.e. Test With -> Coverage from the context menu.
The project contains some code I don't want covered, and I've solved that by adding the [ExcludeFromCodeCoverage] for those types and methods.
We've just upgraded TeamCity to 6.0.3, and I've added dotCover coverage to the NUnit build step.
I've managed to remove coverage for external assemblies such as NHibernate in the "Filters" section (by explicitly state the assemblies for which I want coverage), but I'm struggling with how to exclude types and methods from covered assemblies.
| Ok, Martin, I figured it out! It only took an hour of randomly poking at the filter syntax... when the documentation says to add a filter like this
+:myassembly=*;type=*;method=***
They really mean this... where anything in <> is replaced entirely by you and anything else is a literal
+:<myassembly>;type=<filter>;method=<filter>
So, the filter I wanted was to include a single assembly (from a bunch of assemblies) and then exclude a few namespaces in that assembly. I wrote
+:Omnyx.Scanner
-:Omnyx.Scanner;type=Omnyx.Scanner.Simulation.*
-:Omnyx.Scanner;type=Omnyx.Scanner.ToolsCommon.*
| TeamCity | 5,631,533 | 56 |
In Husdon/Jenkins, I can setup notifications when the build is broken to email the user(s) that made the checkins that broke the build. How do I do this in Teamcity?
I am aware that individual users can setup email notifications for themselves via the Teamcity interface (for when the build is broken), but I ONLY want emails sent to the users that broke the build, also I don't want the requirement that every individual user have to update their Teamcity settings.
|
Open TeamCity in your browser.
Browse to Administration > Users and Groups > Groups
Click on the group name All Users
Select the tab Notification Rules (you see the Email notifier rules by
default)
Click on Add new rule
choose in the column Watch the
option Builds affected by my
changes
choose in the column Send
notification when the checkbox The
build fails and Ignore failures
not caused by my changes
Save this new notification rule with klick on the Save button.
A notification rule created that way works for all users. That's because the notification rule was created in the administration section within the group All Users, and not within one users personal notification settings. This works also in earlier versions of TeamCity, e.g. in 5.x.
The user still has the option to define additional rules if needed.
| TeamCity | 6,180,772 | 55 |
I am trying to get a build process set up in TeamCity 5, and I am encountering an access denied error when trying to copy some files. I see that my build agent is running as "SYSTEM" now, and I think that's part of the problem. I'd like to change that user identity. The trouble is that I can't figure out how to change those settings on the build agent. How can I change the build user identity?
|
Open the services list (Start -> Run -> services.msc)
Find the "Team City Build Agent" service
Open the properties dialog for the service (right click, Properties)
Choose the "Log On" tab
Change the identity of the user running the service by choosing "this account" and enter the password.
| TeamCity | 2,485,446 | 54 |
I am working on upgrading our TeamCity projects from VS2012 to VS2015 and I am running into an issue compiling our MVC application.
Old MSBuild (v4.0.30319.34209) generates a file in the obj directory called MyApplication.Web.Mvc.dll.licenses which apparently is required for building, but we have no idea what the file is actually used for.
New MSBuild (v14.0.23107.0) does not create this MyApplication.Web.Mvc.dll.licenses file, so the build fails with the following error:
CSC error CS1566: Error reading resource 'MyApplication.Web.Mvc.dll.licenses'
-- 'Could not find file 'C:\BuildAgent\work\58ddf5f1234d8c8a\application\MyApplication\MyApplication.Web.Mvc\obj\Release\MyApplication.Web.Mvc.dll.licenses'.'
I have been running the builds manually via cmd on the machine, and the dll.licenses file gets created whenever running the build using the old msbuild, just not the new one.
The file gets created on the development machines running VS2015, but not on the Teamcity build server. So it seems to me that something else is out of date?
| After a bit more googling, I stumbled upon this thread on MSDN.
The solution suggested here is to install the Windows 10 SDK. We did this on our TeamCity build server running Windows Server 2012 R2 using the default installation options, and after a reboot, our build was working again.
Hope this helps :)
| TeamCity | 32,377,302 | 52 |
I have created a Nuget Server using Teamcity (running on a virtual machine in internet) and created the build that publishes a package into it.
I also have another project that needs to use that package. This project is built on teamcity as well. On my local Visual Studio I added the nuget feed uri, installed the package and everything works fine. But when I try to build it on teamcity it says that "Package not found".
So my question is : "How to add the custom nuget feed to TeamCity build?"
| The NuGet package sources are configured through Visual Studio, but they're stored in a per-user configuration file, found at c:\Users\$USER\AppData\Roaming\NuGet\NuGet.config. The entry for the TeamCity package source needs to be added to the config file of the build agent user that's running your builds.
On your local machine, open the Nuget.config file for your user
Copy the entry for the TeamCity package source to the clipboard
On the build agent, open the NuGet.config file for the user that's executing your TeamCity builds
Paste in the TeamCity package source entry. Save & quit.
Run the build again. It should now be able to find the package.
EDIT: ladenedge documents a good solution that didn't exist when I originally answered this question. The solution is especially useful if you don't have admin access to the build agent or want to configure package sources on a per-project basis.
| TeamCity | 14,548,324 | 50 |
I'm having a problem on my TeamCity CI build server where during compilation I get the following error:
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets(2342, 9): error MSB3086: Task could not find "AL.exe" using the SdkToolsPath "" or the registry key "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v7.0A". Make sure the SdkToolsPath is set and the tool exists in the correct processor specific location under the SdkToolsPath and that the Microsoft Windows SDK is installed
I've found similar reports from a year ago when people were upgrading to .NET 3.5, for example this one. In that case, installing the latest SDK solved the issue, however I have already installed the latest SDK (Microsoft Windows SDK for Windows 7 and .NET Framework 4) on my build server. The MSBuild tools are all there on the server, in a folder called
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319
and AL.exe exists in
C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\NETFX 4.0 Tools
However the registry key mentioned in the error message does not exist. So, it seems like there is something wrong with the installation/configuration of MSBuild. This error only happens for projects that have embedded resources, which require AL.exe.
| As you have install the latest SDK (I'm assuming that's v7.1)
Go to "Microsoft Windows SDK v7.1" from the Start menu
Select "Windows SDK 7.1 Command Prompt" and enter
cd Setup
WindowsSdkVer -version:v7.1
This will tell msbuild to use that version of the tools without needing to do any scary registry editing.
| TeamCity | 2,986,440 | 49 |
I'm trying to deploy one of the web projects in my solution to a server. I am using msbuild on TeamCity like so:
msbuild MySolution.sln /t:WebSite:Rebuild /p:DeployOnBuild=True /p:PublishProfile=Prod ...
However, when I run it, msbuild still tries to build my WebService project, even though my WebSite project does not depend on it (but it does depend on a Services project also in the solution). How do only publish one project, aka just WebSite?
I have also tried building the project file using
msbuild WebSite/WebSite.csproj /p:DeployOnBuild=True ...
but it then complains that it can't restore packages:
[07:47:17]WebSite\WebSite.csproj.teamcity: Build target: Build
[07:47:17][WebSite\WebSite.csproj.teamcity] RestorePackages
[07:47:17][RestorePackages] Exec
[07:47:17][Exec] C:\TeamCity\buildAgent\work\cab8a3d752df3a51\.nuget\NuGet.targets(90, 15): error MSB4064: The "LogStandardErrorAsError" parameter is not supported by the "Exec" task. Verify the parameter exists on the task, and it is a settable public instance property.
[07:47:17][Exec] C:\TeamCity\buildAgent\work\cab8a3d752df3a51\.nuget\NuGet.targets(89, 9): error MSB4063: The "Exec" task could not be initialized with its input parameters.
[07:47:17][WebSite\WebSite.csproj.teamcity] Project WebSite\WebSite.csproj.teamcity failed.
When I disable NuGet Package Restore, CoreCompile (Csc) fails with errors I've never heard of and shouldn't be happening:
[07:54:43]WebSite\WebSite.csproj.teamcity: Build target: Build (13s)
[07:54:55][WebSite\WebSite.csproj.teamcity] CoreCompile
[07:54:55][CoreCompile] Csc
[07:54:56][Csc] Areas\Api\Services\TripService.cs(19, 104): error CS0241: Default parameter specifiers are not permitted
[07:54:56][Csc] Helpers\StatisticsUtility.cs(11, 35): error CS1031: Type expected
[07:54:56][Csc] Helpers\StatisticsUtility.cs(11, 53): error CS1002: ; expected
[07:54:56][Csc] Helpers\StatisticsUtility.cs(16, 28): error CS1519: Invalid token '(' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(16, 37): error CS1519: Invalid token ',' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(17, 27): error CS1519: Invalid token '(' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(17, 32): error CS1519: Invalid token ')' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(23, 17): error CS1519: Invalid token 'for' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(23, 26): error CS1519: Invalid token '<=' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(23, 45): error CS1519: Invalid token '-' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(23, 51): error CS1519: Invalid token '++' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(24, 34): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
[07:54:56][Csc] Helpers\StatisticsUtility.cs(24, 37): error CS1519: Invalid token '==' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(24, 51): error CS1519: Invalid token ')' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(24, 63): error CS1519: Invalid token '++' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(25, 41): error CS1519: Invalid token '>' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(25, 53): error CS1519: Invalid token ')' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(27, 36): error CS1519: Invalid token '=' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(27, 48): error CS1519: Invalid token ';' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(28, 36): error CS1519: Invalid token '=' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(29, 37): error CS1519: Invalid token '=' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(29, 48): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
[07:54:56][Csc] Helpers\StatisticsUtility.cs(29, 50): error CS1519: Invalid token ';' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(30, 33): error CS1519: Invalid token '=' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(30, 44): error CS0270: Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
[07:54:56][Csc] Helpers\StatisticsUtility.cs(30, 50): error CS1519: Invalid token ';' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\StatisticsUtility.cs(32, 21): error CS0116: A namespace does not directly contain members such as fields or methods
[07:54:56][Csc] Helpers\StatisticsUtility.cs(35, 50): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\StatisticsUtility.cs(38, 21): error CS0116: A namespace does not directly contain members such as fields or methods
[07:54:56][Csc] Helpers\StatisticsUtility.cs(40, 50): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\StatisticsUtility.cs(42, 21): error CS1022: Type or namespace definition, or end-of-file expected
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(8, 59): error CS1031: Type expected
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(8, 80): error CS1002: ; expected
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(10, 55): error CS1519: Invalid token '(' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(10, 60): error CS1520: Class, struct, or interface method must have a return type
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(10, 82): error CS1002: ; expected
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(13, 23): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(15, 60): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(18, 23): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(20, 25): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(23, 28): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(26, 28): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(29, 24): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(29, 84): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(32, 28): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(35, 9): error CS1022: Type or namespace definition, or end-of-file expected
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(23, 26): error CS0101: The namespace '<global namespace>' already contains a definition for '?'
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(26, 26): error CS0101: The namespace '<global namespace>' already contains a definition for '?'
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(29, 22): error CS0101: The namespace '<global namespace>' already contains a definition for '?'
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(29, 83): error CS0101: The namespace '<global namespace>' already contains a definition for '?'
[07:54:56][Csc] Helpers\UrlHelperExtensions.cs(32, 26): error CS0101: The namespace '<global namespace>' already contains a definition for '?'
[07:54:56][Csc] Controllers\SessionController.cs(13, 51): error CS0241: Default parameter specifiers are not permitted
[07:54:56][Csc] Helpers\JsonNetResult.cs(13, 44): error CS1031: Type expected
[07:54:56][Csc] Helpers\JsonNetResult.cs(13, 72): error CS1041: Identifier expected, 'object' is a keyword
[07:54:56][Csc] Helpers\JsonNetResult.cs(13, 91): error CS1002: ; expected
[07:54:56][Csc] Helpers\JsonNetResult.cs(16, 38): error CS1519: Invalid token '=' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\JsonNetResult.cs(16, 59): error CS1519: Invalid token ';' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\JsonNetResult.cs(17, 64): error CS1519: Invalid token '=' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\JsonNetResult.cs(17, 90): error CS1519: Invalid token ';' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\JsonNetResult.cs(18, 32): error CS1519: Invalid token '=' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\JsonNetResult.cs(18, 46): error CS1519: Invalid token ';' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\JsonNetResult.cs(19, 33): error CS1519: Invalid token ';' in class, struct, or interface member declaration
[07:54:56][Csc] Helpers\JsonNetResult.cs(22, 23): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\JsonNetResult.cs(25, 37): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\JsonNetResult.cs(32, 23): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\JsonNetResult.cs(35, 37): error CS1518: Expected class, delegate, enum, interface, or struct
[07:54:56][Csc] Helpers\JsonNetResult.cs(40, 9): error CS1022: Type or namespace definition, or end-of-file expected
[07:54:56][Csc] Mailers\ITripMailer.cs(13, 132): error CS0241: Default parameter specifiers are not permitted
[07:54:56][Csc] Mailers\TripMailer.cs(54, 85): error CS0241: Default parameter specifiers are not permitted
[07:54:56][Csc] Services\Impl\AuthorizationService.cs(12, 70): error CS0241: Default parameter specifiers are not permitted
[07:54:56][Csc] Services\Impl\AuthorizationService.cs(43, 77): error CS0241: Default parameter specifiers are not permitted
[07:54:56][WebSite\WebSite.csproj.teamcity] Project WebSite\WebSite.csproj.teamcity failed.
| I blogged about this at http://sedodream.com/2013/03/06/HowToPublishOneWebProjectFromASolution.aspx a few months back. I've copied the details here as well, see below.
Today on twitter @nunofcosta asked me roughly the question “How do I publish one web project from a solution that contains many?”
The issue that he is running into is that he is building from the command line and passing the following properties to msbuild.exe.
/p:DeployOnBuild=true
/p:PublishProfile='siteone - Web Deploy'
/p:Password=%password%
You can read more about how to automate publishing at http://sedodream.com/2013/01/06/CommandLineWebProjectPublishing.aspx.
When you pass these properties to msbuild.exe they are known as global properties. These properties are difficult to override and are passed to every project that is built. Because of this if you have a solution with multiple web projects, when each web project is built it is passed in the same set of properties. Because of this when each project is built the publish process for that project will start and it will expect to find a file named siteone – Web Deploy.pubxml in the folder *Properties\PublishProfiles*. If the file doesn’t exist the operation may fail.
Note: If you are interested in using this technique for an orchestrated publish see my comments at https://stackoverflow.com/a/14231729/105999 before doing so.
So how can we resolve this?
Let’s take a look at a sample (see links below). I have a solution, PublishOnlyOne, with the following projects.
ProjA
ProjB
ProjA has a publish profile named ‘siteone – Web Deploy’, ProjB does not. When trying to publish this you may try the following command line.
msbuild.exe PublishOnlyOne.sln /p:DeployOnBuild=true /p:PublishProfile=’siteone – Web Deploy’ /p:Password=%password%
See publish-sln.cmd in the samples.
If you do this, when its time for ProjB to build it will fail because there’s no siteone – Web Deploy profile for that project. Because of this, we cannot pass DeployOnBuild. Instead here is what we need to do.
Edit ProjA.csproj to define another property which will conditionally set DeployOnBuild
From the command line pass in that property
I edited ProjA and added the following property group before the Import statements in the .csproj file.
<PropertyGroup>
<DeployOnBuild Condition=" '$(DeployProjA)'!='' ">$(DeployProjA)</DeployOnBuild>
</PropertyGroup>
Here you can see that DeployOnBuild is set to whatever value DeployProjA is as long as it’s not empty. Now the revised command is:
msbuild.exe PublishOnlyOne.sln /p:DeployProjA=true /p:PublishProfile=’siteone – Web Deploy’ /p:Password=%password%
Here instead of passing DeployOnBuild, I pass in DeployProjA which will then set DeployOnBuild. Since DeployOnBuild wasn’t passed to ProjB it will not attempt to publish.
You can find the complete sample at https://github.com/sayedihashimi/sayed-samples/tree/master/PublishOnlyOne.
| TeamCity | 16,891,530 | 48 |
I want to copy a directory(abc) from domain1/user1 to domain2/user1. any idea how to do this.
e.g robocopy
robocopy \\server1\G$\testdir\%3 \\server2\g$\uploads
and both are on different domains
| Robocopy will use the standard windows authentication mechanism.
So you probably need to connect to the servers using the appropriate credentials before you issue the robocopy command.
You can use net use to do this and you could put that in a batch script.
Note that Windows doesn't like you to connect to the same server with two different sets of credentials (so you can't copy from and to the same server as different users). But that's not what it looks like you need.
Something like this:
net use \\server1\g$ /user:domain1\user1 *
net use \\server2\g$ /user:domain2\user2 *
robocopy \\server1\G$\testdir\%3 \\server2\g$\uploads
Notes:
This is using 'deviceless' connections which will not be recreated at start up (and won't appear with a drive letter in windows explorer).
The asterisk at the end of the net use command means prompt for password, you could hard code the password in there (or get it as a parameter to the script).
Might be worth reading up on net use to make sure it does what you need.
You can probably also remove the network connection to the servers by using this (I haven't tried this with a deviceless connection):
net use \\server1\g$ /delete
net use \\server2\g$ /delete
| TeamCity | 10,346,891 | 47 |
I have a VS solution and as part of a TeamCity Build, we restore packages from both a private NuGet feed (myget) and the public feed (nuget.org). Most packages restore fine, but it hangs on the ones below for WebApi and Mono.Security. This is all working locally in Visual Studio.
[restore] NuGet command: C:\TeamCity\buildAgent\plugins\nuget-agent\bin\JetBrains.TeamCity.NuGetRunner.exe C:\TeamCity\buildAgent\tools\NuGet.CommandLine.DEFAULT.nupkg\tools\NuGet.exe restore C:\TeamCity\buildAgent\work\953bd084b49f7d88\DataFinch.Web.sln -Source https://www.myget.org/F/datafinch/auth/<hidden>/api/v2 -Source https://api.nuget.org/v3/index.json
[11:41:35][restore] Starting: C:\TeamCity\buildAgent\temp\agentTmp\custom_script473789219385667038.cmd
[11:41:35][restore] in directory: C:\TeamCity\buildAgent\work\953bd084b49f7d88
[11:41:35][restore] JetBrains TeamCity NuGet Runner 8.0.37059.9
[11:41:35][restore] Registered additional extensions from paths: C:\TeamCity\buildAgent\plugins\nuget-agent\bin\plugins-2.8
[11:41:35][restore] Starting NuGet.exe 2.8.50926.602 from C:\TeamCity\buildAgent\tools\NuGet.CommandLine.DEFAULT.nupkg\tools\NuGet.exe
[11:41:43][restore] Unable to find version '5.2.3' of package 'Microsoft.AspNet.WebApi.Client'.
[11:41:43][restore] Unable to find version '5.2.3' of package 'Microsoft.AspNet.WebApi.Core'.
[11:41:43][restore] Unable to find version '3.2.3.0' of package 'Mono.Security'.
[11:41:43][restore] Unable to find version '6.0.4' of package 'Newtonsoft.Json'.
[11:41:43][restore] Process exited with code 1
Teamcity config:
| Try using https://www.nuget.org/api/v2instead of https://api.nuget.org/v3/index.json per the nuget docs: https://docs.nuget.org/consume/Command-Line-Reference.
| TeamCity | 32,360,518 | 45 |
Does anyone know where I can find a good tutorial to walk me through how to setup TeamCity CI server? I am new to unit testing and the agile philosophy of development so I could use some help getting my feet wet. I'm working with Asp.NET code using NUnit for my unit tests and would prefer a windows environment for the TeamCity server. Please note that I have no idea how to configure NANT for the build or anything else needed to have continuous builds. I just have unit tested .NET code.
| The folks at DimeCasts.net have a nice TeamCity tutorial.
| TeamCity | 361,386 | 44 |
I'm using teamcity 8.x.x version.I configured my Teamcity for continuous deployment. I'm need a feature branching deployment. I see this document "http://confluence.jetbrains.com/display/TCD8/Working+with+Feature+Branches".
I'm trying this document implementing on my Teamcity. I have a problem.
My deployment config use "OctoPack" (nuget). My nuget package needs build count and branch name. example: 1.0.0.356-feature-1.
I'm try this versioning,
%build.number%-%teamcity.build.vcs.branch.VCS_ROOT_ID% ----> 1.0.0.356-refs/head/feature-1
this version not support nuget versioning. nuget not comparative "/".
I need this,
%build.number%-%teamcity.build.vcs.SHORT_BRANCH_NAME.VCS_ROOT_ID% ---> 1.0.0.356-feature-1
how can I?
| I believe what you need is another variable. Try using %vcsroot.branch%. There is also %teamcity.build.branch%, but that one will contain "<default>" on the default branch. If you want more flexibility to choose exactly which part of the branch name gets selected, you can follow the instructions on this page:
http://confluence.jetbrains.com/display/TCD7/Working+with+Feature+Branches#WorkingwithFeatureBranches-branchSpec.
| TeamCity | 20,514,112 | 43 |
We do have hundreds of failed builds in TeamCity (number is especially high because of old retry on fail settings) and now it's a pain to browse history.
I want to clean up only old failed builds, is there anyway to do that in TeamCity? Normal clean-up policy only allows X days before the last successful build sort of clean ups.
| In more recent versions of TeamCity you can now:
Click on the build you want to remove.
From the Build Actions menu select Remove...
Put in an optional comment and click the Remove button to remove that build.
| TeamCity | 2,947,910 | 42 |
How-To Integrate IIS 7 Web Deploy with MSBuild (TeamCity) ?
| Troy Hunt has an excellent 5-part blog series that goes over this topic in detail.
He has effectively compiled all of the other resources out there and turned them into a tutorial.
It's the clearest (and believe it or not, the most concise) way to do what you want.
| TeamCity | 2,847,575 | 41 |
I have some XML that looks something like this:
<?xml version="1.0" encoding="utf-8"?>
<XmlConfig instancetype="XmlConfig, Processing, Version=1.0.0.0, Culture=neutral">
<item>
<key>IsTestEnvironment</key>
<value>True</value>
<encrypted>False</encrypted>
</item>
<item>
<key>HlrFtpPutDir</key>
<value>C:\DevPath1</value>
<encrypted>False</encrypted>
</item>
<item>
<key>HlrFtpPutCopyDir</key>
<value>C:\DevPath2</value>
<encrypted>False</encrypted>
</item>
....
</Provisioning.Lib.Processing.XmlConfig>
In TeamCity I have many system properties:
system.HlrFtpPutDir H:\ReleasePath1
system.HlrFtpPutCopyDir H:\ReleasePath2
What sort of MsBuild magic can I use to push these values into my XML file? In all there are 20 or so items.
| I just blogged about this (http://sedodream.com/2011/12/29/UpdatingXMLFilesWithMSBuild.aspx) but I'll paste the info here for you as well.
Today I just saw a question posted on StackOverflow asking how to update an XML file using MSBuild during a CI build executed from Team City.
There is not correct single answer, there are several different ways that you can update an XML file during a build. Most notably:
Use SlowCheetah to transform the files for you
Use the TransformXml task directly
Use the built in (MSBuild 4.0) XmlPoke task
Use a third party task library
1 Use SlowCheetah to transform the files for you
Before you start reading too far into this post let me go over option #3 first because I think it’s the easiest approach and the most easily maintained. You can download my SlowCheetah XML Transforms Visual Studio add in. Once you do this for your projects you will see a new menu command to transform a file on build (for web projects on package/publish). If you build from the command line or a CI server the transforms should run as well.
2 Use the TransformXml task directly
If you want a technique where you have a “main” XML file and you want to be able to contain transformations to that file inside of a separate XML file then you can use the TransformXml task directly. For more info see my previous blog post at http://sedodream.com/2010/11/18/XDTWebconfigTransformsInNonwebProjects.aspx
3 Use the built in XmlPoke task
Sometimes it doesn’t make sense to create an XML file with transformations for each XML file. For example if you have an XML file and you want to modify a single value but to create 10 different files the XML transformation approach doesn’t scale well. In this case it might be easier to use the XmlPoke task. Note this does require MSBuild 4.0.
Below are the contents of sample.xml (came from the SO question).
<Provisioning.Lib.Processing.XmlConfig instancetype="XmlConfig, Processing, Version=1.0.0.0, Culture=neutral">
<item>
<key>IsTestEnvironment</key>
<value>True</value>
<encrypted>False</encrypted>
</item>
<item>
<key>HlrFtpPutDir</key>
<value>C:\DevPath1</value>
<encrypted>False</encrypted>
</item>
<item
<key>HlrFtpPutCopyDir</key>
<value>C:\DevPath2</value>
<encrypted>False</encrypted>
</item>
</Provisioning.Lib.Processing.XmlConfig>
So in this case we want to update the values of the value element. So the first thing that we need to do is to come up with the correct XPath for all the elements which we want to update. In this case we can use the following XPath expressions for each value element.
/Provisioning.Lib.Processing.XmlConfig/item[key='HlrFtpPutDir']/value
/Provisioning.Lib.Processing.XmlConfig/item[key='HlrFtpPutCopyDir']/value
I’m not going to go over what you need to do to figure out the correct XPath because that’s not the purpose of this post. There are a bunch of XPath related resources on the interwebs. In the resources section I have linked to the online XPath tester which I always use.
Now that we’ve got the required XPath expressions we need to construct our MSBuild elements to get everything updated. Here is the overall technique:
Place all info for all XML updates into an item
Use XmlPoke along with MSBuild batching to perform all the updates
For #2 if you are not that familiar with MSBuild batching then I would recommend buying my book or you can take a look at the resources I have online relating to batching (the link is below in resources section). Below you will find a simple MSBuild file that I created, UpdateXm01.proj.
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="UpdateXml" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<SourceXmlFile>$(MSBuildProjectDirectory)\sample.xml</SourceXmlFile>
<DestXmlFiles>$(MSBuildProjectDirectory)\result.xml</DestXmlFiles>
</PropertyGroup>
<ItemGroup>
<!-- Create an item which we can use to bundle all the transformations which are needed -->
<XmlConfigUpdates Include="ConfigUpdates-SampleXml">
<XPath>/Provisioning.Lib.Processing.XmlConfig/item[key='HlrFtpPutDir']/value</XPath>
<NewValue>H:\ReleasePath1</NewValue>
</XmlConfigUpdates>
<XmlConfigUpdates Include="ConfigUpdates-SampleXml">
<XPath>/Provisioning.Lib.Processing.XmlConfig/item[key='HlrFtpPutCopyDir']/value</XPath>
<NewValue>H:\ReleasePath2</NewValue>
</XmlConfigUpdates>
</ItemGroup>
<Target Name="UpdateXml">
<Message Text="Updating XML file at $(DestXmlFiles)" />
<Copy SourceFiles="$(SourceXmlFile)"
DestinationFiles="$(DestXmlFiles)" />
<!-- Now let's execute all the XML transformations -->
<XmlPoke XmlInputPath="$(DestXmlFiles)"
Query="%(XmlConfigUpdates.XPath)"
Value="%(XmlConfigUpdates.NewValue)"/>
</Target>
</Project>
The parts to pay close attention to is the XmlConfigUpdates item and the contents of the UpdateXml task itself. Regarding the XmlConfigUpdates, that name is arbitrary you can use whatever name you want, you can see that the Include value (which typically points to a file) is simply left at ConfigUpdates-SampleXml. The value for the Include attribute is not used here. I would place a unique value for the Include attribute for each file that you are updating. This just makes it easier for people to understand what that group of values is for, and you can use it later to batch updates. The XmlConfigUpdates item has these two metadata values:
XPath
-- This contains the XPath required to select the element which is going to be updated
NewValue
-- This contains the new value for the element which is going to be updated
Inside of the UpdateXml target you can see that we are using the XmlPoke task and passing the XPath as %(XmlConfigUpdate.XPath) and the value as %(XmlConfigUpdates.NewValue). Since we are using the %(…) syntax on an item this start MSBuild batching. Batching is where more than one operation is performed over a “batch” of values. In this case there are two unique batches (1 for each value in XmlConfigUpdates) so the XmlPoke task will be invoked two times. Batching can be confusing so make sure to read up on it if you are not familiar.
Now we can use msbuild.exe to start the process. The resulting XML file is:
<Provisioning.Lib.Processing.XmlConfig instancetype="XmlConfig, Processing, Version=1.0.0.0, Culture=neutral">
<item>
<key>IsTestEnvironment</key>
<value>True</value>
<encrypted>False</encrypted>
</item>
<item>
<key>HlrFtpPutDir</key>
<value>H:\ReleasePath1</value>
<encrypted>False</encrypted>
</item>
<item>
<key>HlrFtpPutCopyDir</key>
<value>H:\ReleasePath2</value>
<encrypted>False</encrypted>
</item>
</Provisioning.Lib.Processing.XmlConfig>
So now we can see how easy it was to use the XmlPoke task. Let’s now take a look at how we can extend this example to manage updates to the same file for an additional environment.
How to manage updates to the same file for multiple different results
Since we’ve created an item which will keep all the needed XPath as well as the new values we have a bit more flexibility in managing multiple environments. In this scenario we have the same file that we want to write out, but we need to write out different values based on the target environment. Doing this is pretty easy. Take a look at the contents of UpdateXml02.proj below.
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="UpdateXml" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<SourceXmlFile>$(MSBuildProjectDirectory)\sample.xml</SourceXmlFile>
<DestXmlFiles>$(MSBuildProjectDirectory)\result.xml</DestXmlFiles>
</PropertyGroup>
<PropertyGroup>
<!-- We can set a default value for TargetEnvName -->
<TargetEnvName>Env01</TargetEnvName>
</PropertyGroup>
<ItemGroup Condition=" '$(TargetEnvName)' == 'Env01' ">
<!-- Create an item which we can use to bundle all the transformations which are needed -->
<XmlConfigUpdates Include="ConfigUpdates">
<XPath>/Provisioning.Lib.Processing.XmlConfig/item[key='HlrFtpPutDir']/value</XPath>
<NewValue>H:\ReleasePath1</NewValue>
</XmlConfigUpdates>
<XmlConfigUpdates Include="ConfigUpdates">
<XPath>/Provisioning.Lib.Processing.XmlConfig/item[key='HlrFtpPutCopyDir']/value</XPath>
<NewValue>H:\ReleasePath2</NewValue>
</XmlConfigUpdates>
</ItemGroup>
<ItemGroup Condition=" '$(TargetEnvName)' == 'Env02' ">
<!-- Create an item which we can use to bundle all the transformations which are needed -->
<XmlConfigUpdates Include="ConfigUpdates">
<XPath>/Provisioning.Lib.Processing.XmlConfig/item[key='HlrFtpPutDir']/value</XPath>
<NewValue>G:\SomeOtherPlace\ReleasePath1</NewValue>
</XmlConfigUpdates>
<XmlConfigUpdates Include="ConfigUpdates">
<XPath>/Provisioning.Lib.Processing.XmlConfig/item[key='HlrFtpPutCopyDir']/value</XPath>
<NewValue>G:\SomeOtherPlace\ReleasePath2</NewValue>
</XmlConfigUpdates>
</ItemGroup>
<Target Name="UpdateXml">
<Message Text="Updating XML file at $(DestXmlFiles)" />
<Copy SourceFiles="$(SourceXmlFile)"
DestinationFiles="$(DestXmlFiles)" />
<!-- Now let's execute all the XML transformations -->
<XmlPoke XmlInputPath="$(DestXmlFiles)"
Query="%(XmlConfigUpdates.XPath)"
Value="%(XmlConfigUpdates.NewValue)"/>
</Target>
</Project>
The differences are pretty simple, I introduced a new property, TargetEnvName which lets us know what the target environment is. (note: I just made up that property name, use whatever name you like). Also you can see that there are two ItemGroup elements containing different XmlConfigUpdate items. Each ItemGroup has a condition based on the value of TargetEnvName so only one of the two ItemGroup values will be used. Now we have a single MSBuild file that has the values for both environments. When building just pass in the property TargetEnvName, for example msbuild .\UpdateXml02.proj /p:TargetEnvName=Env02. When I executed this the resulting file contains:
<Provisioning.Lib.Processing.XmlConfig instancetype="XmlConfig, Processing, Version=1.0.0.0, Culture=neutral">
<item>
<key>IsTestEnvironment</key>
<value>True</value>
<encrypted>False</encrypted>
</item>
<item>
<key>HlrFtpPutDir</key>
<value>G:\SomeOtherPlace\ReleasePath1</value>
<encrypted>False</encrypted>
</item>
<item>
<key>HlrFtpPutCopyDir</key>
<value>G:\SomeOtherPlace\ReleasePath2</value>
<encrypted>False</encrypted>
</item>
</Provisioning.Lib.Processing.XmlConfig>
You can see that the file has been updated with different paths in the value element.
4 Use a third party task library
If you are not using MSBuild 4 then you will need to use a third party task library like the MSBuild Extension Pack (link in resources).
Resources
MSBuild batching: http://sedotech.com/Resources#Batching
SlowCheetah – XML Transforms extension: http://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5
MSBuild Extension Pack (has a task to update XML files): http://msbuildextensionpack.codeplex.com/
Online XPath tester: http://www.whitebeam.org/library/guide/TechNotes/xpathtestbed.rhtm
| TeamCity | 8,658,972 | 41 |
I am trying to set up a TeamCity build process that runs a custom command line script. The script uses a variable so it needs a percent sign (e.g. %x). But TeamCity uses percent signs for its properties (e.g. %build.number%), so the percent sign in the script gets removed when it runs.
If the script contains this:
for /d %x in ("c:\*") do @echo "%x"
This is what it actually runs:
for /d x in ("\*") do @echo "x"
How can I write my script so it can include variables?
| If you want to pass % to TeamCity, you should escape it with another %, i.e. for % it must be %%`.
But the Windows command line considers % as an escape character, so you should escape it again adding another % before each %, i.e. for %% you should pass %%%%
Flow is:
%%%% in cmd -> %% in TeamCity -> % actual sign.
tl;dr: the answer to your question will be:
for /d %%%%x in ("c:\*") do @echo "%%%%x"
| TeamCity | 4,389,946 | 41 |
Our buildserver (TeamCity, much recommended), runs our a whole bunch of testsuites on our finished c++ program.
Once in a whole, a test causes our program to crash, often bringing up a VisualStudio dialog offering me to JustInTime debug the crash. The dialog stops the buildserver from progressing. Instead of the build marked as failed, it just hangs. I've turned off the Just In Time debugging feature in VisualStudio, but when it's turned off, you still get a message "Couldn't JustinTime Debug this, you can turn it on in the options".
Does anybody know of a way to ensure that any unhandled exception in a program does not result in any modal dialog?
| This MSDN article explains how to disable Just-In-Time debugging on a Windows server. I've included the relevant portion of the article below:
After Visual Studio is installed on a server, the default behavior when an unhandled
exception occurs is to show an Exception dialog that requires user intervention to
either start Just-In-Time debugging or ignore the exception. This may be undesirable for
unattended operation. To configure the server to no longer show a dialog when an
unhandled exception occurs (the default behavior prior to installing Visual Studio), use
the registry editor to delete the following registry keys:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AeDebug\Debugger
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\DbgManagedDebugger
On a 64-bit operating system also delete the following registry keys:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion\AeDebug\Debugger
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\DbgManagedDebugger
| TeamCity | 1,893,567 | 40 |
Hello I have build server with TeamCity.
My project is Sitecore Web Application. I am using TDS (HedgehogDevelopment). I have setup build settings in TeamCity with MS build and it looks like working when TDS project is disabled in build configuration manager.
But then it enebled I am getting net error
C:\Program Files
(x86)\MSBuild\HedgehogDevelopment\SitecoreProject\v9.0\HedgehogDevelopment.SitecoreProject.targets(310,
5): error MSB4036: The "TransformXml" task was not found. Check the
following: 1.) The name of the task in the project file is the same as
the name of the task class. 2.) The task class is "public" and
implements the Microsoft.Build.Framework.ITask interface. 3.) The task
is correctly declared with in the project file, or in the
*.tasks files located in the "C:\Windows\Microsoft.NET\Framework64\v3.5" directory. Project
NetKey.TDSMaster\MyProject.TDSMaster.scproj failed. Project
Website\MyProject.sln failed
The help in error description is not a case for me.
I don't have VS 2012 on build machine. I have installed Microsoft Visual Studio 2012 Shell
for support my web project.
How to resolve it ?
Thanks.
| TransformXML comes as part of the ASP.NET Web Publishing tools. As such they usually come with a Visual Studio installation on your build server and require more than just the Shell version of Visual Studio. Installing Visual Studio Express Web Edition might also do the trick.
You could try installing the Web-Deploy package to see whether it's enough, but usually I just install the full version of Visual Studio on a build agent. This is legal under MSDN Subscription licensing.
After some experimenting I can tell that you need to install at least the Visual Studio Web Developer Tools on the build server for these tasks to get installed the official way. I suspect that installing the Visual Studio Express Web Edition would suffice.
| TeamCity | 16,646,698 | 40 |
We use TeamCity as our CI server, and I've just started seeing "TestFixtureSetUp Failed" in the test failure window.
Any idea how I go about debugging this problem? The tests run fine on my workstation (R# test runner in VS2008).
| It is a bit of a flaw in the implementation of TestFixtureSetUp (and TestFixtureTearDown) that any exceptions are not well reported. I wrote the first implementation of them and I never got it to work the way it was supposed to. At the time the concepts in the NUnit code were tightly coupled to the idea that actions were directly related to a single test. So the reporting of everything was related to a test result. There wasn't really a space for reporting something that happened at the suite level without a huge re-write (it isn't a refactoring when you change a sheep into an escalator).
Because of that bit of history it's hard to find out what really happened in a TestFixtureSetUp. There isn't a good place to attach the error. The TestFixtureSetUp call is a side effect of running a test instead of being directly related to it.
@TrueWill has the right idea. Check the logs and then modify the test to add more logging if necessary. You might want to put at try/catch inside the TestFixtureSetup and log a lot in the catch block. I just thought I could add some background to it (in other words it's kind of my fault).
| TeamCity | 1,411,676 | 39 |
I'm trying to run a custom command in my MSBuild file; it basically runs 'git log -10' and stores that commit info into a text file.
The problem is, when I try to run the build, it errors saying "fatal: Not a git repository". So I checked TeamCity's work directory for my project, and there is no .git directory!
Why doesn't TeamCity create the .git directory when it clones the repository? Is there a way to enable this?
edit: TeamCity version is 7.1.2; I'll try updating to 8.0.1 to see if there is an option available for this.
| I changed the VCS checkout mode from server to "automatically on agent" and it works now! Thanks to the answer for this question: Using git commands in a TeamCity Build Step.
| TeamCity | 17,555,931 | 39 |
How can I configure TeamCity to build from SVN trunk and also from different branches and/or tags ?
Our idea is to have multiple builds from the same project, this way we can have the current version that is in production (with the ability to make deploys and fixes over that "release tag") and at the same time have the trunk and branches with the actual development that is taking place daily.
We have our policies, owner and all that for our SVN directories, the problem that we have is how to configure TeamCity to make multiple builds for the same project over the different "versions" or "states" of the application.
What is the best way to do this ?
Thanks in advance !
| First, ensure your VCS root is the root of your SVN repository in your administration panel, instead of being pointed to the trunk directory.
Then, for each build configuration, edit the checkout rules in your VCS Configuration. Add the checkout rule you desire.
For example, for your 'trunk' build configuraton, you would have a checkout rule of: +:trunk => ..
If you have a tag or branch you want to build, just create a new build config with a corresponding checkout rule. A tag of 'release-1.1' would have a checkout rule of: +:tags/release-1.1 => .
Here is the documentation on checkout rules: http://confluence.jetbrains.net/display/TCD65/VCS+Checkout+Rules
| TeamCity | 6,874,796 | 36 |
Coming "from" TFS and using TeamCity in a customer project....
...is there a way to install multiple agent instances on one computer? I could easily do that with TFS.
The reason is that we have build scripts that are linear in execution for some (large) part and take a significant amount of time. Basically with a a modern server (4, 6, 8, 12 cores) there is nothing stopping the server from actually efficiently running multiple builds AT THE SAME TIME - except there seems to be no way to install multiple agent instances on one machine.
| Yes it is possible (I also have 2 agents installed on one machine) see TeamCity docs:
Several agents can be installed on a single machine. They function as
separate agents and TeamCity works with them as different agents, not
utilizing the fact that they share the same machine.
After installing one agent you can install additional one, providing the
following conditions are met:
the agents are installed in the separate directories
they have distinctive work and temp directories
buildAgent.properties is configured to have different values for name and ownPort properties
Make sure, there are no build configurations
that have absolute checkout directory specified (alternatively, make
sure such build configurations have "clean checkout" option enabled
and they cannot be run in parallel).
Under Windows, to install additional agents as services, modify
\launcher\conf\wrapper.conf to change:
wrapper.console.title,
wrapper.ntservice.name
wrapper.ntservice.displayname
wrapper.ntservice.description
properties to have distinct name within the computer.
More resources:
another question
excellent post
| TeamCity | 4,333,989 | 36 |
Is it possible, without disabling all other connected agents, to force TeamCity to build on a specific agents machine?
| Under Build Configuration Settings go to Agent Requirements and set an Explicit Requirement for the specific agent name:
Parameter Name: system.agent.name
Condition: equals
Value: YOUR_SPECIFIC_AGENT_NAME
| TeamCity | 1,600,778 | 36 |
I am trying to compile a Nativescript application as part of our Teamcity deployment strategy.
When I run NPM install, I get a ENOENT error trying to find files, as shown below:
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-7722a2ea/fp/assignAll.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-8fa77886/fp/create.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-7722a2ea/fp/assignAllWith.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-b2787570/fp/assign.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-8fa77886/fp/curry.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-b2787570/fp/assignAll.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-7722a2ea/fp/assignIn.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-8fa77886/fp/curryN.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-b2787570/fp/assignAllWith.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-7722a2ea/fp/assignInAll.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-7722a2ea/fp/assignInAllWith.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-8fa77886/fp/curryRight.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-b2787570/fp/assignIn.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-8fa77886/fp/curryRightN.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-b2787570/fp/assignInAll.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-7722a2ea/fp/assignInWith.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-b2787570/fp/assignInAllWith.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-8fa77886/fp/date.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-7722a2ea/fp/assignWith.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-7722a2ea/fp/assoc.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-8fa77886/fp/debounce.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-7722a2ea/fp/assocPath.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-b2787570/fp/assignInWith.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-8fa77886/fp/deburr.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-7722a2ea/fp/at.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-b2787570/fp/assignWith.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-8fa77886/fp/defaults.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-b2787570/fp/assoc.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-7722a2ea/fp/attempt.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-8fa77886/fp/defaultsAll.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-b2787570/fp/assocPath.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/browserify-117e4a8d/test/shared_symlink/shared/index.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-7722a2ea/fp/before.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-8fa77886/fp/defaultsDeep.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-b2787570/fp/at.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-8fa77886/fp/defaultsDeepAll.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-7722a2ea/fp/bind.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-b2787570/fp/attempt.js'
npm WARN tar ENOENT: no such file or directory, open '/home/my_user/BuildAgent/work/my_application/node_modules/.staging/lodash-8fa77886/fp/defaultTo.js'
I have tried cleaning up the node_modules folder, ~/.npm and the package-lock.json before issuing npm install, running the same in different containers, cleaning the checkout folder in teamcity before running npm install, changing the checkout folder and all I can think off. I have also ran npm cache clear --force.
I have also tried running the same steps in a local machine, with the same container, and the compilation is working.
There seems to be some dirty data related to npm or something similar causing this, but I can't find out what.
This is the dockerfile being used:
FROM ubuntu:18.04
USER root
ENV ANDROID_HOME=/android-sdk PATH=$PATH:/android-sdk/tools:/android-sdk/tools/bin:/android-sdk:/platform-tools
RUN apt-get update && apt-get install -y sudo lib32z1 lib32ncurses5 g++ unzip openjdk-8-jdk zsh-common curl gnupg2 git
RUN curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash - && \
apt-get install -y nodejs && \
curl "https://dl.google.com/android/repository/sdk-tools-linux-4333796.zip" -o /tmp/sdk.zip && \
mkdir -p /android-sdk && \
unzip -q /tmp/sdk.zip -d /android-sdk && \
mkdir -p /root/.android/ && touch /root/.android/repositories.cfg && \
rm -rf /tmp/* && \
rm -rf /var/lib/apt/lists/* && \
rm -rf /var/lib/apt/*
RUN echo "export JAVA_OPTS=\"$JAVA_OPTS\"" >> /root/.bashrc && \
echo "export ANDROID_HOME=$ANDROID_HOME" >> /root/.bashrc && \
echo "export PATH=$PATH" >> /root/.bashrc
RUN yes | /android-sdk/tools/bin/sdkmanager --licenses && \
/android-sdk/tools/bin/sdkmanager "tools" "platform-tools" "platforms;android-28" "build-tools;28.0.3" "extras;google;m2repository" "extras;android;m2repository"
RUN yes | npm install [email protected] -g --unsafe-perm && \
tns extension install [email protected] && \
tns usage-reporting disable && \
tns error-reporting enable
RUN nativescript doctor
How can I clean this up?
UPDATE
I have also noticed that npm uninstall loadash triggers the same behaviour and the multiple enoent messages.
Not quite sure why...
| Make sure that log output is the end of it.
In my case it was:
npm ERR! code ENOENT
npm ERR! syscall spawn git
npm ERR! path git
npm ERR! errno -2
npm ERR! enoent Error while executing:
npm ERR! enoent undefined ls-remote -h -t ssh://[email protected]/bodymovin/lottie-api.git
npm ERR! enoent
npm ERR! enoent
npm ERR! enoent spawn git ENOENT
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent
If not, check the end of your log for the actual issue.
I experienced this when running a docker container and it turned out one of the packages is being pulled using git as you see in the log, so the git command needs to be in the PATH of the user that runs the npm command.
If it's not that, the end of the log will likely tell you what is the actual error.
If it's not clear, it might be the package-lock.json file having old references generated by the package.json when running npm install.
Try to remove/rename it and run npm install, then compare the differences.
If that still does not fix it, maybe package.json has a reference that is too old to be resolved by npm.
The npm cache you may be looking for on a Linux system is usually under ~/.npm or ~/.npm-global depending on how you configured npm/node.
If none of this resolves it, please update your answer with a full log, and the exact environment and conditions you run this in.
If this only happens for lodash, try to see what happens if you remove it as a dependency.
Good luck
| TeamCity | 59,343,549 | 35 |
I recently started using NuGet to manage external packages. For now I have only needed it for NLog.
Everything works fine when I Build the project in VS 2012. However, I am trying out TeamCity as a CI server (I'm fairly new to CI) and it is giving me the following error:
[Csc] SomeNamespace\SomeClass.cs(10, 7): error CS0246:
The type or namespace name 'NLog' could not be found
(are you missing a using directive or an assembly reference?)
(this error is repeated throughout where ever I use NLog)
Now I did not include the 'packages/' folder in SVN, since I thought it was good practice not to include binaries and let MSBuild in TeamCity download these on its own. However it's clearly not doing that. I DO include the 'packages.xml' file in SVN.
What can I check to see what is going wrong?
Update
Thanks to @DavidBrabant I was nudged in the right direction. However, I now get the following error in TeamCity:
Package restore is disabled by default. To give consent, open the Visual Studio Options dialog,
click on Package Manager node and check 'Allow NuGet to download missing packages during build.'
However I'm not in Visual Studio but TeamCity, so I do not know how to set 'consent' to true! I tried to set RestorePackages to 'true' in the NuGet.targets file:
<RestorePackages Condition=" '$(RestorePackages)' == '' ">true</RestorePackages>
but this didn't work.
Update 2
To make it work I also set the following property NuGet.targets:
<RequireRestoreConsent Condition=" '$(RequireRestoreConsent)' != 'true' ">false</RequireRestoreConsent>
This made the build run succesfully!
| The enable package restore feature built into NuGet allows you to very easily set up the pre-build part of the workflow. To do so, right-click the solution node in Visual Studio’s Solution Explorer, and click the Enable NuGet Package Restore option. Note that you need to have the NuGet Visual Studio Extension installed on your system. If you do, and you still don’t see this menu item appear, you either already enabled this option, or you have a folder named .nuget in your solution directory.
After having set that option, you can now delete all sub-folders of your package installation directory, by default $(SolutionDir)\packages, except for the repositories.config file, and your solution should still compile properly. During compilation, you should see NuGet installation traces in the Visual Studio output window, and you should see the required NuGet packages reappear in the package installation directory as well.
Also see Using Nuget without committing packages.
| TeamCity | 14,438,650 | 35 |
We are migrating to .NET 4 and very interested in implementing new Design By Contract capabilities.
As we know Code Contract engine requires installation of Code Contract addin
and VS Ultimate or Premium (for static checking).
Here is my questions:
Can I use code contract rewriting
without installing VS on CI build Server (TeamCity)?
Is there any
msbuild tasks to execute Contract checking?
Do you use Code Contract's validation with CI builds?
|
Can I use code contract rewriting without installing VS on CI build
server (TeamCity)?
Yes. Install CodeContracts on the build server. (If it refuses to install on a machine without Visual Studio, just copy the files listed below, and their dependencies, onto the build server.) Once installed, you'll find the CodeContract tools installed in %programfiles%\Microsoft\Contracts\Bin. In that directory, there are 4 executables you'll be interested in:
ccrewrite.exe - The binary rewriter. This should be executed after compilation. It turns your contracts into runtime checks or whatever you specify you want them turned into.
ccrefgen.exe - This can generate contract reference assemblies alongside your assemblies. This is useful if you're shipping dlls to be consumed by other parties.
cccheck.exe - The static checker. On the build server, you'd run this tool over your assemblies containing contracts, and it will spit out warnings and messages as it encounters potential problems.
ccdocgen.exe - This generates XML documentation from the contracts in your code. You might want to use this if you're shipping dlls with contracts for consumption by other parties, or if you just need internal docs on your code.
Is there any msbuild tasks to execute Contract checking?
Yes. There are 2 MSBuild tasks shipping with CodeContracts: in the same CodeContracts installation directory, check out the MSBuild\[framework version] folder. In that directory, there are 2 files that should help you out: Microsoft.CodeContracts.targets and Microsoft.CodeContractAnalysis.targets.
According to the CodeContracts documentation,
An msbuild script extension Microsoft
.Contract. targets contains the extra
build actions for the runtime contract
instrumentation and static verification
steps. As a result of this approach,
it is possible to use the same
functionality when building from the
command line with the msbuild command.
Using msbuild on a project or solution
that uses contracts enabled via the VS
user interface will perform the same
actions as the corresponding build
under VS.
As you can see, it is possible and supported to integrate the tools into CI builds via the MSBuild targets.
Do you use Code Contract's validation with CI builds?
Assuming you mean static checking with warnings/messages, I've done this personally, but haven't done this on a big project.
I hope this helps!
Hat tip to Jon Skeet's C# In Depth book for explanation of the command line tools.
| TeamCity | 3,569,108 | 35 |
Has anybody successfully configured Teamcity to monitor, extract, and build from GitHub?
I can't seem to figure how where and how to configure the SSH keys for Teamcity. I have Teamcity running as a system service, under a system account. So where does Teamcity stash its SSH configuration?
EDIT
To get this to work, I needed to stop the agent from running under a system account.
| Ok... I got this to start working on my Windows server. Here are the steps I took to configure TeamCity 4.5 Professional:
Downloaded the JetBrains Git VCS Plugin
Copied the downloaded zip file to .BuildServer\plugins
In the Administration > Edit Build Configuration > Edit VCS Root configuration screen, I selected "Git (JetBrains)"
Entered my Clone Url from the GitHub project page
Set for authentication method "Default Private Key" -- this is IMPORTANT
The TeamCity BuildAgent should be running as a standard user, with the SSH installation configured properly for that user.
Follow the GitHub SSH directions for SSH configuration
Leave the username blank. This should already be provided for in your GitHub clone URL
| TeamCity | 797,090 | 35 |
We are hosting our own nuget server through Teamcity. Is there any other way to add an icon to a .nuspec file other than specifying a web url (http://....)?
Or is there a place in Teamcity that these icons could be hosted?
| As of NuGet 5.3.0 you can now use <icon> to provide a relative path to your JPEG or PNG icon file located within your package.
<package>
<metadata>
...
<icon>images\icon.png</icon>
...
</metadata>
<files>
...
<file src="..\icon.png" target="images\" />
...
</files>
</package>
Source: https://learn.microsoft.com/en-us/nuget/reference/nuspec#icon
<iconUrl> is now deprecated.
| TeamCity | 38,329,201 | 34 |
TeamCity agent's show a list of "Environment Variables" under Agent Parameters but I cannot get them to update. I've added environment variables to my agent operating system, but cannot get them to refresh. I've tried restarting the agent and disabling and re-enabling the agent.
| The TeamCity agent doesn't actually read environment variables from the OS. Instead it reads them from the buildAgent/conf/buildAgent.properties file on your agent machine. Down at the bottom of this file you'll see instructions on how to add new variables. Something like this:
# Environment Variables
#env.exampleEnvVar=example Env Value
env.GRADLE_HOME=/Frameworks/gradle-2.9
Once you've done this, switch to the command prompt on your agent machine, and execute something like this:
./agent.sh stop
./agent.sh start
Obviously OS dependent. There is a .bat file there for Windows.
That should get your environment variables showing up in TeamCity.
| TeamCity | 36,198,286 | 34 |
Subsets and Splits