I am creating two environment variables in my Jenkins Pipeline,
environment{
base_ver=sh(script: 'grep FROM ${WORKSPACE}/Dockerfile | awk -F : \'{print $2}\'', returnStdout: true).trim()
git_hash=sh(script: 'git rev-parse --short HEAD', returnStdout: true).trim()
}
Now I want to create another env variable in same section by using above two variables, it would we something like this
Image='$base_ver'-'$git_hash'
I tried multiple ways of doing it but none on them seems to work, can we access the env variable within env variable section?
Here is what I tried,
environment{
base_ver=sh(script: 'grep FROM ${WORKSPACE}/Dockerfile | awk -F : \'{print $2}\'', returnStdout: true).trim()
git_hash=sh(script: 'git rev-parse --short HEAD', returnStdout: true).trim()
Image=sh(script: 'DockerImage=${base_ver}-${git_hash}', returnStdout: true).trim()
}
Please let me know if this is possible or right way of doing it.
Thanks .
What you currently doing is launching shell, defining variable in it and exiting. There is nothing printed and therefore stdout returned is empty.
Concatenation can be done by groovy. There is no need to launch shell for that.
Thy this:
Image = base_ver + '-' + git_hash
If you need to do it in shell for whatever reason just add echo (also note double quotes so that groovy substitute variables before calling shell):
Image=sh(script: "echo -n '${base_ver}-${git_hash}'", returnStdout: true).trim()
I tried this way and it worked for me. Thank you guys for suggestion.
sh """
Image=${PROD_ECR_REPO}:${env.base_ver}-${env.git_hash}
echo \$Image
"""
Related
I'm using the post-checkout hook to try and set environment variables when switching branches.
#!/bin/sh
echo "Updating environment variables..."
OLD_IFS=$IFS
IFS=$'\n'
for x in $(cat .env | sed -e '/^#/d;/^\s*$/d' -e "s/'/'\\\''/g" -e "s/=\(.*\)/='\1'/g")
do
var_name=$( cut -d '=' -f 1 <<< "$x" )
export $x
pwsh.exe -c "\$env:$x"
pwsh.exe -c "echo 1; echo \$env:$var_name"
export $x
done
IFS=$OLD_IFS
The problem is that git hook is executed with WSL so the variables I set are lost after the post-hook
I assume this is because of the shebang?
I've tried #!/usr/bin/env pwsh but I get the error Processing -File '.git/hooks/post-checkout' failed because the file does not have a '.ps1' extension. Specify a valid PowerShell script file name, and then try again.
Is this something that can be done? I want to automatically change the DB connection when I switch branches.
As anthony sottlie noted, you can't do it that way.
What you need instead is a command that you run instead of git switch or git checkout. In this command, you will:
run git switch or git checkout, then
set the environment variables you would have set in your script, the way you would have set them
and since this will be done by the command itself, rather than in a subprocess, it will affect further commands run by this same command-line interpreter.
there
I need to pass multiple arguments to a docker command, but I wanted this string of arguments to be built interactively and not by hand. In my specific problem, I want to get all the environment variables in this machine and set each one of them as a build-arg argument.
For example, if the env variables are
ENV_VAR1=ENV_VALUE1
ENV_VAR2=ENV_VALUE2
ENV_VAR3=ENV_VALUE3
I want to build a string like this
docker build --build-arg ENV_VAR1=ENV_VALUE1 --build-arg ENV_VAR2=ENV_VALUE2 --build-arg ENV_VAR1=ENV_VALUE1 .`
I was wondering how to wrap this repetition in a bash script something like this (please this is just a pseudocode):
docker build $(FOREACH get_output_of_env() AS $env DO `--build-arg $env` END) .
Is that anyhow possible?
Thanks in advance
Use an array:
dockerargs=()
for i in ENV_VAR1 ENV_VAR2 ENV_VAR3; do
dockerargs+=(--build-arg "$i=${!i}")
done
docker build "${dockerargs[#]}" ...
If you really want to use how to iterate over env and do for i in $(compgen -e)
#!/bin/sh
cat > args < EOF
#!/bin/sh
EOF
env -0 >> args
sed -i s'#^#--build-arg #g' args
tr '\n' ' '
sed -i s'#^#docker build#' args
Then just execute "args" as another shell script. I admit that I haven't tested this, but I can't see too many reasons why it shouldn't work.
Does anyone know how to show git username in the terminal?
I am using the following bash script for the branch, but, since I have several accounts I would like to show as well username or user email
BTW, I know I can use git config --global --list. The idea is to see the info in the terminal without having to check every time, as with the branch
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u#\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "
You can use git config --get to get a single configuration value, like the username. Then, you can wrap it in a function:
parse_git_user() {
git config --get user.email
}
And then you can incorporate it into the prompt (PS1) in any format you wish. E.g.:
export PS1="\u#\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] ($(parse_git_user))$ "
# Here -----------------------------------------------------------^
I suspect you want to make sure you get the correct user.email for each of your projects? #Mureinik eloquently answered the question, but I think this may help you or someone else searching.
Rather than have the user.name in your prompt, I suggest you set it based on the remote url. That way it should just workâ˘.
It works by using a zsh hook every time you change into a directory.
autoload -Uz add-zsh-hook
set-git-email() {
if [ -d .git ]; then
remote=`git remote -v | awk '/\(push\)$/ {print $2}'`
if [[ $remote == git#git.server.com:* ]]; then
git config user.email user#email.com
fi
fi
}
add-zsh-hook chpwd set-git-email
set-git-email
I have the following script. Unfortunately I not able to get it run on Jenkins.
#!/bin/bash
function pushImage () {
local serviceName=$1
local version=$(getImageVersionTag $serviceName)
cd ./dist/$serviceName
docker build -t $serviceName .
docker tag $serviceName gcr.io/$PROJECT_ID/$serviceName:$version
docker tag $serviceName gcr.io/$PROJECT_ID/$serviceName:latest
docker push gcr.io/$PROJECT_ID/$serviceName
cd ../..
}
function getImageVersionTag () {
local serviceName=$1
if [ $BUILD_ENV = "dev" ];
then
echo $(timestamp)
else
if [ $serviceName = "api" ];
then
echo $(git tag -l --sort=v:refname | tail -1 | awk -F. '{print $1"-"$2"-"$3"-"$4}')
else
echo $(git tag -l --sort=refname | tail -1 | awk -F. '{print $1"-"$2"-"$3"-"$4}')
fi
fi
}
function timestamp () {
echo $(date +%s%3N)
}
set -x
## might be api or static-content
pushImage $1
I'm receiving this error on Jenkins
10:10:17 + sh push-image.sh api
10:10:17 push-image.sh: 2: push-image.sh: Syntax error: "(" unexpected
I already configured Jenkins global parameter to /bin/bash as default shell execute environment, but still having same error.
The main issue here in usage of functions, as other scripts that has been executed successfully don't have any.
How this can be fixed?
Short answer: make sure you're running bash and not sh
Long answer: sh (which is run here despite your effort of adding a shebang) is the bourne shell and does not understand the function keyword. Simply removing it will solve your issue.
Please note however that all your variable expansions should be quoted to prevent against word splitting and globbing. Ex: local version=$(getImageVersionTag "$serviceName")
See shellcheck.net for more problems appearing in your file (usage of local var=$(...)) and explicit list of snippets which are missing quotes.
I have following bash function in my ~/.bashrc
function gitlab {
MSG='first commit'
CMD="git commit -m '${MSG}'"
echo $CMD
$CMD
}
Here is the result
$ gitlab
git commit -m 'first commit'
error: pathspec 'commit'' did not match any file(s) known to git.
What's the fix?
BASH FAQ entry #50: "I'm trying to put a command in a variable, but the complex cases always fail!"
Definitely read BashFAQ/050 that Ignacio linked to.
You could try this, though:
function gitlab {
local PS4='Running: '
local msg='first commit'
bash -xc "git commit -m '$msg'"
}
I suppose you should use \" instead of ' so it should be something like:
CMD="git commit -m \"${MSG}\""
Try putting your commit message in double quotes, as single and double quotes mean different things to bash.
function gitlab {
MSG="first commit"
CMD=`git commit -m \"${MSG}\"`
echo $CMD
$CMD
}