diff --git a/cmd/mapt/cmd/aws/services/snc.go b/cmd/mapt/cmd/aws/services/snc.go index 8019e1a7b..8d52a885d 100644 --- a/cmd/mapt/cmd/aws/services/snc.go +++ b/cmd/mapt/cmd/aws/services/snc.go @@ -32,6 +32,9 @@ const ( operatorChannelDesc = "override the OLM subscription channel for an operator (--operator-channel serverless-operator=preview,nfd=4.17)" catalogSource = "catalog-source" catalogSourceDesc = "override the OLM catalog source with a custom index image (--catalog-source serverless-operator=quay.io/my-org/my-index:latest)" + + dnsSuffix = "dns-suffix" + dnsSuffixDesc = "DNS suffix used for the cluster endpoints instead of the nip.io default (e.g. sslip.io or a domain you control). The cluster IP is embedded in the hostname (api..), so the suffix must resolve wildcards of the instance public IP. Requires OpenShift >= 4.22 or 5.x (bundle support from crc-org/snc#1266)" ) func GetOpenshiftSNCCmd() *cobra.Command { @@ -97,9 +100,11 @@ func createSNC() *cobra.Command { PullSecretFile: viper.GetString(pullSecretFile), Timeout: viper.GetString(params.Timeout), ServiceEndpoints: params.NetworkServiceEndpoints(), - Profiles: profiles, - OperatorChannels: viper.GetStringMapString(operatorChannel), - CatalogSources: viper.GetStringMapString(catalogSource)}); err != nil { + Profiles: profiles, + OperatorChannels: viper.GetStringMapString(operatorChannel), + CatalogSources: viper.GetStringMapString(catalogSource), + DNSuffix: viper.GetString(dnsSuffix), + }); err != nil { return err } return nil @@ -116,6 +121,7 @@ func createSNC() *cobra.Command { flagSet.StringSliceP(sncProfile, "", []string{}, sncProfileDesc) flagSet.StringToStringP(operatorChannel, "", nil, operatorChannelDesc) flagSet.StringToStringP(catalogSource, "", nil, catalogSourceDesc) + flagSet.StringP(dnsSuffix, "", "", dnsSuffixDesc) params.AddComputeRequestFlags(flagSet) params.AddSpotFlags(flagSet) params.AddNetworkFlags(flagSet, awsParams.ServiceEndpointsDesc) diff --git a/cmd/mapt/cmd/ibmcloud/services/snc.go b/cmd/mapt/cmd/ibmcloud/services/snc.go index 82e4423e2..ea028eb4c 100644 --- a/cmd/mapt/cmd/ibmcloud/services/snc.go +++ b/cmd/mapt/cmd/ibmcloud/services/snc.go @@ -32,6 +32,8 @@ const ( catalogSource = "catalog-source" catalogSourceDesc = "override the OLM catalog source with a custom index image (--catalog-source serverless-operator=quay.io/my-org/my-index:latest)" + dnsSuffix = "dns-suffix" + dnsSuffixDesc = "DNS suffix used for the cluster endpoints instead of the nip.io default (e.g. sslip.io or a domain you control). The cluster IP is embedded in the hostname (api..), so the suffix must resolve wildcards of the instance floating IP. Requires OpenShift >= 4.22 or 5.x (bundle support from crc-org/snc#1266)" ) func GetOpenshiftSNCCmd() *cobra.Command { @@ -97,6 +99,7 @@ func createSNC() *cobra.Command { Profiles: profiles, OperatorChannels: viper.GetStringMapString(operatorChannel), CatalogSources: viper.GetStringMapString(catalogSource), + DNSuffix: viper.GetString(dnsSuffix), VpcID: viper.GetString(params.VpcID), }); err != nil { return err @@ -113,6 +116,7 @@ func createSNC() *cobra.Command { flagSet.StringSliceP(sncProfile, "", []string{}, sncProfileDesc) flagSet.StringToStringP(operatorChannel, "", nil, operatorChannelDesc) flagSet.StringToStringP(catalogSource, "", nil, catalogSourceDesc) + flagSet.StringP(dnsSuffix, "", "", dnsSuffixDesc) flagSet.StringP(params.VpcID, "", "", params.VpcIDDesc) params.AddComputeRequestFlags(flagSet) params.AddSpotFlags(flagSet) diff --git a/docs/aws/openshift-snc.md b/docs/aws/openshift-snc.md index 9c68967c0..552c13818 100644 --- a/docs/aws/openshift-snc.md +++ b/docs/aws/openshift-snc.md @@ -47,6 +47,38 @@ After the AMI is published and accessible by the account, we can use the followi After the above command succeeds the `kubeconfig` to access the deployed cluster will be available in `/tmp/snc/kubeconfig` +## Custom DNS suffix + +By default the cluster endpoints use `nip.io` to map the instance public IP to +resolvable hostnames (`api..nip.io`, `*.apps..nip.io`). Use the +`--dns-suffix` flag to replace it with another wildcard DNS service (e.g. +`sslip.io`) or a domain you control: + +``` +% mapt aws openshift-snc create \ + --version 4.21.0 \ + --project-name mapt-snc \ + --backed-url file:///home/tester/workspace \ + --conn-details-output /tmp/snc \ + --pull-secret-file /home/tester/Downloads/pull-secret \ + --dns-suffix sslip.io +``` + +The suffix is written to `/opt/crc/dns-suffix` on the instance and picked up by +the `ocp-custom-domain` service, which patches the console, OAuth, API server +and image registry endpoints accordingly. The generated `kubeconfig` and the +reported console URL follow the same suffix. + +> [!NOTE] +> +> - The suffix must be able to resolve the cluster hostnames: it is used as +> `api..` and `*.apps..`, where `` is the +> instance public IP. +> - This requires OpenShift >= 4.22 or 5.x: the bundle must include +> [crc-org/snc#1266](https://github.com/crc-org/snc/pull/1266) (backported +> to the 4.22 and 5.0 bundle branches). Older bundles ignore the setting +> and keep using `nip.io`, so `mapt` rejects the flag for them. + ## Profiles Profiles are optional addons that are installed on the SNC cluster after it is ready. Use the `--profile` flag to enable one or more profiles: diff --git a/docs/ibmcloud/openshift-snc.md b/docs/ibmcloud/openshift-snc.md index cd0afb150..a876cf54b 100644 --- a/docs/ibmcloud/openshift-snc.md +++ b/docs/ibmcloud/openshift-snc.md @@ -69,6 +69,28 @@ mapt ibmcloud openshift-snc create \ --pull-secret-file /path/to/pull-secret ``` +With a custom DNS suffix (instead of the `nip.io` default): + +```bash +mapt ibmcloud openshift-snc create \ + --version 4.22.14 \ + --project-name my-snc \ + --backed-url file:///workspace \ + --conn-details-output /tmp/snc \ + --pull-secret-file /path/to/pull-secret \ + --dns-suffix sslip.io +``` + +The suffix is written to `/opt/crc/dns-suffix` on the instance and picked up by +the `ocp-custom-domain` service, which patches the console, OAuth, API server +and image registry endpoints accordingly. The generated `kubeconfig` and the +reported console URL follow the same suffix. The suffix must resolve +`api..` and `*.apps..` — where `` is the instance +floating IP — and it requires OpenShift >= 4.22 or 5.x: the bundle must +include [crc-org/snc#1266](https://github.com/crc-org/snc/pull/1266) +(backported to the 4.22 and 5.0 bundle branches). Older bundles ignore the +setting and keep using `nip.io`, so `mapt` rejects the flag for them. + ### Outputs Files written to the path defined by `--conn-details-output`: @@ -78,7 +100,7 @@ Files written to the path defined by `--conn-details-output`: | `host` | Floating IP of the instance | | `username` | SSH username (`core`) | | `id_rsa` | Private key for the instance | -| `kubeconfig` | Kubeconfig for the cluster (API server points to the floating IP via nip.io) | +| `kubeconfig` | Kubeconfig for the cluster (API server points to the floating IP via the configured DNS suffix, `nip.io` by default) | ### Pulumi passphrase handling diff --git a/pkg/provider/aws/action/snc/snc.go b/pkg/provider/aws/action/snc/snc.go index ab690a57b..8b138d2cd 100644 --- a/pkg/provider/aws/action/snc/snc.go +++ b/pkg/provider/aws/action/snc/snc.go @@ -31,8 +31,8 @@ import ( "github.com/redhat-developer/mapt/pkg/target/service/snc/profile" "github.com/redhat-developer/mapt/pkg/util" "github.com/redhat-developer/mapt/pkg/util/logging" - "github.com/redhat-developer/mapt/pkg/util/ssh" resourcesUtil "github.com/redhat-developer/mapt/pkg/util/resources" + "github.com/redhat-developer/mapt/pkg/util/ssh" ) type openshiftSNCRequest struct { @@ -46,10 +46,11 @@ type openshiftSNCRequest struct { pullSecretFile *string serviceEndpoints []string allocationData *allocation.AllocationResult - profiles []string - operatorChannels map[string]string - catalogSources map[string]string - diskSize *int + profiles []string + operatorChannels map[string]string + catalogSources map[string]string + dnsSuffix string + diskSize *int } func (r *openshiftSNCRequest) validate() error { @@ -77,6 +78,9 @@ func Create(mCtxArgs *mc.ContextArgs, args *apiSNC.SNCArgs) (_ *apiSNC.SNCResult if err := profile.ValidateOperatorOverrides(args.OperatorChannels, args.CatalogSources); err != nil { return nil, err } + if err := apiSNC.ValidateDNSSuffix(args.Version, args.DNSuffix); err != nil { + return nil, err + } // Compose request prefix := util.If(len(args.Prefix) > 0, args.Prefix, "main") r := openshiftSNCRequest{ @@ -88,10 +92,11 @@ func Create(mCtxArgs *mc.ContextArgs, args *apiSNC.SNCArgs) (_ *apiSNC.SNCResult pullSecretFile: &args.PullSecretFile, timeout: &args.Timeout, serviceEndpoints: args.ServiceEndpoints, - profiles: args.Profiles, - operatorChannels: args.OperatorChannels, - catalogSources: args.CatalogSources, - diskSize: args.ComputeRequest.DiskSize} + profiles: args.Profiles, + operatorChannels: args.OperatorChannels, + catalogSources: args.CatalogSources, + dnsSuffix: args.DNSuffix, + diskSize: args.ComputeRequest.DiskSize} if args.Spot != nil { r.spot = args.Spot.Spot } @@ -162,7 +167,8 @@ func (r *openshiftSNCRequest) createCluster() (*apiSNC.SNCResults, error) { return apiSNC.Results(sr, r.prefix, r.mCtx.GetResultsOutputPath(), r.allocationData.SpotPrice, - r.disableClusterReadiness) + r.disableClusterReadiness, + r.dnsSuffix) } func (r *openshiftSNCRequest) deploy(ctx *pulumi.Context) error { @@ -276,7 +282,7 @@ func (r *openshiftSNCRequest) deploy(ctx *pulumi.Context) error { } } // Use kubeconfig as the readiness for the cluster - kubeconfig, err := kubeconfig(ctx, r.prefix, c, keyResources.PrivateKey, *r.version, r.disableClusterReadiness) + kubeconfig, err := kubeconfig(ctx, r.prefix, c, keyResources.PrivateKey, *r.version, r.disableClusterReadiness, r.dnsSuffix) if err != nil { return err } @@ -399,7 +405,8 @@ func (r *openshiftSNCRequest) userData(ctx *pulumi.Context, PublicIP: args[1].(string), SSMPullSecretName: *psName, SSMKubeAdminPasswordName: *kaPassName, - SSMDeveloperPasswordName: *devPassName}) + SSMDeveloperPasswordName: *devPassName, + DNSSuffix: r.dnsSuffix}) return *ccB64, err }).(pulumi.StringOutput) @@ -411,6 +418,7 @@ func kubeconfig(ctx *pulumi.Context, c *compute.Compute, mk *tls.PrivateKey, ocpVersion string, disableClusterReadiness bool, + dnsSuffix string, ) (pulumi.StringOutput, error) { // Once the cluster setup is comleted we // get the kubeconfig file from the host running the cluster @@ -460,7 +468,7 @@ func kubeconfig(ctx *pulumi.Context, func(args []interface{}) string { return strings.ReplaceAll(args[0].(string), "https://api.crc.testing:6443", - fmt.Sprintf("https://api.%s.nip.io:6443", args[1].(string))) + apiSNC.APIServerURL(args[1].(string), dnsSuffix)) }).(pulumi.StringOutput) return kubeconfig, nil } diff --git a/pkg/provider/ibmcloud/action/snc/cloud-config b/pkg/provider/ibmcloud/action/snc/cloud-config index d44cdd95b..ef9b6234b 100644 --- a/pkg/provider/ibmcloud/action/snc/cloud-config +++ b/pkg/provider/ibmcloud/action/snc/cloud-config @@ -33,3 +33,8 @@ write_files: owner: root:root path: /etc/sysconfig/crc-env permissions: '0644' +{{ if .DNSSuffix }}- path: /opt/crc/dns-suffix + content: {{ .DNSSuffix }} + owner: root:root + permissions: '0644' +{{ end }} diff --git a/pkg/provider/ibmcloud/action/snc/snc.go b/pkg/provider/ibmcloud/action/snc/snc.go index 4dfc30790..660b93bba 100644 --- a/pkg/provider/ibmcloud/action/snc/snc.go +++ b/pkg/provider/ibmcloud/action/snc/snc.go @@ -24,8 +24,8 @@ import ( "github.com/redhat-developer/mapt/pkg/util" "github.com/redhat-developer/mapt/pkg/util/file" "github.com/redhat-developer/mapt/pkg/util/logging" - "github.com/redhat-developer/mapt/pkg/util/ssh" resourcesUtil "github.com/redhat-developer/mapt/pkg/util/resources" + "github.com/redhat-developer/mapt/pkg/util/ssh" ) var kubeconfigURLPattern = regexp.MustCompile(`https://api\.crc\.testing:\d+`) @@ -34,12 +34,15 @@ var kubeconfigURLPattern = regexp.MustCompile(`https://api\.crc\.testing:\d+`) var cloudConfigTemplate []byte type dataValues struct { - Username string - PubKey string - PublicIP string - PullSecretB64 string + Username string + PubKey string + PublicIP string + PullSecretB64 string KubeAdminPassword string DeveloperPassword string + // DNS suffix for the cluster endpoints. When empty the SNC bundle keeps + // its own default (nip.io). + DNSSuffix string } type sncRequest struct { @@ -57,6 +60,7 @@ type sncRequest struct { profiles []string operatorChannels map[string]string catalogSources map[string]string + dnsSuffix string // bareMetal is true when the request needs nested virtualization. IBM // Cloud provides it on a bare metal server only. bareMetal bool @@ -77,6 +81,9 @@ func Create(mCtxArgs *mc.ContextArgs, args *apiSNC.SNCArgs) (*apiSNC.SNCResults, if err := profile.ValidateOperatorOverrides(args.OperatorChannels, args.CatalogSources); err != nil { return nil, err } + if err := apiSNC.ValidateDNSSuffix(args.Version, args.DNSuffix); err != nil { + return nil, err + } version := args.Version var offeringCRN string if version == "" { @@ -183,6 +190,7 @@ func Create(mCtxArgs *mc.ContextArgs, args *apiSNC.SNCArgs) (*apiSNC.SNCResults, profiles: args.Profiles, operatorChannels: args.OperatorChannels, catalogSources: args.CatalogSources, + dnsSuffix: args.DNSuffix, } cs := manager.Stack{ StackName: mCtx.StackNameByProject(apiSNC.StackName), @@ -198,7 +206,8 @@ func Create(mCtxArgs *mc.ContextArgs, args *apiSNC.SNCArgs) (*apiSNC.SNCResults, return apiSNC.Results(sr, &prefix, mCtx.GetResultsOutputPath(), nil, - r.disableClusterReadiness) + r.disableClusterReadiness, + r.dnsSuffix) } func Destroy(mCtxArgs *mc.ContextArgs) error { @@ -296,7 +305,7 @@ func (r *sncRequest) deploy(ctx *pulumi.Context) error { n.Floatingip.Address) kc, err := kubeconfig(ctx, r.prefix, n.Floatingip.Address, pk, - *r.version, r.disableClusterReadiness, []pulumi.Resource{fipAssoc}) + *r.version, r.disableClusterReadiness, r.dnsSuffix, []pulumi.Resource{fipAssoc}) if err != nil { return err } @@ -518,6 +527,7 @@ func (r *sncRequest) userData( PullSecretB64: psB64, KubeAdminPassword: args[2].(string), DeveloperPassword: args[3].(string), + DNSSuffix: r.dnsSuffix, } rawCC, err := file.Template(data, string(cloudConfigTemplate)) if err != nil { @@ -548,7 +558,7 @@ func mimeWrapCloudConfig(rawCC string) string { func kubeconfig(ctx *pulumi.Context, prefix *string, ip pulumi.StringOutput, mk *tls.PrivateKey, ocpVersion string, disableClusterReadiness bool, - dependencies []pulumi.Resource, + dnsSuffix string, dependencies []pulumi.Resource, ) (pulumi.StringOutput, error) { sshReadyCmd, err := remote.NewCommand(ctx, resourcesUtil.GetResourceName(*prefix, ibmCloudSNCID, "ssh-ready"), @@ -634,7 +644,7 @@ func kubeconfig(ctx *pulumi.Context, prefix *string, ip pulumi.StringOutput, func(args []interface{}) string { return kubeconfigURLPattern.ReplaceAllString( args[0].(string), - fmt.Sprintf("https://api.%s.nip.io:6443", args[1].(string))) + apiSNC.APIServerURL(args[1].(string), dnsSuffix)) }).(pulumi.StringOutput) return kc, nil } diff --git a/pkg/provider/ibmcloud/action/snc/snc_test.go b/pkg/provider/ibmcloud/action/snc/snc_test.go index 76f4b8add..96278dbf5 100644 --- a/pkg/provider/ibmcloud/action/snc/snc_test.go +++ b/pkg/provider/ibmcloud/action/snc/snc_test.go @@ -44,3 +44,48 @@ func TestCloudConfigQuotesPasswordValues(t *testing.T) { t.Errorf("developer password was not preserved: %q", contents["/opt/crc/pass_developer"]) } } + +func TestCloudConfigDNSSuffix(t *testing.T) { + base := dataValues{ + Username: "core", + PubKey: "ssh-rsa AAAATEST", + PublicIP: "192.0.2.1", + PullSecretB64: "cHJ1bGxlcnNlY3JldA==", + KubeAdminPassword: "!admin-password", + DeveloperPassword: "!developer-password", + } + + render := func(t *testing.T, data dataValues) map[string]string { + t.Helper() + rendered, err := file.Template(data, string(cloudConfigTemplate)) + if err != nil { + t.Fatalf("render cloud config: %v", err) + } + var config struct { + WriteFiles []struct { + Path string `yaml:"path"` + Content string `yaml:"content"` + } `yaml:"write_files"` + } + if err := yaml.Unmarshal([]byte(rendered), &config); err != nil { + t.Fatalf("parse rendered cloud config: %v", err) + } + contents := make(map[string]string) + for _, writeFile := range config.WriteFiles { + contents[writeFile.Path] = writeFile.Content + } + return contents + } + + withoutSuffix := render(t, base) + if _, ok := withoutSuffix["/opt/crc/dns-suffix"]; ok { + t.Error("dns-suffix file should not be written when no suffix is set") + } + + withSuffix := base + withSuffix.DNSSuffix = "sslip.io" + contents := render(t, withSuffix) + if got := contents["/opt/crc/dns-suffix"]; got != "sslip.io" { + t.Errorf("dns-suffix file content = %q, want %q", got, "sslip.io") + } +} diff --git a/pkg/target/service/snc/api.go b/pkg/target/service/snc/api.go index d104c8ede..a904eae43 100644 --- a/pkg/target/service/snc/api.go +++ b/pkg/target/service/snc/api.go @@ -2,6 +2,7 @@ package snc import ( "fmt" + "strings" cr "github.com/redhat-developer/mapt/pkg/provider/api/compute-request" spotTypes "github.com/redhat-developer/mapt/pkg/provider/api/spot" @@ -13,7 +14,13 @@ var ( StackName = "stackOpenshiftSNC" OCPSNCID = "snc" - consoleURLRegex = "https://console-openshift-console.apps.%s.nip.io" + // DefaultDNSSuffix is used when no custom suffix is set on SNCArgs. + DefaultDNSSuffix = "nip.io" + + // minDNSSuffixVersion is the first OpenShift version whose SNC bundle + // reads /opt/crc/dns-suffix (crc-org/snc#1266, merged on master and + // backported to the release-4.22 and release-5.0 bundle branches). + minDNSSuffixVersion = "v4.22" OutputHost = "aosHost" OutputUsername = "aosUsername" @@ -40,6 +47,49 @@ func CommandCaServiceRan(version string) string { return fmt.Sprintf(commandCaServiceRan, util.If(semver.Compare(version, ContextAdminStarterVersion) < 0, contextSystemAdmin, contextAdmin)) } +// DNSSuffixOrDefault returns dnsSuffix when set, DefaultDNSSuffix otherwise. +func DNSSuffixOrDefault(dnsSuffix string) string { + return util.If(dnsSuffix != "", dnsSuffix, DefaultDNSSuffix) +} + +// ValidateDNSSuffix checks that dnsSuffix, when set, is a bare DNS suffix +// and that the requested OpenShift version runs a bundle which reads +// /opt/crc/dns-suffix (crc-org/snc#1266). An empty version means the latest +// available bundle, which always includes the change. +func ValidateDNSSuffix(version, dnsSuffix string) error { + if dnsSuffix == "" { + return nil + } + if strings.ContainsAny(dnsSuffix, " \t\n/") || strings.HasPrefix(dnsSuffix, ".") { + return fmt.Errorf("invalid dns suffix %q: expected a bare suffix like sslip.io", dnsSuffix) + } + if version == "" { + return nil + } + v := "v" + strings.TrimPrefix(version, "v") + if !semver.IsValid(v) { + return fmt.Errorf("cannot check the dns suffix support against version %q: not a semantic version", version) + } + if semver.Compare(v, minDNSSuffixVersion) < 0 { + return fmt.Errorf("the dns suffix requires OpenShift >= 4.22 or 5.x: the bundle for %s does not read /opt/crc/dns-suffix (crc-org/snc#1266) and the cluster endpoints would stay on %s", version, DefaultDNSSuffix) + } + return nil +} + +// ConsoleURL returns the URL of the OpenShift console for the cluster +// reachable at ip, using dnsSuffix (or the default one when empty) as the +// DNS suffix. +func ConsoleURL(ip, dnsSuffix string) string { + return fmt.Sprintf("https://console-openshift-console.apps.%s.%s", ip, DNSSuffixOrDefault(dnsSuffix)) +} + +// APIServerURL returns the URL of the OpenShift API server for the cluster +// reachable at ip, using dnsSuffix (or the default one when empty) as the +// DNS suffix. +func APIServerURL(ip, dnsSuffix string) string { + return fmt.Sprintf("https://api.%s.%s:6443", ip, DNSSuffixOrDefault(dnsSuffix)) +} + type SNCArgs struct { Prefix string ComputeRequest *cr.ComputeRequestArgs @@ -53,6 +103,10 @@ type SNCArgs struct { Profiles []string OperatorChannels map[string]string CatalogSources map[string]string + // DNSSuffix overrides the nip.io default used for the cluster endpoints. + // When empty the SNC bundle falls back to its own default (nip.io). It + // requires a bundle including https://github.com/crc-org/snc/pull/1266. + DNSuffix string // VpcID, when non-empty, reuses an existing IBM Cloud VPC instead of // creating a new one. A new subnet is still provisioned inside it. VpcID string diff --git a/pkg/target/service/snc/api_test.go b/pkg/target/service/snc/api_test.go new file mode 100644 index 000000000..f0f201132 --- /dev/null +++ b/pkg/target/service/snc/api_test.go @@ -0,0 +1,31 @@ +package snc + +import "testing" + +func TestValidateDNSSuffix(t *testing.T) { + tests := []struct { + name string + version string + suffix string + wantErr bool + }{ + {name: "no suffix is always valid", version: "4.21.0", suffix: ""}, + {name: "supported version", version: "4.22.14", suffix: "sslip.io"}, + {name: "major version", version: "5.0.0", suffix: "sslip.io"}, + {name: "autodetected version", version: "", suffix: "sslip.io"}, + {name: "default aws version is too old", version: "4.21.0", suffix: "sslip.io", wantErr: true}, + {name: "short version below minimum", version: "4.21", suffix: "sslip.io", wantErr: true}, + {name: "suffix with space", version: "4.22.0", suffix: "ssl ip.io", wantErr: true}, + {name: "suffix with leading dot", version: "4.22.0", suffix: ".example.com", wantErr: true}, + {name: "suffix with path separator", version: "4.22.0", suffix: "example.com/x", wantErr: true}, + {name: "not a semantic version", version: "latest", suffix: "sslip.io", wantErr: true}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := ValidateDNSSuffix(tt.version, tt.suffix) + if (err != nil) != tt.wantErr { + t.Errorf("ValidateDNSSuffix(%q, %q) error = %v, wantErr %v", tt.version, tt.suffix, err, tt.wantErr) + } + }) + } +} diff --git a/pkg/target/service/snc/cloud-config b/pkg/target/service/snc/cloud-config index 77f28fccc..870b3fef4 100644 --- a/pkg/target/service/snc/cloud-config +++ b/pkg/target/service/snc/cloud-config @@ -30,3 +30,8 @@ write_files: owner: root:root path: /etc/sysconfig/crc-env permissions: '0644' +{{ if .DNSSuffix }}- path: /opt/crc/dns-suffix + content: {{ .DNSSuffix }} + owner: root:root + permissions: '0644' +{{ end }} diff --git a/pkg/target/service/snc/cloudconfig.go b/pkg/target/service/snc/cloudconfig.go index e7438b4bf..7917992b7 100644 --- a/pkg/target/service/snc/cloudconfig.go +++ b/pkg/target/service/snc/cloudconfig.go @@ -17,6 +17,9 @@ type DataValues struct { SSMPullSecretName string SSMKubeAdminPasswordName string SSMDeveloperPasswordName string + // DNS suffix for the cluster endpoints. When empty the SNC bundle keeps + // its own default (nip.io). + DNSSuffix string } //go:embed cloud-config diff --git a/pkg/target/service/snc/cloudconfig_test.go b/pkg/target/service/snc/cloudconfig_test.go new file mode 100644 index 000000000..e6ddf6c2a --- /dev/null +++ b/pkg/target/service/snc/cloudconfig_test.go @@ -0,0 +1,54 @@ +package snc + +import ( + "testing" + + "gopkg.in/yaml.v3" + + "github.com/redhat-developer/mapt/pkg/util/file" +) + +func renderCloudConfig(t *testing.T, data DataValues) map[string]string { + t.Helper() + rendered, err := file.Template(data, string(CloudConfigFile)) + if err != nil { + t.Fatalf("render cloud config: %v", err) + } + var config struct { + WriteFiles []struct { + Path string `yaml:"path"` + Content string `yaml:"content"` + } `yaml:"write_files"` + } + if err := yaml.Unmarshal([]byte(rendered), &config); err != nil { + t.Fatalf("parse rendered cloud config: %v", err) + } + contents := make(map[string]string) + for _, writeFile := range config.WriteFiles { + contents[writeFile.Path] = writeFile.Content + } + return contents +} + +func TestCloudConfigWithoutDNSSuffix(t *testing.T) { + contents := renderCloudConfig(t, DataValues{ + Username: "core", + PubKey: "ssh-rsa AAAATEST", + PublicIP: "192.0.2.1", + }) + if _, ok := contents["/opt/crc/dns-suffix"]; ok { + t.Error("dns-suffix file should not be written when no suffix is set") + } +} + +func TestCloudConfigWithDNSSuffix(t *testing.T) { + contents := renderCloudConfig(t, DataValues{ + Username: "core", + PubKey: "ssh-rsa AAAATEST", + PublicIP: "192.0.2.1", + DNSSuffix: "sslip.io", + }) + if got := contents["/opt/crc/dns-suffix"]; got != "sslip.io" { + t.Errorf("dns-suffix file content = %q, want %q", got, "sslip.io") + } +} diff --git a/pkg/target/service/snc/snc.go b/pkg/target/service/snc/snc.go index c9bab681c..78916e4e8 100644 --- a/pkg/target/service/snc/snc.go +++ b/pkg/target/service/snc/snc.go @@ -10,7 +10,7 @@ import ( func Results(stackResult auto.UpResult, prefix *string, resultOutputPath string, spotPrice *float64, - disableClusterReadiness bool) (*SNCResults, error) { + disableClusterReadiness bool, dnsSuffix string) (*SNCResults, error) { username, err := getResultOutput(OutputUsername, stackResult, prefix) if err != nil { return nil, err @@ -53,9 +53,9 @@ func Results(stackResult auto.UpResult, prefix *string, } } - consoleURL := fmt.Sprintf(consoleURLRegex, host) + consoleURL := ConsoleURL(host, dnsSuffix) if eip, ok := stackResult.Outputs[hostIPKey].Value.(string); ok { - fmt.Printf("Cluster has been started you can access console at: %s.\n", fmt.Sprintf(consoleURLRegex, eip)) + fmt.Printf("Cluster has been started you can access console at: %s.\n", ConsoleURL(eip, dnsSuffix)) } return &SNCResults{