Skip to content

Commit

Permalink
Revert "Remove special hostname behavior for aws cloud-provider"
Browse files Browse the repository at this point in the history
This reverts commit 89a8d81.

Signed-off-by: Brad Davidson <brad.davidson@rancher.com>
(cherry picked from commit 6e701fc)
Signed-off-by: Brad Davidson <brad.davidson@rancher.com>
  • Loading branch information
brandond committed Nov 27, 2024
1 parent 56cfa3f commit fd93d9d
Showing 1 changed file with 64 additions and 0 deletions.
64 changes: 64 additions & 0 deletions pkg/rke2/rke2_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,16 @@
package rke2

import (
"bytes"
"context"
"fmt"
"io/ioutil"
"net/http"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"

"github.com/k3s-io/k3s/pkg/agent/config"
"github.com/k3s-io/k3s/pkg/cli/cmds"
Expand All @@ -18,6 +24,7 @@ import (
"github.com/rancher/rke2/pkg/cli/defaults"
"github.com/rancher/rke2/pkg/images"
"github.com/rancher/rke2/pkg/podexecutor"
"github.com/sirupsen/logrus"
"github.com/urfave/cli"
)

Expand Down Expand Up @@ -89,6 +96,19 @@ func initExecutor(clx *cli.Context, cfg Config, isServer bool) (*podexecutor.Sta
Name: cfg.CloudProviderName,
Path: cfg.CloudProviderConfig,
}
if clx.String("node-name") == "" && cfg.CloudProviderName == "aws" {
fqdn := hostnameFromMetadataEndpoint(context.Background())
if fqdn == "" {
hostFQDN, err := hostnameFQDN()
if err != nil {
return nil, err
}
fqdn = hostFQDN
}
if err := clx.Set("node-name", fqdn); err != nil {
return nil, err
}
}
}

if cfg.KubeletPath == "" {
Expand Down Expand Up @@ -469,3 +489,47 @@ func parseControlPlaneMounts(cfg Config) (*podexecutor.ControlPlaneMounts, error
CloudControllerManager: cfg.ExtraMounts.CloudControllerManager.Value(),
}, nil
}

func hostnameFQDN() (string, error) {
cmd := exec.Command("hostname", "-f")

var b bytes.Buffer
cmd.Stdout = &b

if err := cmd.Run(); err != nil {
return "", err
}

return strings.TrimSpace(b.String()), nil
}

func hostnameFromMetadataEndpoint(ctx context.Context) string {
ctx, cancel := context.WithTimeout(ctx, time.Second)
defer cancel()

req, err := http.NewRequestWithContext(ctx, http.MethodGet, "http://169.254.169.254/latest/meta-data/local-hostname", nil)
if err != nil {
logrus.Debugf("Failed to create request for metadata endpoint: %v", err)
return ""
}

resp, err := http.DefaultClient.Do(req)
if err != nil {
logrus.Debugf("Failed to get local-hostname from metadata endpoint: %v", err)
return ""
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
logrus.Debugf("Metadata endpoint returned unacceptable status code %d", resp.StatusCode)
return ""
}

b, err := ioutil.ReadAll(resp.Body)
if err != nil {
logrus.Debugf("Failed to read response body from metadata endpoint: %v", err)
return ""
}

return strings.TrimSpace(string(b))
}

0 comments on commit fd93d9d

Please sign in to comment.