I can check that a job exists if there is no folder:
http://myJenkinsInstance:8080/checkJobName?value=TestJob101
What I am can't to work out is how do I check for a job that is within a folder please when I am using the folders plugin.
e.g. http://myJenkinsInstance:8080/job/MyFolder/job/TestJob101/
http://myJenkinsInstance:8080/checkJobName?value=job/MyFolder/job/TestJob101/
returns:
‘/’ is an unsafe character
To access the Jenkins REST API you can add \api\json
suffix to many URLs which will cause Jenkins to return a JSON segment (if it exists, otherwise a 404) that you can consume. Tools like json2csharp are invaluable in this scenario.
Methods of consumption
1. Scripting
`curl -XGET 'http://myJenkinsInstance:8080/job/MyFolder/job/TestJob101/api/json' --user user.name:YourAPIToken`
This returns either 200 or 404 depending on whether the job already exists.
2. Programming language (like C#)
Go to your folder URL and append api\json
like so:
http://myJenkinsInstance:8080/job/MyFolder/job/TestJob101/api/json
If that folder exists you will see in the browser some json, otherwise you will get a 404. Copy all of the json and paste it into json2csharp and generate the C#.
You should get the following C#:
public class Action
{
public string _class { get; set; }
}
public class Job
{
public string _class { get; set; }
public string name { get; set; }
public string url { get; set; }
public string color { get; set; }
}
public class PrimaryView
{
public string _class { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class View
{
public string _class { get; set; }
public string name { get; set; }
public string url { get; set; }
}
public class RootObject
{
public string _class { get; set; }
public List<Action> actions { get; set; }
public string description { get; set; }
public string displayName { get; set; }
public object displayNameOrNull { get; set; }
public string fullDisplayName { get; set; }
public string fullName { get; set; }
public string name { get; set; }
public string url { get; set; }
public List<object> healthReport { get; set; }
public List<Job> jobs { get; set; }
public PrimaryView primaryView { get; set; }
public List<View> views { get; set; }
}
You should rename RootObject class to something more meaningful in your context to make your code more readable, like FolderCheck
Once you have this code you can make an HTTP GET call to the same URL. (Note: substituting the folder name in programmatically will make it work for any folder you want to work with.) and deserialise it like so using the Json.NET NuGet package:
var json = Adapter.Get(url, username, apiKey);
JsonConvert.DeserializeObject<FolderCheck>(json);
If the json variable contains valid json, then you know the folder exists.
Tested on Jenkins LTS 2.60.3 and 2.90.