GitLabgitlab-org
cli
main
1package init
3import (
4 "context"
5 "errors"
6 "fmt"
7 "io/fs"
8 "os/exec"
9 "path/filepath"
10 "regexp"
11 "strings"
13 "github.com/MakeNowJust/heredoc/v2"
14 "github.com/spf13/cobra"
16 gitlab "gitlab.com/gitlab-org/api/client-go/v3"
18 "gitlab.com/gitlab-org/cli/internal/api"
19 "gitlab.com/gitlab-org/cli/internal/cmdutils"
20 "gitlab.com/gitlab-org/cli/internal/config"
21 "gitlab.com/gitlab-org/cli/internal/glrepo"
22 "gitlab.com/gitlab-org/cli/internal/iostreams"
23 "gitlab.com/gitlab-org/cli/internal/mcpannotations"
24)
26var errUnsupportedAuth = errors.New("init command does not support this authentication method")
28type options struct {
29 io *iostreams.IOStreams
30 baseRepo func() (glrepo.Interface, error)
31 apiClient func(repoHost string) (*api.Client, error)
32 exec cmdutils.Executor
34 stateName string
35 binary string
36 directory string
37 initArgs []string
38}
40func NewCmd(f cmdutils.Factory) *cobra.Command {
41 opts := &options{
42 io: f.IO(),
43 baseRepo: f.BaseRepo,
44 apiClient: f.ApiClient,
45 exec: f.Executor(),
46 }
48 cmd := &cobra.Command{
49 Use: "init <state> [flags]",
50 Short: `Initialize OpenTofu or Terraform.`,
51 Long: heredoc.Docf(`
52 Configures the GitLab HTTP backend for OpenTofu or Terraform state
53 and runs %[1]stofu init%[1]s. You must run this command from a GitLab
54 project repository.
56 If glab is installed as a snap, it cannot run OpenTofu or Terraform
57 binaries installed on the host or by other snaps. Place the binary in
58 your home directory and pass its path with %[1]s--binary%[1]s.
59 `, "`"),
60 Example: heredoc.Doc(`
61 # Initialize state with name production in working directory
62 glab opentofu init production
64 # Initialize state with name production in infra/ directory
65 glab opentofu init production -d infra/
67 # Initialize state with name production with Terraform
68 glab opentofu init production -b terraform
70 # Initialize state with name production with reconfiguring state
71 glab opentofu init production -- -reconfigure`),
72 Args: cobra.MinimumNArgs(1),
73 Annotations: map[string]string{
74 mcpannotations.Destructive: "true",
75 },
76 RunE: func(cmd *cobra.Command, args []string) error {
77 opts.complete(args)
79 return opts.run(cmd.Context())
80 },
81 }
83 fl := cmd.Flags()
84 fl.StringVarP(&opts.binary, "binary", "b", "tofu", "Name or path of the OpenTofu or Terraform binary to use for the initialization.")
85 fl.StringVarP(&opts.directory, "directory", "d", ".", "Directory of the OpenTofu or Terraform project to initialize.")
87 return cmd
88}
90func (o *options) complete(args []string) {
91 o.stateName = args[0]
92 o.initArgs = args[1:]
93}
95func (o *options) run(ctx context.Context) error {
96 repo, err := o.baseRepo()
97 if err != nil {
98 return err
99 }
101 apiClient, err := o.apiClient(repo.RepoHost())
102 if err != nil {
103 return err
104 }
106 client := apiClient.Lab()
107 baseURL := client.BaseURL()
108 stateAPIURL := baseURL.JoinPath("projects", gitlab.PathEscape(repo.FullName()), "terraform", "state", gitlab.PathEscape(o.stateName))
109 args := []string{
110 fmt.Sprintf(`-chdir=%s`, o.directory),
111 "init",
112 fmt.Sprintf(`-backend-config=address=%s`, stateAPIURL.String()),
113 fmt.Sprintf(`-backend-config=lock_address=%s`, stateAPIURL.JoinPath("lock").String()),
114 fmt.Sprintf(`-backend-config=unlock_address=%s`, stateAPIURL.JoinPath("lock").String()),
115 `-backend-config=lock_method=POST`,
116 `-backend-config=unlock_method=DELETE`,
117 `-backend-config=retry_wait_min=5`,
118 }
120 authArgs, err := authBackendConfig(ctx, apiClient)
121 if err != nil {
122 return err
123 }
124 args = append(args, authArgs...)
125 args = append(args, o.initArgs...)
127 err = o.exec.Exec(ctx, o.binary, args, nil)
128 // exec only searches $PATH for bare names; a missing path fails with fs.ErrNotExist instead.
129 if (errors.Is(err, exec.ErrNotFound) || errors.Is(err, fs.ErrNotExist)) && config.SnapConfined() {
130 return fmt.Errorf("%w\n\nglab is running under snap confinement and cannot see binaries installed on the host or by other snaps.\nPlace the binary in your home directory and pass its path, for example: glab opentofu init %s --binary ~/%s", err, shellQuote(o.stateName), shellQuote(filepath.Base(o.binary)))
131 }
132 return err
133}
135// authBackendConfig renders the backend configuration OpenTofu needs to
136// authenticate against the state API.
137func authBackendConfig(ctx context.Context, apiClient *api.Client) ([]string, error) {
138 // Password auth carries no token and needs a username from the API, so it
139 // cannot come from Credential.
140 if as, ok := apiClient.AuthSource().(*gitlab.PasswordCredentialsAuthSource); ok {
141 currentUser, _, err := apiClient.Lab().Users.CurrentUser(gitlab.WithContext(ctx))
142 if err != nil {
143 return nil, fmt.Errorf("unable to retrieve current user: %w", err)
144 }
146 return []string{
147 fmt.Sprintf(`-backend-config=username=%s`, currentUser.Username),
148 fmt.Sprintf(`-backend-config=password=%s`, as.Password),
149 }, nil
150 }
152 cred, err := apiClient.Credential(ctx)
153 switch {
154 case errors.Is(err, api.ErrUnsupportedAuthSource):
155 // Name the requirement rather than passing on the wrapped Go type.
156 return nil, errUnsupportedAuth
157 case errors.Is(err, api.ErrUnauthenticated):
158 // Already actionable, and wrapping it reads as two errors.
159 return nil, err
160 case err != nil:
161 return nil, fmt.Errorf("unable to retrieve an access token to authenticate OpenTofu: %w", err)
162 }
164 switch cred.Kind {
165 case api.CredentialJobToken:
166 return []string{fmt.Sprintf(`-backend-config=headers={%q = %q}`, gitlab.JobTokenHeaderName, cred.Token)}, nil
167 case api.CredentialPAT, api.CredentialOAuth2:
168 return []string{fmt.Sprintf(`-backend-config=headers={"Authorization" = "Bearer %s"}`, cred.Token)}, nil
169 default:
170 return nil, fmt.Errorf("%w: %s", errUnsupportedAuth, cred.Kind)
171 }
172}
174var shellSafe = regexp.MustCompile(`^[A-Za-z0-9_./-]+$`)
176// shellQuote single-quotes s unless it only has characters the shell treats literally.
177func shellQuote(s string) string {
178 if shellSafe.MatchString(s) {
179 return s
180 }
181 return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
182}
Diagnostics8 git calls · 29 ms
CallStatusSizeTime029 ms
discover200185 B3 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs 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 KiB3 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=3 git.response.bytes=59849 git.response.cache=UPDATING git.response.duration_ms=3 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 · 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=32926 git.response.cache=HIT git.response.duration_ms=2 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=44Open 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=1 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=fb03183b7909876778f740d196d7516811003517Open pack map
fetchtree:0200171 B · hit3 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=171 git.response.cache=HIT git.response.duration_ms=3 git.fetch.filter=tree:0 git.fetch.wants=2855fba468423062dfdcf0df3b48b51ba83b86fc 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=171 git.pkt.payload.max=144 git.sideband.band1.bytes=144 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=144 git.pack.trailer=9cf2753898214ee7a00e442cff7d52bb582cde2eOpen pack map
fetchtree:0200135 B · hit4 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=135 git.response.cache=HIT git.response.duration_ms=4 git.fetch.filter=tree:0 git.fetch.wants=d696f1306cf5765e7ec77a88e29ce68d08b51093 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=135 git.pkt.payload.max=108 git.sideband.band1.bytes=108 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=1 git.pack.bytes=108 git.pack.trailer=0efd523d8b97287959a6006de564aff42f32db4bOpen pack map
fetch2002.3 KiB · hit16 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=16 git.response.bytes=2357 git.response.cache=HIT git.response.duration_ms=16 git.fetch.wants=ff088f73cbbee411c06f8969f1b01845af59cb86 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=2357 git.pkt.payload.max=2330 git.sideband.band1.bytes=2330 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
- a5e2ce48fd92efad
- Request
- 90209554…
- 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