Skip to content

Commit ea2869e

Browse files
committed
applied a small number of refactorings as I read through the code
1 parent 29896f2 commit ea2869e

File tree

10 files changed

+73
-50
lines changed

10 files changed

+73
-50
lines changed

api/v1beta1/zz_generated.conversion.go

Lines changed: 0 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

api/v1beta2/conditions_consts.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,3 +173,11 @@ const (
173173
// S3BucketFailedReason is used when any errors occur during reconciliation of an S3 bucket.
174174
S3BucketFailedReason = "S3BucketCreationFailed"
175175
)
176+
177+
const (
178+
// OIDCProviderReadyCondition indicates that the OIDC provider has been created successfully.
179+
OIDCProviderReadyCondition = "OIDCProviderCreated"
180+
181+
// OIDCProviderReconciliationFailedReason is used if we can't reconcile the OIDC provider.
182+
OIDCProviderReconciliationFailedReason = "OIDCProviderReconciliationFailed"
183+
)

controllers/awscluster_controller.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -337,6 +337,7 @@ func (r *AWSClusterReconciler) reconcileNormal(ctx context.Context, clusterScope
337337
}
338338

339339
if err := iamService.ReconcileOIDCProvider(ctx); err != nil {
340+
conditions.MarkFalse(awsCluster, infrav1.OIDCProviderReadyCondition, infrav1.OIDCProviderReconciliationFailedReason, clusterv1.ConditionSeverityError, err.Error())
340341
clusterScope.Error(err, "failed to reconcile OIDC provider")
341342
return reconcile.Result{RequeueAfter: 15 * time.Second}, nil
342343
}

controllers/awsmachine_controller.go

Lines changed: 24 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -309,7 +309,7 @@ func (r *AWSMachineReconciler) reconcileDelete(machineScope *scope.MachineScope,
309309
}
310310

311311
instance, err := r.findInstance(machineScope, ec2Service)
312-
if err != nil && err != ec2.ErrInstanceNotFoundByID {
312+
if err != nil && !errors.Is(err, ec2.ErrInstanceNotFoundByID) {
313313
machineScope.Error(err, "query to find instance failed")
314314
return ctrl.Result{}, err
315315
}
@@ -651,8 +651,7 @@ func (r *AWSMachineReconciler) reconcileOperationalState(ctx context.Context, ec
651651
}
652652

653653
// check if the remote kubeconfig works and annotate the cluster
654-
_, ok := machineScope.InfraCluster.InfraCluster().GetAnnotations()[scope.KubeconfigReadyAnnotation]
655-
if !ok && machineScope.IsControlPlane() {
654+
if _, ok := machineScope.InfraCluster.InfraCluster().GetAnnotations()[scope.KubeconfigReadyAnnotation]; !ok && machineScope.IsControlPlane() {
656655
// if a control plane node is operational check for a kubeconfig and a working control plane node
657656
// and set the annotation so any reconciliation which requires workload api access can complete
658657
remoteClient, err := machineScope.InfraCluster.RemoteClient()
@@ -669,23 +668,29 @@ func (r *AWSMachineReconciler) reconcileOperationalState(ctx context.Context, ec
669668
for i := range nodes.Items {
670669
if util.IsNodeReady(&nodes.Items[i]) {
671670
oneReady = true // if one control plane is ready return true
671+
break
672672
}
673673
}
674674

675-
if oneReady {
676-
awsCluster := &infrav1.AWSCluster{}
677-
key := types.NamespacedName{Namespace: machineScope.InfraCluster.Namespace(), Name: machineScope.InfraCluster.Name()}
678-
if err := r.Client.Get(ctx, key, awsCluster); err != nil {
679-
return err
680-
}
681-
anno := awsCluster.GetAnnotations()
682-
anno[scope.KubeconfigReadyAnnotation] = "true"
683-
awsCluster.SetAnnotations(anno)
684-
if err := r.Client.Update(ctx, awsCluster); err != nil {
685-
return err
686-
}
687-
} else {
675+
if !oneReady {
688676
r.Log.Info("waiting for a control plane node to be ready before annotating the cluster, do you need to deploy a CNI?")
677+
678+
return nil
679+
}
680+
681+
awsCluster := &infrav1.AWSCluster{}
682+
key := types.NamespacedName{
683+
Namespace: machineScope.InfraCluster.Namespace(),
684+
Name: machineScope.InfraCluster.Name(),
685+
}
686+
if err := r.Client.Get(ctx, key, awsCluster); err != nil {
687+
return fmt.Errorf("failed to get aws cluster: %w", err)
688+
}
689+
690+
awsCluster.Annotations[scope.KubeconfigReadyAnnotation] = "true"
691+
692+
if err := r.Client.Update(ctx, awsCluster); err != nil {
693+
return fmt.Errorf("failed to update aws cluster with new annotation: %w", err)
689694
}
690695
}
691696

@@ -1206,19 +1211,19 @@ func (r *AWSMachineReconciler) ensureStorageTags(ec2svc services.EC2Interface, i
12061211
if err != nil {
12071212
r.Log.Error(err, "Failed to fetch the changed volume tags in EC2 instance")
12081213
}
1209-
prevAnnotations[volumeID] = newAnnotation
1214+
annotations[volumeID] = newAnnotation
12101215
} else {
12111216
newAnnotation, err := r.ensureVolumeTags(ec2svc, aws.String(volumeID), make(map[string]interface{}), additionalTags)
12121217
if err != nil {
12131218
r.Log.Error(err, "Failed to fetch the changed volume tags in EC2 instance")
12141219
}
1215-
prevAnnotations[volumeID] = newAnnotation
1220+
annotations[volumeID] = newAnnotation
12161221
}
12171222
}
12181223

12191224
if !cmp.Equal(prevAnnotations, annotations, cmpopts.EquateEmpty()) {
12201225
// We also need to update the annotation if anything changed.
1221-
err = r.updateMachineAnnotationJSON(machine, VolumeTagsLastAppliedAnnotation, prevAnnotations)
1226+
err = r.updateMachineAnnotationJSON(machine, VolumeTagsLastAppliedAnnotation, annotations)
12221227
if err != nil {
12231228
r.Log.Error(err, "Failed to fetch the changed volume tags in EC2 instance")
12241229
}

pkg/cloud/services/iam/iam.go

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,16 @@ package iam
33
import (
44
"context"
55
"errors"
6+
"fmt"
67
"regexp"
78

89
"github.com/aws/aws-sdk-go/service/iam/iamiface"
910
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
1011

12+
infrav1 "sigs.k8s.io/cluster-api-provider-aws/v2/api/v1beta2"
1113
"sigs.k8s.io/cluster-api-provider-aws/v2/pkg/cloud/scope"
1214
"sigs.k8s.io/cluster-api-provider-aws/v2/pkg/cloud/services/s3"
15+
"sigs.k8s.io/cluster-api/util/conditions"
1316
)
1417

1518
type Service struct {
@@ -57,11 +60,11 @@ var (
5760
// ReconcileOIDCProvider replicates functionality already built into managed clusters by auto-deploying the
5861
// modifying kube-apiserver args, deploying the pod identity webhook and setting/configuring an oidc provider
5962
// for more details see: https://github.com/aws/amazon-eks-pod-identity-webhook/blob/master/SELF_HOSTED_SETUP.md
60-
// 1. create a self signed issuer for the mutating webhook
63+
// 1. create a self-signed issuer for the mutating webhook
6164
// 2. add create a json patch for kube-apiserver and use capi config to add to the kubeadm.yml
6265
// 3. create an oidc provider in aws which points to the s3 bucket
63-
// 4. pause until kubeconfig and cluster acccess is ready
64-
// 5. move openid config and jwks to the s3 bucket
66+
// 4. pause until kubeconfig and cluster access is ready
67+
// 5. move openid config and JWKs to the s3 bucket
6568
// 6. add the pod identity webhook to the workload cluster
6669
// 7. add the configmap to the workload cluster.
6770
func (s *Service) ReconcileOIDCProvider(ctx context.Context) error {
@@ -104,7 +107,13 @@ func (s *Service) ReconcileOIDCProvider(ctx context.Context) error {
104107
return err
105108
}
106109

107-
return s.reconcileTrustPolicyConfigMap(ctx)
110+
if err := s.reconcileTrustPolicyConfigMap(ctx); err != nil {
111+
return fmt.Errorf("failed to reconcile trust policy config map: %w", err)
112+
}
113+
114+
conditions.MarkTrue(s.scope.InfraCluster(), infrav1.OIDCProviderReadyCondition)
115+
116+
return nil
108117
}
109118

110119
// DeleteOIDCProvider will delete the iam resources note that the bucket is cleaned up in the s3 service

pkg/cloud/services/iam/oidc.go

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"context"
66
"crypto/sha1"
77
"crypto/tls"
8+
stderr "errors"
89
"fmt"
910
"path"
1011
"strings"
@@ -247,29 +248,31 @@ func findAndVerifyOIDCProvider(issuerURL, thumbprint string, iamClient iamiface.
247248
return "", nil
248249
}
249250

250-
func fetchRootCAThumbprint(url string, port int) (ret string, err error) {
251+
func fetchRootCAThumbprint(url string, port int) (_ string, err error) {
251252
// Parse cmdline arguments using flag package
252253
conn, err := tls.Dial("tcp", fmt.Sprintf("%s:%d", url, port), &tls.Config{
253254
MinVersion: tls.VersionTLS12,
254255
})
255256
if err != nil {
256-
return
257+
return "", err
257258
}
259+
258260
defer func() {
259-
err = conn.Close()
261+
if cerr := conn.Close(); cerr != nil {
262+
err = stderr.Join(err, cerr)
263+
}
260264
}()
261-
262265
// Get the ConnectionState struct as that's the one which gives us x509.Certificate struct
263266
cert := conn.ConnectionState().PeerCertificates[0]
264267
fingerprint := sha1.Sum(cert.Raw) //nolint:gosec // this is not used for real security
265268
var buf bytes.Buffer
266269
for _, f := range fingerprint {
267-
if _, err = fmt.Fprintf(&buf, "%02X", f); err != nil {
268-
return
270+
if _, err := fmt.Fprintf(&buf, "%02X", f); err != nil {
271+
return "", err
269272
}
270273
}
271-
ret = strings.ToLower(buf.String())
272-
return
274+
275+
return strings.ToLower(buf.String()), nil
273276
}
274277

275278
// DeleteOIDCProvider will delete an OIDC provider.

pkg/cloud/services/iam/podidentitywebhook.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -319,8 +319,8 @@ func objectMeta(name, namespace string) metav1.ObjectMeta {
319319
return meta
320320
}
321321

322-
// reconcileCertifcateSecret takes a secret and moves it to the workload cluster.
323-
func reconcileCertifcateSecret(ctx context.Context, cert *corev1.Secret, remoteClient client.Client) error {
322+
// reconcileCertificateSecret takes a secret and moves it to the workload cluster.
323+
func reconcileCertificateSecret(ctx context.Context, cert *corev1.Secret, remoteClient client.Client) error {
324324
// check if the secret was created by cert-manager
325325
certCheck := &corev1.Secret{}
326326
if err := remoteClient.Get(ctx, types.NamespacedName{

pkg/cloud/services/iam/reconcilers.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ func (s *Service) reconcilePodIdentityWebhook(ctx context.Context) error {
4343
}
4444

4545
// switch it to kube-system and move it to the remote cluster
46-
if err := reconcileCertifcateSecret(ctx, certSecret, remoteClient); err != nil {
46+
if err := reconcileCertificateSecret(ctx, certSecret, remoteClient); err != nil {
4747
return err
4848
}
4949

pkg/cloud/services/s3/s3.go

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -49,19 +49,19 @@ type Service struct {
4949
var DisabledError = errors.New("s3 management disabled")
5050

5151
func IsDisabledError(err error) bool {
52-
return err == DisabledError
52+
return errors.Is(err, DisabledError)
5353
}
5454

5555
var EmptyBucketError = errors.New("empty bucket name")
5656

5757
func IsEmptyBucketError(err error) bool {
58-
return err == EmptyBucketError
58+
return errors.Is(err, EmptyBucketError)
5959
}
6060

6161
var EmptyKeyError = errors.New("empty key")
6262

6363
func IsEmptyKeyError(err error) bool {
64-
return err == EmptyKeyError
64+
return errors.Is(err, EmptyKeyError)
6565
}
6666

6767
// NewService returns a new service given the api clients.
@@ -123,7 +123,8 @@ func (s *Service) DeleteBucket() error {
123123
return nil
124124
}
125125

126-
aerr, ok := err.(awserr.Error)
126+
var aerr awserr.Error
127+
ok := errors.As(err, &aerr)
127128
if !ok {
128129
return errors.Wrap(err, "deleting S3 bucket")
129130
}
@@ -186,10 +187,10 @@ func (s *Service) create(putInput *s3.PutObjectInput) (string, error) {
186187
}
187188

188189
if exp := s.scope.Bucket().PresignedURLDuration; exp != nil {
189-
s.scope.Info("Generating presigned URL", "bucket_name", bucket, "key", key)
190+
s.scope.Info("Generating presigned URL", "bucket_name", aws.StringValue(putInput.Bucket), "key", aws.StringValue(putInput.Key))
190191
req, _ := s.S3Client.GetObjectRequest(&s3.GetObjectInput{
191-
Bucket: aws.String(bucket),
192-
Key: aws.String(key),
192+
Bucket: putInput.Bucket,
193+
Key: putInput.Key,
193194
})
194195
return req.Presign(exp.Duration)
195196
}
@@ -228,7 +229,8 @@ func (s *Service) Delete(key string) error {
228229
return nil
229230
}
230231

231-
aerr, ok := err.(awserr.Error)
232+
var aerr awserr.Error
233+
ok := errors.As(err, &aerr)
232234
if !ok {
233235
return errors.Wrap(err, "deleting S3 object")
234236
}
@@ -255,7 +257,8 @@ func (s *Service) createBucketIfNotExist(bucketName string) error {
255257
return nil
256258
}
257259

258-
aerr, ok := err.(awserr.Error)
260+
var aerr awserr.Error
261+
ok := errors.As(err, &aerr)
259262
if !ok {
260263
return errors.Wrap(err, "creating S3 bucket")
261264
}
@@ -272,11 +275,10 @@ func (s *Service) createBucketIfNotExist(bucketName string) error {
272275
}
273276

274277
func (s *Service) ensureBucketAccess(bucketName string) error {
275-
f := false
276278
input := &s3.PutPublicAccessBlockInput{
277279
Bucket: aws.String(bucketName),
278280
PublicAccessBlockConfiguration: &s3.PublicAccessBlockConfiguration{
279-
BlockPublicAcls: aws.Bool(f),
281+
BlockPublicAcls: aws.Bool(false),
280282
},
281283
}
282284

pkg/cloud/services/s3/s3_test.go

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -299,7 +299,6 @@ func TestReconcileBucket(t *testing.T) {
299299

300300
s3Mock.EXPECT().CreateBucket(gomock.Any()).Return(nil, nil).Times(1)
301301
s3Mock.EXPECT().PutBucketTagging(gomock.Any()).Return(nil, nil).Times(1)
302-
s3Mock.EXPECT().PutBucketPolicy(gomock.Any()).Return(nil, errors.New("error")).Times(1)
303302
s3Mock.EXPECT().PutPublicAccessBlock(gomock.Any()).Return(nil, errors.New("error")).Times(1)
304303

305304
if err := svc.ReconcileBucket(); err == nil {

0 commit comments

Comments
 (0)