How to get start time and endtime for a job or step as Buildkite variable

Hi Team,

I have a requirement where I need to get the start and end time of a job/step and post it via notify to slack.

It would be great to have that as a variable that can be directly injected but I am open to other solutions as well, if that is not available.

Thanks and Regards,
Ismail

Hey Ismail,

To achieve this workflow, you can use the GraphQL API to query the job’s start and finish times with the query shown below.

query GetJobRunTimeByBuild{
  build(slug: "org-slug/pipeline-slug/build-number") {
    jobs(first: 1, step: {key: "insert-key"}) {
      edges {
        node {
          ... on JobTypeCommand {
            startedAt
            finishedAt
          }
        }
      }
    }
  }
}

startedAt: DateTime when the job started running
finishedAt: DateTime when the job finished

Then extract this information then pass these values into a pipeline step for notifying Slack.

steps:
 - label: "Send Slack Message"
   command:   |
      startedAt="...."
      finishedAt"...."
      cat <<- YAML | buildkite-agent pipeline upload 
         steps:
           - label: "Notify slack about Job"
             command: echo  "Notify slack about Job"
             notify:
               - slack:
                   channels:
                     - "#general_test"
                   message: "The Job started at $$startedAt and finished at $$finishedAt"
      YAML