I have two separate functions in my Jenkins pipeline and i want to call 1st function from 2nd function.
I tried following code.
def first(){
return{
stages{
stage("test"){
steps{
echo "ok"
}
}
}
}
}
def second(){
return{
first().call()
}
}
pipeline {
agent any
stages{
stage("Run"){
steps{
script{
second().call()
}
}
}
}
}
is this possible or not. suggest me right way.
Yes, you can. Your Jenkinsfile will look like this:
def first(){
stage("test"){
println "executing first"
}
}
def second(){
println("calling first from second")
first()
}
pipeline {
agent any
stages{
stage("Run"){
steps{
second()
}
}
}
}
Related
I am trying to add an environment variable containing a json which needs to give out the deployed branch name like below:
stage('Build files') {
agent { label "${AGENT_NAME}"}
environment {
DEPLOYED_BRANCH = '{\"branch\":\"${env.BRANCH_NAME}\"}'
}
steps { //Do something}
ansiColor('xterm') {
sh """
echo \"${DEPLOYED_BRANCH}\" > deployed_branch.json
"""
}
}
While deploying, I am getting :
"{"branch":"${env.BRANCH_NAME}"}": bad substitution
I've tried a few different options with the single/double quotes but with no success. Any ideas?
you can do it like this, but it will be a JSON string in the deployed_branch.json file (JSON file with a string content)
stage('create a JSON ') {
environment {
SOME_ENV_VARS = '{\"branch\":\"$WORKSPACE\"}'
}
steps {
sh """
echo $SOME_ENV_VARS > deployed_branch.json
"""
}
}
It can be done better way like this:
scripted pipeline
node {
stage('any') {
def myJSON = readJSON text: '{}'
myJSON.branch = "${env.WORKSPACE}" as String
writeJSON file: "${WORKSPACE}/x.json", json: myJSON
}
}
declarative pipeline
pipeline {
agent any;
stages {
stage('create a JSON ') {
steps {
script {
def myJSON = readJSON text: '{}'
myJSON.branch = "${env.WORKSPACE}" as String
writeJSON file: "${WORKSPACE}/x.json", json: myJSON
}
}
}
}
}
Note - it need Jenkins Utility Pluigns
In Jenkins, I know I can do this...
pipeline {
agent any
stages {
stage('Demo') {
steps {
MyFunction()
}
}
}
}
void MyFunction() {
sh 'ls /'
}
In this situation, the function is within the pipeline, but then I can always extract MyFunction into a shared library for reuse across pipelines.
But would it be possible to do this with a post-build step?
In this case, I would like to convert this into a function and extract it into a library.
post {
always {
/* clean up our workspace */
deleteDir()
/* clean up tmp directory */
dir("${workspace}#tmp") {
deleteDir()
}
/* clean up script directory */
dir("${workspace}#script") {
deleteDir()
}
dir("${workspace}#2") {
deleteDir()
}
dir("${workspace}#2#tmp") {
deleteDir()
}
}
}
I've tried this
post {
always{
test()
}
}
}
With Function
void test() {
{
/* clean up our workspace */
deleteDir()
/* clean up tmp directory */
dir("${workspace}#tmp") {
deleteDir()
}
/* clean up script directory */
dir("${workspace}#script") {
deleteDir()
}
dir("${workspace}#2") {
deleteDir()
}
dir("${workspace}#2#tmp") {
deleteDir()
}
}
}
But it doesn't seem to work.
Is this possible at all or am I just missing something really obvious?
Passing the name of the workspace as a parameter in the function will solve your issue. The below script works.
pipeline {
agent any
stages {
stage('Hello') {
steps {
echo 'Hello World'
}
}
}
post{
always{
echo "In : ${env.WORKSPACE}"
test(env.WORKSPACE)
}
}
}
void test(workspace){
echo "In test : " + workspace
deleteDir()
dir("${workspace}#tmp") {
deleteDir()
}
}
Also, instead of calling deleteDir() for multiple tmp directories, if you call deleteDir() only once, then it will delete the workspace as well as tmp directories
The way that works for us to clean up the workspace after a specific stage and without trying to guess the folder name is to make your post function in stage:
pipeline {
agent any
stages {
stage('1') {
steps {
echo 'Hello World'
}
post {
cleanup {
script {
// Workspace Cleanup plugin
cleanWs deleteDirs: true,
notFailBuild: true,
cleanWhenAborted: true,
cleanWhenFailure: true,
cleanWhenSuccess: true
}
}
}
}
}
}
We use WorkspaceCleanup plugin.
Hello I am new in Griffon Framework I want to add Login feature in my application. Follow are my model,view and controller:
SignInModel.groovy
#ArtifactProviderFor(GriffonModel)
#griffon.transform.Validateable
class SignInModel {
#Bindable String userName
#Bindable String password
static CONSTRAINTS = {
userName(blank: false,nullable: false)
password(blank: false, nullable: false)
}
}
SignInView.groovy
#ArtifactProviderFor(GriffonView)
class SignInView {
FactoryBuilderSupport builder
SignInModel model
SignInController controller
void initUI() {
builder.with {
application{
frame(title: 'Login', size: [330, 230],
show: true,resizable:false,locationRelativeTo: null,
defaultCloseOperation: EXIT_ON_CLOSE) {
panel(constraints: BorderLayout.CENTER,
border: compoundBorder([emptyBorder(10),titledBorder('Welcome To Tracker')])) {
tableLayout() {
tr {
td {
label(text: "Username")
}
td {
textField(id: "usernameTxt", columns: 15, text: bind(target: model, 'userName', mutual: true))
}
}
tr{
td{
label(text:"Password")
}
td{
passwordField(id:"passwordTxt",columns:15,text:bind(target:model,'password',mutual:true))
}
}
}
}
panel(constraints: BorderLayout.SOUTH) {
button text: 'Login', actionPerformed: {
model?.getErrors()?.clearAllErrors()
controller.signIn()
}
}
}
}
}
}
}
}
SignInController.groovy
#ArtifactProviderFor(GriffonController)
class SignInController {
SignInModel model
SignInView view
void signIn(){
try {
if (model?.validate()) {
println("No Error Found..")
} else {
println("Error Found..")
}
}catch (Exception ex){
println("Exception Generated:>>>>>>>>>>>>>>"+ex?.getMessage())
}
}
}
I want to update my SignIn View If username and password are empty with error message. I am able to get error message in my model but my view not update so Please help me.
#Note: I have added griffon validation plugin
You must process the errors property of the validateable (the model instance). This property contains a list of messages that can be used to display information back to the user, however you must choose which messages, as there may be many. Your current code is one step away from this as it has already triggered validation; now you just need to consume the messages and present them in the UI.
I'm porting a working webapp from Grails 2.3 to 3.0.1. When I post the Json string {"command":"ping"} to the server i get the following result:
{"timestamp":1429380750958,"status":405,"error":"Method Not Allowed","exception":"org.springframework.web.HttpRequestMethodNotSupportedException","message":"Request method 'POST' not supported","path":"/rps/request"}
Here's the controller:
import org.grails.web.json.JSONObject
class RequestController {
def jsonManagerService
def index() {
JSONObject json = request.JSON
if(!json){
render "{json or gtfo}"
return
}
render jsonManagerService.parseJson(json)
}
}
Here's the JsonManagerService:
import grails.transaction.Transactional
import org.grails.web.json.JSONObject
#Transactional
class JsonManagerService {
def parseJson(JSONObject o) {
switch (o.command){
case("ping"):
return '{"result":"pong"}'
break;
default:
return '{"result":"unknown command"}'
}
}
}
And here's my UrlMappings.groovy (it's the default one):
class UrlMappings {
static mappings = {
"/$controller/$action?/$id?(.$format)?"{
constraints {
// apply constraints here
}
}
"/"(view:"/index")
"500"(view:'/error')
"404"(view:'/notFound')
}
}
It looks like a Spring related issue. All the search on this matter provided no results. Any idea?
Edit: thanks #dmahapatro, added UrlMappingsgroovy. Corrected the controller, dumb mistake, but result is still the same.
I am using helper functions to store and retrieve game state using HTML5 DOM storage and the JSON features built into ECMAScript5, my code is:
function saveState(state) {
window.localStorage.setItem("gameState",state);
}
function restoreState() {
var state = window.localStorage.getItem("gameState");
if (state) {
return parse(state);
} else {
return null;
}
}
but anyhow I am not getting desired output, as i am new to JSON its hard to resolve. HELP please !
Try below code:
function saveState(state) {
window.localStorage.setItem("gameState", JSON.stringify(state));
}
function restoreState() {
var state = window.localStorage.getItem("gameState");
if (state) {
return JSON.parse(state);
} else {
return null;
}
}