1

In a Gitlab pipeline, I have to get the date the pipeline is running, for example, 25 of August. I have to then make two variables, and get the first of that month, and the last of the month. So in this case, it must be variable 1 = August 1st, variable 2 = August 31st, and I need to echo these values when the pipeline is running.

The method I had in mind was:

  1. Get the date/time the pipeline is running using the inbuilt variable CI_JOB_STARTED_AT .
  2. Export this value to Python script
  1. Since CI_JOB_STARTED_AT is always in this format 2021-11-05T20:12:38Z, we can manipulate the data using a slice, and return the the values for the two variables.
  2. Two variables receive the values and echo the value while the pipeline is running.

What I don't know is if it's the ideal approach or if I can do it using the script in the pipeline. Can someone please tell me how I can approach this problem?

Thanks in advance

TM1
  • 35
  • 9

1 Answers1

0

You can probably just encapsulate it all in a single Python script.

So, a simple CI job defined like so:

myjob:
  image: python:3.10
  before_script: "pip install dateutil"
  script: "./myscript.py"

And a script with the following contents:

import calendar
import os

from dateutil.parser import parse


job_start = os.environ['CI_JOB_STARTED_AT']  # or CI_PIPELINE_CREATED_AT
job_start_date = parse(job_start)

month_name = calendar.month_name[job_start_date.month]

# ref: https://stackoverflow.com/a/43663/5747944
_, last_of_month = calendar.monthrange(job_start_date.year, job_start_date.month)

# Print current day and month
print(month_name, job_start_date.day)

# print first day of the month
print(month_name, '1')

# print last day of the month
print(month_name, last_of_month)

Assuming the date in CI_JOB_STARTED_AT is 2021-11-05T20:12:38Z, the job output from the script would be as follows:

November 5
November 1
November 30

However, be aware that a job start time may not necessarily be the same time the pipelines was created. So you may consider using the variable CI_PIPELINE_CREATED_AT instead.


On a side note, it's kind of questionable why you would need to do this in a job, since GitLab itself always stores (and shows in the UI) the pipeline start date and it can be retrieved via the pipelines API.

sytech
  • 29,298
  • 3
  • 45
  • 86