Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Release-1.21] Get node name from metadata if AWS cloud provider is enabled #2166

Merged
Merged
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
46 changes: 43 additions & 3 deletions pkg/rke2/rke2_linux.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
//go:build linux
// +build linux

package rke2

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

"github.com/pkg/errors"
"github.com/rancher/k3s/pkg/agent/config"
Expand Down Expand Up @@ -67,9 +72,13 @@ func initExecutor(clx *cli.Context, cfg Config, dataDir string, disableETCD bool
Path: cfg.CloudProviderConfig,
}
if clx.String("node-name") == "" && cfg.CloudProviderName == "aws" {
fqdn, err := hostnameFQDN()
if err != nil {
return nil, err
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
Expand Down Expand Up @@ -204,3 +213,34 @@ func hostnameFQDN() (string, error) {

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/metadata/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))
}