Creating personal access token through CLI

As mentioned in the following [page] Personal access tokens | GitLab) I’m looking for creating the PAT through CLI (programmatically) and having the expiry date of the token set to as min as possible (eg., less than or equal to 6 hour).

gitlab-rails runner "token = User.find_by_username('<user>').personal_access_tokens.create(scopes: ['read_user'], name: 'create_runner_pat', expires_at: 1.days.from_now); token.set_token('token-string-here123'); token.save!"

questions:

  1. When i set the expires_at value to 6 hours from_now it throws me an error. Can someone please confirm if it;s possible to set this value in hours?
  2. Also how we can generate the token.set_token string ? Any random string works here ?

I am no expert, anything but, more to save my own experience here for when I google it again in the future. 6 hours works and you do not set the token yourself, it generates on save.

Tested via gitlab-rails console.

token = root.personal_access_tokens.create()
irb(main):028> token = root.personal_access_tokens.create()
=>
#<PersonalAccessToken:0x00007ff6ba0e99e0

irb(main):029> token.name = “create_runner_pat”
=> “create_runner_pat”
irb(main):030> token.scopes << “create_runner”
=> [“create_runner”]
irb(main):031> token.expires_at = 6.hours.from_now
=> Mon, 15 Sep 2025 22:42:51.697945764 UTC +00:00
irb(main):032> token.save
=> true
irb(main):033> token.token
=> “”

Hopes this helps someone else, perhaps myself in the future.