Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions modules/platform/platform.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@ const resolvePrincipalIDFnID = "resolve_principal_id"

func ModuleInit(reg registry.ModuleRegistrar) {
reg.RegisterFlagResolveFn(resolvePrincipalIDFnID, resolvePrincipalID)
reg.RegisterWorkflow("project_copy", projectCopy)
}
77 changes: 77 additions & 0 deletions modules/platform/project-copy.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Copy a project (CD core)

`harness migrate project:project` copies project-scoped CD configuration from one project to another in the same org. The CLI reads the source and writes the destination. Delegates, executions, code repositories, GitOps, and feature flags are not copied.

```sh
harness migrate project:project \
--from source_project \
--to destination_project \
--org example_org \
--resources cd-core

harness migrate project:project \
--from source_project \
--to destination_project \
--org example_org \
--resources cd-core \
--apply
```

The first command is a plan. Nothing is written. `--apply` creates the destination project when it does not exist, then copies resources. `--from` and `--to` are required and must differ. The profile's default project is not used. Pass `--org` for the shared org.

## What is copied

Order: project, secrets, connectors, services, environments, infrastructures, service overrides, templates, pipelines, input sets, triggers, policies, policy sets.

- Inline `SecretText` is created with the placeholder value `123456`. The source value is not read. Update each listed secret before running the destination project.
- Reference secrets copy the secret manager and reference path. A destination secret with a different path is a conflict.
- Other secret types are reported as blocked and skipped.
- Templates are copied in dependency order using project-scoped `templateRef` values.
- Triggers are created disabled.
- Git-backed entities are skipped and the command exits nonzero so the skip is not treated as a complete copy.
- Org and account references, including `account.` and `org.` identifiers, are reported and left in place.
- Delegate selectors are checked against connected delegates (`CONNECTED`). Delegates themselves are not installed.
- Identical destination resources are skipped. A same identifier with different content aborts the copy before any write.
- A create failure stops the copy. Re-run `--apply` to continue; matching resources already written are skipped.

## Test against a source project

Use a project in an org your token can read and write. Pick a destination identifier that does not already exist.

```sh
task build
./bin/harness migrate project:project \
--from YOUR_SOURCE_PROJECT \
--to YOUR_DESTINATION_PROJECT \
--org YOUR_ORG \
--resources cd-core
```

Read the plan. Then apply:

```sh
./bin/harness migrate project:project \
--from YOUR_SOURCE_PROJECT \
--to YOUR_DESTINATION_PROJECT \
--org YOUR_ORG \
--resources cd-core \
--apply
```

After apply, replace each inline secret:

```sh
./bin/harness update secret SECRET_ID --org YOUR_ORG --project YOUR_DESTINATION_PROJECT --set value='the-real-value'
```

Check the destination in the UI, or:

```sh
./bin/harness list pipeline --org YOUR_ORG --project YOUR_DESTINATION_PROJECT
./bin/harness list connector --org YOUR_ORG --project YOUR_DESTINATION_PROJECT
./bin/harness list secret --org YOUR_ORG --project YOUR_DESTINATION_PROJECT
```

Run the same `--apply` command again. Resources that match should be reported as `skip`, and inline secrets you already updated should not be reset to `123456`.

`--out report.json` writes the report to a new file and refuses to overwrite an existing one. `--format json` prints the same report to stdout.
154 changes: 154 additions & 0 deletions modules/platform/project_copy.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
// Copyright © 2026 Harness Inc.
// SPDX-License-Identifier: Apache-2.0

package platform

import (
"encoding/json"
"errors"
"fmt"
"io"
"os"

"github.com/harness/cli/v3/modules/platform/projectcopy"
"github.com/harness/cli/v3/pkg/cmdctx"
)

func projectCopy(ctx *cmdctx.Ctx) error {
scope, err := projectCopyScope(ctx)
if err != nil {
return err
}
out, closeOut, err := openProjectCopyOut(ctx)
if err != nil {
return err
}
if closeOut != nil {
defer closeOut()
}
report, copyErr := projectcopy.Copy(ctx.Context, projectcopy.NewTransport(ctx.Auth), scope, projectCopyShouldApply(ctx))
if err := renderProjectCopyReport(out, reportFormat(ctx), report); err != nil {
if copyErr != nil {
return copyErr
}
return errors.New("cannot write project planning report")
}
return copyErr
}

func projectCopyShouldApply(ctx *cmdctx.Ctx) bool {
if cmdctx.GetBool(ctx.FlagValues, "dry-run") {
return false
}
return cmdctx.GetBool(ctx.FlagValues, "apply")
}

func reportFormat(ctx *cmdctx.Ctx) string {
if ctx.FormatFlags.Format == "" {
return "text"
}
return ctx.FormatFlags.Format
}

func openProjectCopyOut(ctx *cmdctx.Ctx) (io.Writer, func(), error) {
if ctx.FormatFlags.OutFile == "" {
return os.Stdout, nil, nil
}
f, err := os.OpenFile(ctx.FormatFlags.OutFile, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600)
if err != nil {
return nil, nil, errors.New("cannot create report: --out must name a new file")
}
return f, func() { _ = f.Close() }, nil
}

func projectCopyScope(ctx *cmdctx.Ctx) (projectcopy.Scope, error) {
if ctx.ProvidedFlags["dry-run"] && !cmdctx.GetBool(ctx.FlagValues, "dry-run") && !projectCopyShouldApply(ctx) {
return projectcopy.Scope{}, errors.New("pass --apply to copy; --dry-run=false does not write")
}
if cmdctx.GetString(ctx.FlagValues, "resources") != "cd-core" {
return projectcopy.Scope{}, errors.New("select --resources cd-core")
}
if ctx.Auth == nil {
return projectcopy.Scope{}, errors.New("resolved authentication required")
}
if f := ctx.FormatFlags.Format; f != "" && f != "text" && f != "json" {
return projectcopy.Scope{}, errors.New("project planning supports --format text or json")
}
if ctx.ProvidedFlags["project"] || (ctx.Level != "" && ctx.Level != "project") {
return projectcopy.Scope{}, errors.New("use explicit --from/--to projects, not --project or a different --level")
}
if len(ctx.Args) > 0 || ctx.Id != "" {
return projectcopy.Scope{}, errors.New("project planning accepts flags only")
}
scope := projectcopy.Scope{Account: ctx.Auth.AccountID, Org: ctx.Auth.OrgID, Source: ctx.MigrateFrom, Destination: ctx.MigrateTo}
return scope, scope.Validate()
}

func writeProjectCopyReport(ctx *cmdctx.Ctx, report projectcopy.Report) error {
out, closeOut, err := openProjectCopyOut(ctx)
if err != nil {
return err
}
if closeOut != nil {
defer closeOut()
}
if err := renderProjectCopyReport(out, reportFormat(ctx), report); err != nil {
return errors.New("cannot write project planning report")
}
return nil
}

func renderProjectCopyReport(w io.Writer, format string, r projectcopy.Report) error {
if format == "json" {
enc := json.NewEncoder(w)
enc.SetIndent("", " ")
return enc.Encode(r)
}
if r.Coverage == "cd-core" {
return renderCDCoreReport(w, r)
}
if _, err := fmt.Fprintf(w, "PARTIAL — read-only secret planning; apply unavailable\nAccount: %s; org: %s; source: %s; destination: %s\nSecret inventory complete: %t\nReadiness: %s\nNOT INVENTORIED: connectors, pipelines and all other project resources\n", r.Scope.Account, r.Scope.Org, r.Scope.Source, r.Scope.Destination, r.InventoryComplete, r.Readiness); err != nil {
return err
}
for _, item := range r.Secrets {
if _, err := fmt.Fprintf(w, "Secret #%d: %s — %s (%s)\n", item.Number, item.Type, item.Capability, item.Reason); err != nil {
return err
}
}
return nil
}

func renderCDCoreReport(w io.Writer, r projectcopy.Report) error {
if _, err := fmt.Fprintf(w, "cd-core %s\nAccount: %s; org: %s; source: %s; destination: %s\nReadiness: %s\n", r.Mode, r.Scope.Account, r.Scope.Org, r.Scope.Source, r.Scope.Destination, r.Readiness); err != nil {
return err
}
for _, item := range r.Results {
if _, err := fmt.Fprintf(w, "%s %s: %s", item.Kind, item.Identifier, item.Action); err != nil {
return err
}
if item.Reason != "" {
if _, err := fmt.Fprintf(w, " — %s", item.Reason); err != nil {
return err
}
}
if _, err := fmt.Fprintln(w); err != nil {
return err
}
}
for _, item := range r.DelegateSelectors {
if _, err := fmt.Fprintf(w, "delegate selector %s: %s — %s\n", item.Identifier, item.Action, item.Reason); err != nil {
return err
}
}
if len(r.SecretsPendingValue) > 0 {
if _, err := fmt.Fprintf(w, "Inline secrets were stored with placeholder value %s. Update each one before running the destination project:\n", projectcopy.InlineSecretPlaceholder); err != nil {
return err
}
for _, id := range r.SecretsPendingValue {
if _, err := fmt.Fprintf(w, "harness update secret %s --org %s --project %s --set value='...'\n", id, r.Scope.Org, r.Scope.Destination); err != nil {
return err
}
}
}
return nil
}
141 changes: 141 additions & 0 deletions modules/platform/project_copy_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
// Copyright © 2026 Harness Inc.
// SPDX-License-Identifier: Apache-2.0

package platform

import (
"bytes"
"os"
"path/filepath"
"strings"
"testing"

"github.com/harness/cli/v3/modules/platform/projectcopy"
"github.com/harness/cli/v3/pkg/auth"
"github.com/harness/cli/v3/pkg/cmdctx"
)

func copyContext() *cmdctx.Ctx {
return &cmdctx.Ctx{Auth: &auth.ResolvedAuth{AccountID: "fixture_account", OrgID: "fixture_org", ProjectID: "ignored_profile_project"}, MigrateFrom: "source", MigrateTo: "destination", FlagValues: map[string]any{"resources": "cd-core"}, ProvidedFlags: map[string]bool{}}
}

func TestProjectCopyRejectsUnavailableWorkBeforeTransport(t *testing.T) {
for _, tc := range []struct {
name string
modify func(*cmdctx.Ctx)
}{
{"dry-run disabled", func(c *cmdctx.Ctx) { c.SetFlag("dry-run", false) }},
{"unsupported format", func(c *cmdctx.Ctx) { c.FormatFlags.Format = "yaml" }},
{"mixed resources", func(c *cmdctx.Ctx) { c.SetFlag("resources", "secret,pipeline") }},
{"no selection", func(c *cmdctx.Ctx) { c.SetFlag("resources", "") }},
{"full", func(c *cmdctx.Ctx) { c.SetFlag("resources", "all") }},
{"identity", func(c *cmdctx.Ctx) { c.MigrateTo = c.MigrateFrom }},
{"source omitted", func(c *cmdctx.Ctx) { c.MigrateFrom = "" }},
{"destination omitted", func(c *cmdctx.Ctx) { c.MigrateTo = "" }},
{"project override", func(c *cmdctx.Ctx) { c.SetFlag("project", "other") }},
{"org level", func(c *cmdctx.Ctx) { c.Level = "org" }},
{"positional", func(c *cmdctx.Ctx) { c.Id = "unexpected" }},
{"malformed scope", func(c *cmdctx.Ctx) { c.MigrateFrom = "source/other" }},
} {
t.Run(tc.name, func(t *testing.T) {
c := copyContext()
tc.modify(c)
// A nil context and invalid API URL would panic/fail if validation reached HTTP.
if err := projectCopy(c); err == nil {
t.Fatal("unsupported work accepted")
}
})
}
c := copyContext()
c.SetFlag("apply", true)
if _, err := projectCopyScope(c); err != nil {
t.Fatal(err)
}
c = copyContext()
c.SetFlag("dry-run", true)
c.SetFlag("apply", true)
if projectCopyShouldApply(c) {
t.Fatal("dry-run must not apply")
}
if _, err := projectCopyScope(c); err != nil {
t.Fatal(err)
}
existing := filepath.Join(t.TempDir(), "report")
os.WriteFile(existing, []byte("kept"), 0600)
c = copyContext()
c.SetFlag("apply", true)
c.FormatFlags.OutFile = existing
if err := projectCopy(c); err == nil || !strings.Contains(err.Error(), "cannot create report") {
t.Fatalf("existing --out must fail before copy: %v", err)
}
if data, _ := os.ReadFile(existing); string(data) != "kept" {
t.Fatal("existing --out changed")
}
c = copyContext()
s, err := projectCopyScope(c)
if err != nil || s.Source != "source" || s.Destination != "destination" {
t.Fatal("profile project replaced explicit locations")
}
}

func TestProjectCopyReportsAndProtectedFiles(t *testing.T) {
c := copyContext()
scope, _ := projectCopyScope(c)
r := projectcopy.NewReport(scope)
r.Secrets = []projectcopy.Item{{Number: 1, Type: "SecretText", Capability: projectcopy.ReferenceOnly, Reason: "external reference configuration only"}}
for _, format := range []string{"text", "json"} {
t.Run(format, func(t *testing.T) {
var buf bytes.Buffer
if err := renderProjectCopyReport(&buf, format, r); err != nil {
t.Fatal(err)
}
if !strings.Contains(buf.String(), "PARTIAL") || !strings.Contains(buf.String(), "destination") || strings.Contains(buf.String(), "ignored_profile_project") {
t.Fatal("incorrect report scope/coverage")
}
c.FormatFlags = cmdctx.FormatFlags{Format: format, OutFile: filepath.Join(t.TempDir(), "report")}
if err := writeProjectCopyReport(c, r); err != nil {
t.Fatal(err)
}
info, _ := os.Stat(c.FormatFlags.OutFile)
if info.Mode().Perm() != 0600 {
t.Fatal("report permissions")
}
before, _ := os.ReadFile(c.FormatFlags.OutFile)
if err := writeProjectCopyReport(c, r); err == nil {
t.Fatal("existing report overwritten")
}
after, _ := os.ReadFile(c.FormatFlags.OutFile)
if !bytes.Equal(before, after) {
t.Fatal("existing data changed")
}
})
}
dir := t.TempDir()
protected := filepath.Join(dir, "profiles.yaml")
os.WriteFile(protected, []byte("SYNTHETIC_PROTECTED_INPUT"), 0600)
for _, kind := range []string{"direct", "symlink", "hardlink"} {
t.Run(kind, func(t *testing.T) {
out := protected
if kind != "direct" {
out = filepath.Join(dir, kind)
var err error
if kind == "symlink" {
err = os.Symlink(protected, out)
} else {
err = os.Link(protected, out)
}
if err != nil {
t.Fatal(err)
}
}
c.FormatFlags = cmdctx.FormatFlags{OutFile: out}
if err := writeProjectCopyReport(c, r); err == nil {
t.Fatal("protected alias accepted")
}
data, _ := os.ReadFile(protected)
if string(data) != "SYNTHETIC_PROTECTED_INPUT" {
t.Fatal("input overwritten")
}
})
}
}
Loading
Loading