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

AMIFamily Defaulting and Validation #1296

Merged
merged 5 commits into from
Feb 9, 2022
Merged
Show file tree
Hide file tree
Changes from 4 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
25 changes: 8 additions & 17 deletions pkg/cloudprovider/aws/ami.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func (p *AMIProvider) Get(ctx context.Context, constraints *v1alpha1.Constraints
// Separate instance types by unique queries
amiQueries := map[string][]cloudprovider.InstanceType{}
for _, instanceType := range instanceTypes {
query := p.getSSMQuery(ctx, constraints, instanceType, version)
query := p.getSSMQuery(constraints, instanceType, version)
amiQueries[query] = append(amiQueries[query], instanceType)
}
// Separate instance types by unique AMIIDs
Expand Down Expand Up @@ -84,6 +84,13 @@ func (p *AMIProvider) getAMIID(ctx context.Context, query string) (string, error
return ami, nil
}

func (p *AMIProvider) getSSMQuery(constraints *v1alpha1.Constraints, instanceType cloudprovider.InstanceType, version string) string {
if aws.StringValue(constraints.AMIFamily) == v1alpha1.AMIFamilyBottlerocket {
return p.getBottlerocketAlias(version, instanceType)
}
return p.getAL2Alias(version, instanceType)
}

// getAL2Alias returns a properly-formatted alias for an Amazon Linux AMI from SSM
func (p *AMIProvider) getAL2Alias(version string, instanceType cloudprovider.InstanceType) string {
amiSuffix := ""
Expand All @@ -104,22 +111,6 @@ func (p *AMIProvider) getBottlerocketAlias(version string, instanceType cloudpro
return fmt.Sprintf("/aws/service/bottlerocket/aws-k8s-%s/%s/latest/image_id", version, arch)
}

func (p *AMIProvider) getSSMQuery(ctx context.Context, constraints *v1alpha1.Constraints, instanceType cloudprovider.InstanceType, version string) string {
ssmQuery := p.getAL2Alias(version, instanceType)
if constraints.AMIFamily != nil {
if *constraints.AMIFamily == v1alpha1.OperatingSystemBottleRocket {
ssmQuery = p.getBottlerocketAlias(version, instanceType)
} else if *constraints.AMIFamily == v1alpha1.OperatingSystemEKSOptimized {
ssmQuery = p.getAL2Alias(version, instanceType)
} else {
logging.FromContext(ctx).Warnf("AMIFamily was set, but was not one of %s or %s. Setting to %s as the default.", v1alpha1.OperatingSystemEKSOptimized, v1alpha1.OperatingSystemBottleRocket, v1alpha1.OperatingSystemEKSOptimized)
ssmQuery = p.getAL2Alias(version, instanceType)
}
}

return ssmQuery
}

func (p *AMIProvider) kubeServerVersion(ctx context.Context) (string, error) {
if version, ok := p.cache.Get(kubernetesVersionCacheKey); ok {
return version.(string), nil
Expand Down
8 changes: 8 additions & 0 deletions pkg/cloudprovider/aws/apis/v1alpha1/provider_defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
func (c *Constraints) Default(ctx context.Context) {
c.defaultArchitecture()
c.defaultCapacityTypes()
c.defaultAMIFamily()
}

func (c *Constraints) defaultCapacityTypes() {
Expand Down Expand Up @@ -54,3 +55,10 @@ func (c *Constraints) defaultArchitecture() {
Values: []string{v1alpha5.ArchitectureAmd64},
})
}

func (c *Constraints) defaultAMIFamily() {
if c.AMIFamily != nil {
return
}
c.AMIFamily = &AMIFamilyEKSOptimized
}
10 changes: 9 additions & 1 deletion pkg/cloudprovider/aws/apis/v1alpha1/provider_validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ func (a *AWS) validate() (errs *apis.FieldError) {
a.validateSecurityGroups(),
a.validateTags(),
a.validateMetadataOptions(),
a.validateAMIFamily(),
)
}

Expand Down Expand Up @@ -121,11 +122,18 @@ func (a *AWS) validateHTTPTokens() *apis.FieldError {
return a.validateStringEnum(*a.MetadataOptions.HTTPTokens, "httpTokens", ec2.LaunchTemplateHttpTokensState_Values())
}

func (a *AWS) validateAMIFamily() *apis.FieldError {
if a.AMIFamily == nil {
return nil
}
return a.validateStringEnum(*a.AMIFamily, "amiFamily", SupportedAMIFamilies)
}

func (a *AWS) validateStringEnum(value, field string, validValues []string) *apis.FieldError {
for _, validValue := range validValues {
if value == validValue {
return nil
}
}
return apis.ErrInvalidValue(fmt.Sprintf("valid values: %s", strings.Join(validValues, ", ")), field)
return apis.ErrInvalidValue(fmt.Sprintf("%s not in %v", value, strings.Join(validValues, ", ")), field)
}
8 changes: 6 additions & 2 deletions pkg/cloudprovider/aws/apis/v1alpha1/register.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,12 @@ var (
AWSRestrictedLabelDomains = []string{
"k8s.aws",
}
OperatingSystemBottleRocket = "Bottlerocket"
OperatingSystemEKSOptimized = "EKSOptimized"
AMIFamilyBottlerocket = "Bottlerocket"
AMIFamilyEKSOptimized = "EKSOptimized"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reminder to make this EKSOptimizedLinux

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can't we just support Operating system separately and keep AMIFamily the actual family? So if AMIFamily was EKSOptimized but the pod requested Windows, we'd just give them windows EKS Optimized?

Copy link
Contributor

@ellistarn ellistarn Feb 8, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This assumes a certain amount of parity between EKSOptimized. In general, I agree with you. IIRC, this was a request from @suket22.

SupportedAMIFamilies = []string{
AMIFamilyBottlerocket,
AMIFamilyEKSOptimized,
}
)

var (
Expand Down
61 changes: 17 additions & 44 deletions pkg/cloudprovider/aws/launchtemplate.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,20 +106,14 @@ func (p *LaunchTemplateProvider) Get(ctx context.Context, constraints *v1alpha1.
}
// Construct launch templates
launchTemplates := map[string][]cloudprovider.InstanceType{}
caBundle, err := p.GetCABundle(ctx)
if err != nil {
return nil, fmt.Errorf("getting ca bundle for user data, %w", err)
}
for amiID, instanceTypes := range amis {
// Get userData for Node
var userData string
if constraints.AMIFamily != nil {
if strings.EqualFold(*constraints.AMIFamily, v1alpha1.OperatingSystemBottleRocket) {
userData, err = p.getBottleRocketUserData(ctx, constraints, additionalLabels)
} else if strings.EqualFold(*constraints.AMIFamily, v1alpha1.OperatingSystemEKSOptimized) {
userData, err = p.getEKSOptimizedUserData(ctx, constraints, instanceTypes, additionalLabels)
} else {
logging.FromContext(ctx).Warnf("AMIFamily was set, but was not one of %s or %s. Setting to %s as the default.", v1alpha1.OperatingSystemEKSOptimized, v1alpha1.OperatingSystemBottleRocket, v1alpha1.OperatingSystemEKSOptimized)
userData, err = p.getEKSOptimizedUserData(ctx, constraints, instanceTypes, additionalLabels)
}
} else {
userData, err = p.getEKSOptimizedUserData(ctx, constraints, instanceTypes, additionalLabels)
userData := p.getEKSOptimizedUserData(ctx, constraints, instanceTypes, additionalLabels, caBundle)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

totally minor, but if you factored this out into a function, you could use the same return pattern used in the ami logic and keep this core Get() function as simple as possible.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How's this?

if aws.StringValue(constraints.AMIFamily) == v1alpha1.AMIFamilyBottlerocket {
userData = p.getBottlerocketUserData(ctx, constraints, additionalLabels, caBundle)
}
if err != nil {
bwagner5 marked this conversation as resolved.
Show resolved Hide resolved
return nil, err
Expand Down Expand Up @@ -252,52 +246,35 @@ func sortedKeys(m map[string]string) []string {
return keys
}

func (p *LaunchTemplateProvider) getBottleRocketUserData(ctx context.Context, constraints *v1alpha1.Constraints, additionalLabels map[string]string) (string, error) {
var userData string
userData += fmt.Sprintf(`[settings.kubernetes]
cluster-name = "%s"
api-server = "%s"
`,
injection.GetOptions(ctx).ClusterName,
injection.GetOptions(ctx).ClusterEndpoint)

func (p *LaunchTemplateProvider) getBottlerocketUserData(ctx context.Context, constraints *v1alpha1.Constraints, additionalLabels map[string]string, caBundle *string) string {
userData := fmt.Sprintf("[settings.kubernetes]\ncluster-name = \"%s\"\napi-server = \"%s\"\n", injection.GetOptions(ctx).ClusterName, injection.GetOptions(ctx).ClusterEndpoint)
if constraints.KubeletConfiguration.ClusterDNS != nil {
userData += fmt.Sprintf("cluster-dns-ip = \"%s\"", constraints.KubeletConfiguration.ClusterDNS)
}

caBundle, err := p.GetCABundle(ctx)
if err != nil {
return "", fmt.Errorf("getting ca bundle for user data, %w", err)
userData += fmt.Sprintf("cluster-dns-ip = \"%s\"\n", constraints.KubeletConfiguration.ClusterDNS)
}
if caBundle != nil {
userData += fmt.Sprintf("cluster-certificate = \"%s\"\n", *caBundle)
}

nodeLabelArgs := functional.UnionStringMaps(additionalLabels, constraints.Labels)
if len(nodeLabelArgs) > 0 {
userData += `[settings.kubernetes.node-labels]
`
userData += "[settings.kubernetes.node-labels]\n"
for key, val := range nodeLabelArgs {
userData += fmt.Sprintf("\"%s\" = \"%s\"", key, val)
userData += fmt.Sprintf("\"%s\" = \"%s\"\n", key, val)
}
}

if len(constraints.Taints) > 0 {
userData += `[settings.kubernetes.node-taints]
`
userData += "[settings.kubernetes.node-taints]\n"
sorted := sortedTaints(constraints.Taints)
for _, taint := range sorted {
userData += fmt.Sprintf("%s=%s:%s", taint.Key, taint.Value, taint.Effect)
userData += fmt.Sprintf("%s=%s:%s\n", taint.Key, taint.Value, taint.Effect)
}
}

return base64.StdEncoding.EncodeToString([]byte(userData)), nil
return base64.StdEncoding.EncodeToString([]byte(userData))
}

// getEKSOptimizedUserData returns the exact same string for equivalent input,
// even if elements of those inputs are in differing orders,
// guaranteeing it won't cause spurious hash differences.
func (p *LaunchTemplateProvider) getEKSOptimizedUserData(ctx context.Context, constraints *v1alpha1.Constraints, instanceTypes []cloudprovider.InstanceType, additionalLabels map[string]string) (string, error) {
func (p *LaunchTemplateProvider) getEKSOptimizedUserData(ctx context.Context, constraints *v1alpha1.Constraints, instanceTypes []cloudprovider.InstanceType, additionalLabels map[string]string, caBundle *string) string {
var containerRuntimeArg string
if !needsDocker(instanceTypes) {
containerRuntimeArg = "--container-runtime containerd"
Expand All @@ -311,10 +288,6 @@ exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1
injection.GetOptions(ctx).ClusterName,
containerRuntimeArg,
injection.GetOptions(ctx).ClusterEndpoint))
caBundle, err := p.GetCABundle(ctx)
if err != nil {
return "", fmt.Errorf("getting ca bundle for user data, %w", err)
}
if caBundle != nil {
userData.WriteString(fmt.Sprintf(` \
--b64-cluster-ca '%s'`,
Expand All @@ -339,7 +312,7 @@ exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1
userData.WriteString(fmt.Sprintf(` \
--dns-cluster-ip '%s'`, constraints.KubeletConfiguration.ClusterDNS[0]))
}
return base64.StdEncoding.EncodeToString(userData.Bytes()), nil
return base64.StdEncoding.EncodeToString(userData.Bytes())
}

func (p *LaunchTemplateProvider) getNodeLabelArgs(nodeLabels map[string]string) string {
Expand Down