I'm running Gitlab locally on my own server with ip 192.168.100.10.
I try to write gitlab-ci.yml
for deploying a project to satge server with different ip like 192.168.208.8.
I want to create dynamic Gitlab environment URL, for example 192.168.208.8:$RANDOM_PORT
, but Gitlab does not fill $RANDOM_PORT
in this code here:
deploy-stage:
stage: deploy-stage
script:
- docker pull ${DESTINATION_REPOSITORY}:${TAG_COMMIT_VERSION}
- export RANDOM_PORT=$(shuf -i 1000-9999 -n 1);
- echo $RANDOM_PORT # echo 5075 and $RANDOM_PORT not empty
- docker run -d --name ${TAG_COMMIT_VERSION} -p $RANDOM_PORT:80 ${DESTINATION_REPOSITORY}:${TAG_COMMIT_VERSION}
environment :
name: main-stage
url: 192.168.208.8:$RANDOM_PORT # in this line random port in null
This is my gitlab-ci.yml
file :
variables:
BRANCH_NAME: ${CI_COMMIT_BRANCH}-
TAG_COMMIT_VERSION: ${BRANCH_NAME}${CI_COMMIT_SHORT_SHA}
TAG_VERSION: latest
DESTINATION_REPOSITORY: $NEXUS_URL/my-project-name
image: docker:latest
services:
- docker:dind
stages:
- build
- docker-image
- deploy-stage
build:
stage: build
image: node:16.10.0-alpine
script:
- npm install
- npm run build
artifacts:
paths:
- build/
- nginx.conf
expire_in: 1 hour
docker-image:
stage: docker-image
dependencies:
- build
script:
- echo "building docker image ......"
- docker build --pull -t ${DESTINATION_REPOSITORY}:${TAG_COMMIT_VERSION} .
- docker push ${DESTINATION_REPOSITORY}:${TAG_COMMIT_VERSION}
deploy-stage:
stage: deploy-stage
script:
- docker pull ${DESTINATION_REPOSITORY}:${TAG_COMMIT_VERSION}
- export RANDOM_PORT=$(shuf -i 1000-9999 -n 1);
- echo $RANDOM_PORT # echo 5075 and $RANDOM_PORT not empty
- docker run -d --name ${TAG_COMMIT_VERSION} -p $RANDOM_PORT:80 ${DESTINATION_REPOSITORY}:${TAG_COMMIT_VERSION}
environment :
name: main-stage
url: 192.168.208.8:$RANDOM_PORT # in this line random port in null
I try this line 192.168.208.8:$RANDOM_PORT
and expected to create this value: 192.168.208.8:5075
It is possible to set a dynamic environment url in Gitlab(depending on version of Gitlab you are using)
What variable you set in script section cannot be accessed outside.
Make use of
artifacts:reports:dotenv
Introduced in GitLab 12.9
The dotenv report collects a set of environment variables as artifacts.
Gitlab parses the deploy.env report artifact, registers a list of variables as runtime-created, sets $RANDOM_PORT to the environment URL.
deploy-stage:
stage: deploy-stage
script:
- docker pull ${DESTINATION_REPOSITORY}:${TAG_COMMIT_VESRION}
- RANDOM_PORT=$(shuf -i 1000-9999 -n 1);
- echo $RANDOM_PORT
- echo "RANDOM_PORT=$RANDOM_PORT" >> deploy.env
- docker run -d --name ${TAG_COMMIT_VESRION} -p $RANDOM_PORT:80 ${DESTINATION_REPOSITORY}:${TAG_COMMIT_VESRION}
artifacts:
reports:
dotenv: deploy.env
enviroment :
name: main-stage
url: 192.168.208.8:$RANDOM_PORT