GitLabgitlab-org

cli

main
ply9 git calls390 ms100 KiB7 cachedprotocol v2
172 lines6.0 KiBRaw
1package create
3import (
4 "context"
5 "time"
7 "github.com/MakeNowJust/heredoc/v2"
8 "github.com/spf13/cobra"
10 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
12 "gitlab.com/gitlab-org/cli/internal/api"
13 "gitlab.com/gitlab-org/cli/internal/cmdutils"
14 "gitlab.com/gitlab-org/cli/internal/cmdutils/tokenduration"
15 "gitlab.com/gitlab-org/cli/internal/commands/service-account/serviceaccountutils"
16 "gitlab.com/gitlab-org/cli/internal/glrepo"
17 "gitlab.com/gitlab-org/cli/internal/iostreams"
18 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
21type options struct {
22 io *iostreams.IOStreams
23 apiClient func(repoHost string) (*api.Client, error)
24 baseRepo func() (glrepo.Interface, error)
26 account string
27 name string
28 scopes []string
29 description string
30 descriptionSet bool
31 duration tokenduration.TokenDuration
32 expiresAt time.Time
33 expiresAtSet bool
34 group string
35 outputFormat string
38func NewCmd(f cmdutils.Factory) *cobra.Command {
39 opts := &options{
40 io: f.IO(),
41 apiClient: f.ApiClient,
42 baseRepo: f.BaseRepo,
43 duration: tokenduration.TokenDuration(30 * 24 * time.Hour),
44 }
46 cmd := &cobra.Command{
47 Use: "create <account-id | username> <name> [flags]",
48 Short: "Create a token for a service account.",
49 Args: cobra.ExactArgs(2),
50 ValidArgsFunction: cobra.NoFileCompletions,
51 Long: heredoc.Docf(`
52 Create a personal access token for a service account of a project or a group.
54 - The token value is printed only once and cannot be retrieved later. It is the only output on stdout, and the token details go to stderr.
55 - At least one scope is required. For the scopes you can grant, see https://docs.gitlab.com/security/tokens/access_token_scopes/.
56 - The token expires after %[1]s--duration%[1]s, 30 days by default, at 00:00 UTC. Use %[1]s--expires-at%[1]s for a specific date instead.
57 - A numeric account argument is always treated as an ID.
58 `, "`"),
59 Example: heredoc.Doc(`
60 # Create a token for service account 42 of the current project
61 glab service-account token create 42 ci --scope api
63 # Create a read-only token that expires in a week, finding the account by its username
64 glab service-account token create release-bot ci-reader --scope read_api,read_repository --duration 7d
66 # Create a token for a group's service account that expires at the end of 2027
67 glab service-account token create 42 deploy --scope api --expires-at 2027-12-31 --group my-group
69 # Create a token and store its value in a variable
70 TOKEN=$(glab service-account token create 42 ci --scope api)`),
71 Annotations: map[string]string{
72 // Creating a token prints a secret, so this command is kept out of MCP,
73 // as glab token create is.
74 mcpannotations.Exclude: "true",
75 },
76 RunE: func(cmd *cobra.Command, args []string) error {
77 if err := opts.complete(cmd, args); err != nil {
78 return err
79 }
81 return opts.run(cmd.Context())
82 },
83 }
85 cmdutils.EnableRepoOverride(cmd, f)
87 fl := cmd.Flags()
88 fl.StringVarP(&opts.group, "group", "g", "", "Create a token for a service account of a `group` instead of a project. Accepts a group ID or full path.")
89 fl.StringSliceVarP(&opts.scopes, "scope", "S", nil, "Scope to grant the token. Multiple scopes can be comma-separated or specified by repeating the flag.")
90 fl.StringVar(&opts.description, "description", "", "Description of the token.")
91 fl.VarP(&opts.duration, "duration", "D", "Sets the token lifetime in days. Accepts: days (30d), weeks (4w), or hours in multiples of 24 (24h, 168h, 720h). Maximum: 365d. The token expires at midnight UTC on the calculated date.")
92 fl.TimeVarP(&opts.expiresAt, "expires-at", "E", time.Time{}, []string{time.DateOnly}, "Expiry date of the token, as YYYY-MM-DD. The token expires at midnight UTC on that date.")
94 cobra.CheckErr(cmd.MarkFlagRequired("scope"))
96 cmdutils.EnableJSONOutput(cmd, opts.io, &opts.outputFormat, "Format output as 'text' for the token value, 'json' for the token with its details.")
97 cmd.MarkFlagsMutuallyExclusive("duration", "expires-at")
98 cmd.MarkFlagsMutuallyExclusive("repo", "group")
100 return cmd
103func (o *options) complete(cmd *cobra.Command, args []string) error {
104 o.account = args[0]
105 o.name = args[1]
107 fl := cmd.Flags()
108 o.descriptionSet = fl.Changed("description")
109 o.expiresAtSet = fl.Changed("expires-at")
111 group, err := cmdutils.GroupOverride(cmd)
112 if err != nil {
113 return err
114 }
115 o.group = group
117 return nil
120func (o *options) run(ctx context.Context) error {
121 client, scope, err := serviceaccountutils.NewClient(o.baseRepo, o.apiClient, o.group)
122 if err != nil {
123 return err
124 }
126 accountID, err := serviceaccountutils.ResolveID(ctx, client, scope, o.account)
127 if err != nil {
128 return cmdutils.WrapError(err, "failed to create service account token")
129 }
131 expiry := o.duration.CalculateExpirationDate()
132 if o.expiresAtSet {
133 expiry = o.expiresAt
134 }
135 expiresAt := new(gitlab.ISOTime(expiry))
137 var description *string
138 if o.descriptionSet {
139 description = &o.description
140 }
142 var token *gitlab.PersonalAccessToken
143 if scope.Group != "" {
144 token, _, err = client.Groups.CreateServiceAccountPersonalAccessToken(scope.Group, accountID, &gitlab.CreateServiceAccountPersonalAccessTokenOptions{
145 Name: &o.name,
146 Description: description,
147 Scopes: &o.scopes,
148 ExpiresAt: expiresAt,
149 }, gitlab.WithContext(ctx))
150 } else {
151 token, _, err = client.Projects.CreateProjectServiceAccountPersonalAccessToken(scope.Project, accountID, &gitlab.CreateProjectServiceAccountPersonalAccessTokenOptions{
152 Name: &o.name,
153 Description: description,
154 Scopes: &o.scopes,
155 ExpiresAt: expiresAt,
156 }, gitlab.WithContext(ctx))
157 }
158 if err != nil {
159 return cmdutils.WrapError(err, "failed to create service account token")
160 }
162 if o.outputFormat == "json" {
163 return o.io.PrintJSON(token)
164 }
166 if err := serviceaccountutils.PrintToken(o.io, token); err != nil {
167 return err
168 }
169 o.io.LogErrorf("%s Created token %d for service account %d in %s. Store the token value now. It is not shown again.\n", o.io.Color().WarnIcon(), token.ID, accountID, scope)
171 return nil
Diagnostics9 git calls · 390 ms
CallStatusSizeTime0390 ms
discover200185 B7 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=185
git.server.agent=git/2.56.g1891de4-Linux
git.server.object_format=sha1
git.server.caps=agent ls-refs fetch server-option object-format
git.server.fetch=shallow wait-for-done filter
git.protocol.version=2
git.pkt.frames=9
git.pkt.data=7
git.pkt.flush=2
git.pkt.delim=0
git.pkt.bytes=185
git.pkt.payload.max=35
ls-refs20058 KiB · hit6 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=6
git.response.bytes=59849
git.response.cache=HIT
git.response.duration_ms=6
git.protocol.version=2
git.pkt.frames=731
git.pkt.data=730
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=59849
git.pkt.payload.max=143
git.ls_refs.count=730
git.ls_refs.head=refs/heads/main
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit2 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=2
git.response.bytes=4273
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=combine:blob:none+tree:2
git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9
git.fetch.haves.count=0
git.fetch.deepen=1
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=7
git.pkt.data=5
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=4273
git.pkt.payload.max=4173
git.sideband.band1.bytes=4173
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=11
git.pack.bytes=4173
git.fetch.wide.objects=11
git.fetch.wide.extra_bytes=3930
git.fetch.wide.blobs=0
fetchtree:0 · deepen 1020032 KiB · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=1
git.response.bytes=32926
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9
git.fetch.haves.count=0
git.fetch.deepen=10
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=22
git.pkt.data=20
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=32926
git.pkt.payload.max=32046
git.sideband.band1.bytes=32046
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=80
git.pack.bytes=32046
git.pack.ofs_delta=36
git.pack.ref_delta=0
git.pack.chain.max=2
git.pack.trailer=cb0bad5d7ffc514895d8b21c4dd470327f90bc91
git.pack.full=44
Open pack map
fetchtree:02001.8 KiB · hit1 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=1857
git.response.cache=HIT
git.response.duration_ms=1
git.fetch.filter=tree:0
git.fetch.wants=dce174ff8c632a19d17eea99c8a9b7c37fb2b592
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=1857
git.pkt.payload.max=1830
git.sideband.band1.bytes=1830
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=1830
git.pack.trailer=fb03183b7909876778f740d196d7516811003517
Open pack map
fetchtree:0200322 B · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=4
git.response.bytes=322
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=ba2caccf6c55211c6b29b98f40c2358479d91b1f
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=322
git.pkt.payload.max=295
git.sideband.band1.bytes=295
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=295
git.pack.trailer=3488e558d4708096e879feba968e084c249dbe22
Open pack map
fetchtree:0200223 B · hit4 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=223
git.response.cache=HIT
git.response.duration_ms=4
git.fetch.filter=tree:0
git.fetch.wants=41d72d07155f99e3acc572f8fe5ad26c802e4ddc
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=223
git.pkt.payload.max=196
git.sideband.band1.bytes=196
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=196
git.pack.trailer=d9c58aac50f427eb21501a81fe28c81c7c49ae44
Open pack map
fetchtree:0200138 B · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=370
git.response.bytes=138
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=17f358c7e70526844540138db141fe75ab4e5547
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=138
git.pkt.payload.max=111
git.sideband.band1.bytes=111
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=111
git.pack.trailer=4d47b7526a382df069b0f8eed3c03e424e930f30
Open pack map
fetch2002.3 KiB370 ms
git.upload-pack fetch
http.response.status_code=200
git.response.bytes=2360
git.response.cache=MISS
git.response.duration_ms=370
git.fetch.wants=d90d102a096b843f9d0d199ee9300b6c6144ceae
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=2360
git.pkt.payload.max=2333
git.sideband.band1.bytes=2333
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0

Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.

Remote
https://gitlab.com/gitlab-org/cli
Ref
refs/heads/main
Commit
0dd7574dce9e385c5c30540e6c15657adc6bdce9
cf-ray
a5e2ecee4dd277be
Request
f43a3c59…
Protocol
v2 · sha1
Agent
git/2.56.g1891de4-Linux
Filter
advertised
Fetch
shallow wait-for-done filter
Capabilities
agent ls-refs fetch server-option object-format