diff --git a/apis/elbv2/v1beta1/targetgroupbinding_types.go b/apis/elbv2/v1beta1/targetgroupbinding_types.go
index 337e89202..7a273a1d4 100644
--- a/apis/elbv2/v1beta1/targetgroupbinding_types.go
+++ b/apis/elbv2/v1beta1/targetgroupbinding_types.go
@@ -157,6 +157,14 @@ type TargetGroupBindingSpec struct {
// VpcID is the VPC of the TargetGroup. If unspecified, it will be automatically inferred.
// +optional
VpcID string `json:"vpcID,omitempty"`
+
+ // IAM Role ARN to assume when calling AWS APIs. Useful if the target group is in a different AWS account
+ // +optional
+ IamRoleArnToAssume string `json:"-"` // `json:"iamRoleArnToAssume,omitempty"`
+
+ // IAM Role ARN to assume when calling AWS APIs. Needed to assume a role in another account and prevent the confused deputy problem. https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html
+ // +optional
+ AssumeRoleExternalId string `json:"-"` // `json:"assumeRoleExternalId,omitempty"`
}
// TargetGroupBindingStatus defines the observed state of TargetGroupBinding
diff --git a/controllers/ingress/group_controller.go b/controllers/ingress/group_controller.go
index 185faa124..6ae288905 100644
--- a/controllers/ingress/group_controller.go
+++ b/controllers/ingress/group_controller.go
@@ -15,7 +15,7 @@ import (
elbv2api "sigs.k8s.io/aws-load-balancer-controller/apis/elbv2/v1beta1"
"sigs.k8s.io/aws-load-balancer-controller/controllers/ingress/eventhandlers"
"sigs.k8s.io/aws-load-balancer-controller/pkg/annotations"
- "sigs.k8s.io/aws-load-balancer-controller/pkg/aws"
+ "sigs.k8s.io/aws-load-balancer-controller/pkg/aws/services"
"sigs.k8s.io/aws-load-balancer-controller/pkg/config"
"sigs.k8s.io/aws-load-balancer-controller/pkg/deploy"
elbv2deploy "sigs.k8s.io/aws-load-balancer-controller/pkg/deploy/elbv2"
@@ -43,7 +43,7 @@ const (
)
// NewGroupReconciler constructs new GroupReconciler
-func NewGroupReconciler(cloud aws.Cloud, k8sClient client.Client, eventRecorder record.EventRecorder,
+func NewGroupReconciler(cloud services.Cloud, k8sClient client.Client, eventRecorder record.EventRecorder,
finalizerManager k8s.FinalizerManager, networkingSGManager networkingpkg.SecurityGroupManager,
networkingSGReconciler networkingpkg.SecurityGroupReconciler, subnetsResolver networkingpkg.SubnetsResolver,
elbv2TaggingManager elbv2deploy.TaggingManager, controllerConfig config.ControllerConfig, backendSGProvider networkingpkg.BackendSGProvider,
diff --git a/controllers/service/service_controller.go b/controllers/service/service_controller.go
index 18dd36de3..9f304987c 100644
--- a/controllers/service/service_controller.go
+++ b/controllers/service/service_controller.go
@@ -11,7 +11,7 @@ import (
"k8s.io/client-go/tools/record"
"sigs.k8s.io/aws-load-balancer-controller/controllers/service/eventhandlers"
"sigs.k8s.io/aws-load-balancer-controller/pkg/annotations"
- "sigs.k8s.io/aws-load-balancer-controller/pkg/aws"
+ "sigs.k8s.io/aws-load-balancer-controller/pkg/aws/services"
"sigs.k8s.io/aws-load-balancer-controller/pkg/config"
"sigs.k8s.io/aws-load-balancer-controller/pkg/deploy"
elbv2deploy "sigs.k8s.io/aws-load-balancer-controller/pkg/deploy/elbv2"
@@ -34,7 +34,7 @@ const (
controllerName = "service"
)
-func NewServiceReconciler(cloud aws.Cloud, k8sClient client.Client, eventRecorder record.EventRecorder,
+func NewServiceReconciler(cloud services.Cloud, k8sClient client.Client, eventRecorder record.EventRecorder,
finalizerManager k8s.FinalizerManager, networkingSGManager networking.SecurityGroupManager,
networkingSGReconciler networking.SecurityGroupReconciler, subnetsResolver networking.SubnetsResolver,
vpcInfoProvider networking.VPCInfoProvider, elbv2TaggingManager elbv2deploy.TaggingManager, controllerConfig config.ControllerConfig,
diff --git a/docs/deploy/installation.md b/docs/deploy/installation.md
index 13ff8fdbd..c4fb97a33 100644
--- a/docs/deploy/installation.md
+++ b/docs/deploy/installation.md
@@ -7,10 +7,10 @@ The LBC is supported by AWS. Some clusters may be using the legacy "in-tree" fun
!!!question "Existing AWS ALB Ingress Controller users"
The AWS ALB Ingress controller must be uninstalled before installing the AWS Load Balancer Controller.
Please follow our [migration guide](upgrade/migrate_v1_v2.md) to do a migration.
-
+
!!!warning "When using AWS Load Balancer Controller v2.5+"
- The AWS LBC provides a mutating webhook for service resources to set the `spec.loadBalancerClass` field for service of type LoadBalancer on create.
- This makes the AWS LBC the **default controller for service** of type LoadBalancer. You can disable this feature and revert to set Cloud Controller Manager (in-tree controller) as the default by setting the helm chart value **enableServiceMutatorWebhook to false** with `--set enableServiceMutatorWebhook=false` .
+ The AWS LBC provides a mutating webhook for service resources to set the `spec.loadBalancerClass` field for service of type LoadBalancer on create.
+ This makes the AWS LBC the **default controller for service** of type LoadBalancer. You can disable this feature and revert to set Cloud Controller Manager (in-tree controller) as the default by setting the helm chart value **enableServiceMutatorWebhook to false** with `--set enableServiceMutatorWebhook=false` .
You will no longer be able to provision new Classic Load Balancer (CLB) from your kubernetes service unless you disable this feature. Existing CLB will continue to work fine.
## Supported Kubernetes versions
@@ -30,7 +30,7 @@ The LBC is supported by AWS. Some clusters may be using the legacy "in-tree" fun
Isolated clusters are clusters without internet access, and instead reply on VPC endpoints for all required connects.
When installing the AWS LBC in isolated clusters, you need to disable shield, waf and wafv2 via controller flags `--enable-shield=false, --enable-waf=false, --enable-wafv2=false`
### Using the Amazon EC2 instance metadata server version 2 (IMDSv2)
-We recommend blocking the access to instance metadata by requiring the instance to use [IMDSv2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html) only. For more information, please refer to the AWS guidance [here](https://aws.github.io/aws-eks-best-practices/security/docs/iam/#restrict-access-to-the-instance-profile-assigned-to-the-worker-node). If you are using the IMDSv2, set the hop limit to 2 or higher in order to allow the LBC to perform the metadata introspection.
+We recommend blocking the access to instance metadata by requiring the instance to use [IMDSv2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/configuring-instance-metadata-service.html) only. For more information, please refer to the AWS guidance [here](https://aws.github.io/aws-eks-best-practices/security/docs/iam/#restrict-access-to-the-instance-profile-assigned-to-the-worker-node). If you are using the IMDSv2, set the hop limit to 2 or higher in order to allow the LBC to perform the metadata introspection.
You can set the IMDSv2 as follows:
```
@@ -127,6 +127,10 @@ If you're not setting up IAM roles for service accounts, apply the IAM policies
curl -o iam-policy.json https://raw.githubusercontent.com/kubernetes-sigs/aws-load-balancer-controller/v2.11.0/docs/install/iam_policy.json
```
+## Special IAM cases
+
+### You only want the LBC to add and remove IPs to already existing target groups:
+
The following IAM permissions subset is for those using `TargetGroupBinding` only and don't plan to use the LBC to manage security group rules:
```
@@ -152,6 +156,57 @@ The following IAM permissions subset is for those using `TargetGroupBinding` onl
}
```
+### You only want the LBC to add and remove IPs to already existing target groups, also in other accounts, assuming roles
+
+On the other hand, if you plan to use the LBC to manage also target groups in different accounts, you will need to add `"sts:AssumeRole"` to your list of permissions, in other words:
+
+```
+{
+ "Statement": [
+ {
+ "Action": [
+ "ec2:DescribeVpcs",
+ "ec2:DescribeSecurityGroups",
+ "ec2:DescribeInstances",
+ "elasticloadbalancing:DescribeTargetGroups",
+ "elasticloadbalancing:DescribeTargetHealth",
+ "elasticloadbalancing:ModifyTargetGroup",
+ "elasticloadbalancing:ModifyTargetGroupAttributes",
+ "elasticloadbalancing:RegisterTargets",
+ "elasticloadbalancing:DeregisterTargets",
+ "sts:AssumeRole"
+ ],
+ "Effect": "Allow",
+ "Resource": "*"
+ }
+ ],
+ "Version": "2012-10-17"
+}
+```
+
+The assumed roles will need the exactly the same permissions, without `"sts:AssumeRole"`. The assumed role will need a to allow to be assumed by the main role, something like this:
+
+```
+{
+ "Version": "2012-10-17",
+ "Statement": [
+ {
+ "Sid": "",
+ "Effect": "Allow",
+ "Principal": {
+ "AWS": "arn:aws:iam::999999999999999:user/test-alb-controller"
+ },
+ "Action": "sts:AssumeRole",
+ "Condition": {
+ "StringEquals": {
+ "sts:ExternalId": "very-secret-string"
+ }
+ }
+ }
+ ]
+}
+```
+
## Network configuration
Review the [worker nodes security group](https://docs.aws.amazon.com/eks/latest/userguide/sec-group-reqs.html) docs. Your node security group must permit incoming traffic on TCP port 9443 from the Kubernetes control plane. This is needed for webhook access.
diff --git a/docs/guide/targetgroupbinding/spec.md b/docs/guide/targetgroupbinding/spec.md
index de865b530..f2b9b80c5 100644
--- a/docs/guide/targetgroupbinding/spec.md
+++ b/docs/guide/targetgroupbinding/spec.md
@@ -52,10 +52,29 @@ Kubernetes meta/v1.ObjectMeta
spec
diff --git a/docs/guide/targetgroupbinding/targetgroupbinding.md b/docs/guide/targetgroupbinding/targetgroupbinding.md
index cec6b6f02..0f3a055e7 100644
--- a/docs/guide/targetgroupbinding/targetgroupbinding.md
+++ b/docs/guide/targetgroupbinding/targetgroupbinding.md
@@ -109,6 +109,29 @@ spec:
...
```
+### AssumeRole
+
+Sometimes the AWS LoadBalancer controller needs to manipulate target groups from different AWS accounts.
+The way to do that is assuming a role from such account. There are annotations that can help you with that:
+
+* `alb.ingress.kubernetes.io/IamRoleArnToAssume`: the ARN that you need to assume
+* `alb.ingress.kubernetes.io/AssumeRoleExternalId`: the external ID for the assume role operation. Optional, but recommended. It helps you to prevent the confused deputy problem ( https://docs.aws.amazon.com/IAM/latest/UserGuide/confused-deputy.html )
+
+
+## Sample YAML
+
+```yaml
+apiVersion: elbv2.k8s.aws/v1beta1
+kind: TargetGroupBinding
+metadata:
+ name: my-tgb
+ annotations:
+ alb.ingress.kubernetes.io/IamRoleArnToAssume: "arn:aws:iam::999999999999:role/alb-controller-policy-to-assume"
+ alb.ingress.kubernetes.io/AssumeRoleExternalId: "some-magic-string"
+spec:
+ ...
+```
+
## MultiCluster Target Group
TargetGroupBinding CRD supports sharing the same target group ARN among multiple clusters. Setting this flag will ensure the controller only operates on targets within the cluster.
diff --git a/go.mod b/go.mod
index baafc0f46..80f7ad25c 100644
--- a/go.mod
+++ b/go.mod
@@ -60,6 +60,7 @@ require (
github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.25 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.25 // indirect
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0 // indirect
+ github.com/aws/aws-sdk-go-v2/service/iam v1.36.3 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.3 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.17 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.22.4 // indirect
diff --git a/pkg/aws/cloud.go b/pkg/aws/cloud.go
index 41070e70d..1e9d50f87 100644
--- a/pkg/aws/cloud.go
+++ b/pkg/aws/cloud.go
@@ -3,17 +3,22 @@ package aws
import (
"context"
"fmt"
+ "log"
+ "net"
+ "os"
+ "strings"
+
awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware"
"github.com/aws/aws-sdk-go-v2/aws/ratelimit"
"github.com/aws/aws-sdk-go-v2/aws/retry"
"github.com/aws/aws-sdk-go-v2/config"
+ "github.com/aws/aws-sdk-go-v2/credentials"
ec2types "github.com/aws/aws-sdk-go-v2/service/ec2/types"
+ "github.com/aws/aws-sdk-go-v2/service/sts"
+
smithymiddleware "github.com/aws/smithy-go/middleware"
- "net"
- "os"
"sigs.k8s.io/aws-load-balancer-controller/pkg/aws/throttle"
"sigs.k8s.io/aws-load-balancer-controller/pkg/version"
- "strings"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/feature/ec2/imds"
@@ -29,37 +34,8 @@ import (
const userAgent = "elbv2.k8s.aws"
-type Cloud interface {
- // EC2 provides API to AWS EC2
- EC2() services.EC2
-
- // ELBV2 provides API to AWS ELBV2
- ELBV2() services.ELBV2
-
- // ACM provides API to AWS ACM
- ACM() services.ACM
-
- // WAFv2 provides API to AWS WAFv2
- WAFv2() services.WAFv2
-
- // WAFRegional provides API to AWS WAFRegional
- WAFRegional() services.WAFRegional
-
- // Shield provides API to AWS Shield
- Shield() services.Shield
-
- // RGT provides API to AWS RGT
- RGT() services.RGT
-
- // Region for the kubernetes cluster
- Region() string
-
- // VpcID for the LoadBalancer resources.
- VpcID() string
-}
-
// NewCloud constructs new Cloud implementation.
-func NewCloud(cfg CloudConfig, metricsCollector *aws_metrics.Collector, logger logr.Logger, awsClientsProvider provider.AWSClientsProvider) (Cloud, error) {
+func NewCloud(cfg CloudConfig, metricsCollector *aws_metrics.Collector, logger logr.Logger, awsClientsProvider provider.AWSClientsProvider) (services.Cloud, error) {
hasIPv4 := true
addrs, err := net.InterfaceAddrs()
if err == nil {
@@ -138,17 +114,26 @@ func NewCloud(cfg CloudConfig, metricsCollector *aws_metrics.Collector, logger l
if err != nil {
return nil, errors.Wrap(err, "failed to get VPC ID")
}
+
cfg.VpcID = vpcID
- return &defaultCloud{
+
+ thisObj := &defaultCloud{
cfg: cfg,
ec2: ec2Service,
- elbv2: services.NewELBV2(awsClientsProvider),
acm: services.NewACM(awsClientsProvider),
wafv2: services.NewWAFv2(awsClientsProvider),
wafRegional: services.NewWAFRegional(awsClientsProvider, cfg.Region),
shield: services.NewShield(awsClientsProvider),
rgt: services.NewRGT(awsClientsProvider),
- }, nil
+
+ assumeRoleElbV2: make(map[string]services.ELBV2),
+ awsClientsProvider: awsClientsProvider,
+ logger: logger,
+ }
+
+ thisObj.elbv2 = services.NewELBV2(awsClientsProvider, thisObj)
+
+ return thisObj, nil
}
func getVpcID(cfg CloudConfig, ec2Service services.EC2, ec2Metadata services.EC2Metadata, logger logr.Logger) (string, error) {
@@ -222,7 +207,7 @@ func inferVPCIDFromTags(ec2Service services.EC2, VpcNameTagKey string, VpcNameTa
return *vpcs[0].VpcId, nil
}
-var _ Cloud = &defaultCloud{}
+var _ services.Cloud = &defaultCloud{}
type defaultCloud struct {
cfg CloudConfig
@@ -234,6 +219,78 @@ type defaultCloud struct {
wafRegional services.WAFRegional
shield services.Shield
rgt services.RGT
+
+ assumeRoleElbV2 map[string]services.ELBV2
+ awsClientsProvider provider.AWSClientsProvider
+ logger logr.Logger
+}
+
+// returns ELBV2 client for the given assumeRoleArn, or the default ELBV2 client if assumeRoleArn is empty
+func (c *defaultCloud) GetAssumedRoleELBV2(ctx context.Context, assumeRoleArn string, externalId string) services.ELBV2 {
+
+ if assumeRoleArn == "" {
+ return c.elbv2
+ }
+
+ assumedRoleELBV2, exists := c.assumeRoleElbV2[assumeRoleArn]
+ if exists {
+ return assumedRoleELBV2
+ }
+ c.logger.Info("awsCloud", "method", "GetAssumedRoleELBV2", "AssumeRoleArn", assumeRoleArn, "externalId", externalId)
+
+ ////////////////
+ existingAwsConfig, _ := c.awsClientsProvider.GetAWSConfig(ctx, "GetAWSConfigForIAMRoleImpersonation")
+
+ sourceAccount := sts.NewFromConfig(*existingAwsConfig)
+ response, err := sourceAccount.AssumeRole(ctx, &sts.AssumeRoleInput{
+ RoleArn: aws.String(assumeRoleArn),
+ RoleSessionName: aws.String("aws-load-balancer-controller"),
+ ExternalId: aws.String(externalId),
+ })
+ if err != nil {
+ log.Fatalf("Unable to assume target role, %v. Attempting to use default client", err)
+ return c.elbv2
+ }
+ assumedRoleCreds := response.Credentials
+ newCreds := credentials.NewStaticCredentialsProvider(*assumedRoleCreds.AccessKeyId, *assumedRoleCreds.SecretAccessKey, *assumedRoleCreds.SessionToken)
+ newAwsConfig, err := config.LoadDefaultConfig(ctx, config.WithRegion(c.cfg.Region), config.WithCredentialsProvider(newCreds))
+ if err != nil {
+ log.Fatalf("Unable to load static credentials for service client config, %v. Attempting to use default client", err)
+ return c.elbv2
+ }
+
+ existingAwsConfig.Credentials = newAwsConfig.Credentials // response.Credentials
+
+ // // var assumedRoleCreds *stsTypes.Credentials = response.Credentials
+
+ // // Create config with target service client, using assumed role
+ // cfg, err = config.LoadDefaultConfig(ctx, config.WithRegion(region), config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(*assumedRoleCreds.AccessKeyId, *assumedRoleCreds.SecretAccessKey, *assumedRoleCreds.SessionToken)))
+ // if err != nil {
+ // log.Fatalf("unable to load static credentials for service client config, %v", err)
+ // }
+
+ // ////////////////
+ // appCreds := stscreds.NewAssumeRoleProvider(client, assumeRoleArn)
+ // value, err := appCreds.Retrieve(context.TODO())
+ // if err != nil {
+ // // handle error
+ // }
+ // /////////
+
+ // ///////////// OLD
+ // creds := stscreds.NewCredentials(c.session, assumeRoleArn, func(p *stscreds.AssumeRoleProvider) {
+ // p.ExternalID = &externalId
+ // })
+ // //////////////
+
+ // c.awsConfig.Credentials = creds
+ // // newObj := services.NewELBV2(c.session, c, c.awsCFG)
+ // newObj := services.NewELBV2(*c.awsConfig, c.endpointsResolver, c)
+
+ newObj := services.NewELBV2(c.awsClientsProvider, c)
+ c.assumeRoleElbV2[assumeRoleArn] = newObj
+
+ return newObj
}
func (c *defaultCloud) EC2() services.EC2 {
diff --git a/pkg/aws/provider/default_aws_clients_provider.go b/pkg/aws/provider/default_aws_clients_provider.go
index b43bc2993..41cd78055 100644
--- a/pkg/aws/provider/default_aws_clients_provider.go
+++ b/pkg/aws/provider/default_aws_clients_provider.go
@@ -21,6 +21,8 @@ type defaultAWSClientsProvider struct {
wafRegionClient *wafregional.Client
shieldClient *shield.Client
rgtClient *resourcegroupstaggingapi.Client
+
+ awsConfig *aws.Config
}
func NewDefaultAWSClientsProvider(cfg aws.Config, endpointsResolver *endpoints.Resolver) (*defaultAWSClientsProvider, error) {
@@ -56,7 +58,7 @@ func NewDefaultAWSClientsProvider(cfg aws.Config, endpointsResolver *endpoints.R
o.Region = cfg.Region
o.BaseEndpoint = wafregionalCustomEndpoint
})
- sheildClient := shield.NewFromConfig(cfg, func(o *shield.Options) {
+ shieldClient := shield.NewFromConfig(cfg, func(o *shield.Options) {
o.Region = cfg.Region
o.BaseEndpoint = shieldCustomEndpoint
})
@@ -72,8 +74,10 @@ func NewDefaultAWSClientsProvider(cfg aws.Config, endpointsResolver *endpoints.R
acmClient: acmClient,
wafv2Client: wafv2Client,
wafRegionClient: wafregionalClient,
- shieldClient: sheildClient,
+ shieldClient: shieldClient,
rgtClient: rgtClient,
+
+ awsConfig: &cfg,
}, nil
}
@@ -107,3 +111,7 @@ func (p *defaultAWSClientsProvider) GetShieldClient(ctx context.Context, operati
func (p *defaultAWSClientsProvider) GetRGTClient(ctx context.Context, operationName string) (*resourcegroupstaggingapi.Client, error) {
return p.rgtClient, nil
}
+
+func (p *defaultAWSClientsProvider) GetAWSConfig(ctx context.Context, operationName string) (*aws.Config, error) {
+ return p.awsConfig, nil
+}
diff --git a/pkg/aws/provider/provider.go b/pkg/aws/provider/provider.go
index 95b1c4742..2cdff4574 100644
--- a/pkg/aws/provider/provider.go
+++ b/pkg/aws/provider/provider.go
@@ -2,6 +2,7 @@ package provider
import (
"context"
+ "github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/acm"
"github.com/aws/aws-sdk-go-v2/service/ec2"
"github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2"
@@ -19,4 +20,6 @@ type AWSClientsProvider interface {
GetWAFRegionClient(ctx context.Context, operationName string) (*wafregional.Client, error)
GetShieldClient(ctx context.Context, operationName string) (*shield.Client, error)
GetRGTClient(ctx context.Context, operationName string) (*resourcegroupstaggingapi.Client, error)
+
+ GetAWSConfig(ctx context.Context, operationName string) (*aws.Config, error)
}
diff --git a/pkg/aws/services/cloudInterface.go b/pkg/aws/services/cloudInterface.go
new file mode 100644
index 000000000..3e0ff558e
--- /dev/null
+++ b/pkg/aws/services/cloudInterface.go
@@ -0,0 +1,34 @@
+package services
+
+import "context"
+
+type Cloud interface {
+ // EC2 provides API to AWS EC2
+ EC2() EC2
+
+ // ELBV2 provides API to AWS ELBV2
+ ELBV2() ELBV2
+
+ // ACM provides API to AWS ACM
+ ACM() ACM
+
+ // WAFv2 provides API to AWS WAFv2
+ WAFv2() WAFv2
+
+ // WAFRegional provides API to AWS WAFRegional
+ WAFRegional() WAFRegional
+
+ // Shield provides API to AWS Shield
+ Shield() Shield
+
+ // RGT provides API to AWS RGT
+ RGT() RGT
+
+ // Region for the kubernetes cluster
+ Region() string
+
+ // VpcID for the LoadBalancer resources.
+ VpcID() string
+
+ GetAssumedRoleELBV2(ctx context.Context, assumeRoleArn string, externalId string) ELBV2
+}
diff --git a/pkg/aws/services/elbv2.go b/pkg/aws/services/elbv2.go
index b89b83d00..877cdd5f3 100644
--- a/pkg/aws/services/elbv2.go
+++ b/pkg/aws/services/elbv2.go
@@ -24,7 +24,6 @@ type ELBV2 interface {
// wrapper to DescribeRulesWithContext API, which aggregates paged results into list.
DescribeRulesAsList(ctx context.Context, input *elasticloadbalancingv2.DescribeRulesInput) ([]types.Rule, error)
-
AddTagsWithContext(ctx context.Context, input *elasticloadbalancingv2.AddTagsInput) (*elasticloadbalancingv2.AddTagsOutput, error)
RemoveTagsWithContext(ctx context.Context, input *elasticloadbalancingv2.RemoveTagsInput) (*elasticloadbalancingv2.RemoveTagsOutput, error)
DescribeTagsWithContext(ctx context.Context, input *elasticloadbalancingv2.DescribeTagsInput) (*elasticloadbalancingv2.DescribeTagsOutput, error)
@@ -61,17 +60,27 @@ type ELBV2 interface {
ModifyListenerAttributesWithContext(ctx context.Context, input *elasticloadbalancingv2.ModifyListenerAttributesInput) (*elasticloadbalancingv2.ModifyListenerAttributesOutput, error)
ModifyCapacityReservationWithContext(ctx context.Context, input *elasticloadbalancingv2.ModifyCapacityReservationInput) (*elasticloadbalancingv2.ModifyCapacityReservationOutput, error)
DescribeCapacityReservationWithContext(ctx context.Context, input *elasticloadbalancingv2.DescribeCapacityReservationInput) (*elasticloadbalancingv2.DescribeCapacityReservationOutput, error)
+ AssumeRole(ctx context.Context, assumeRoleArn string, externalId string) ELBV2
}
-func NewELBV2(awsClientsProvider provider.AWSClientsProvider) ELBV2 {
+func NewELBV2(awsClientsProvider provider.AWSClientsProvider, cloud Cloud) ELBV2 {
return &elbv2Client{
awsClientsProvider: awsClientsProvider,
+ cloud: cloud,
}
}
// default implementation for ELBV2.
type elbv2Client struct {
awsClientsProvider provider.AWSClientsProvider
+ cloud Cloud
+}
+
+func (c *elbv2Client) AssumeRole(ctx context.Context, assumeRoleArn string, externalId string) ELBV2 {
+ if assumeRoleArn == "" {
+ return c
+ }
+ return c.cloud.GetAssumedRoleELBV2(ctx, assumeRoleArn, externalId)
}
func (c *elbv2Client) AddListenerCertificatesWithContext(ctx context.Context, input *elasticloadbalancingv2.AddListenerCertificatesInput) (*elasticloadbalancingv2.AddListenerCertificatesOutput, error) {
diff --git a/pkg/aws/services/elbv2_mocks.go b/pkg/aws/services/elbv2_mocks.go
index 805c0e8ac..8d5b540a7 100644
--- a/pkg/aws/services/elbv2_mocks.go
+++ b/pkg/aws/services/elbv2_mocks.go
@@ -66,6 +66,20 @@ func (mr *MockELBV2MockRecorder) AddTagsWithContext(arg0, arg1 interface{}) *gom
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddTagsWithContext", reflect.TypeOf((*MockELBV2)(nil).AddTagsWithContext), arg0, arg1)
}
+// AssumeRole mocks base method.
+func (m *MockELBV2) AssumeRole(arg0 context.Context, arg1, arg2 string) ELBV2 {
+ m.ctrl.T.Helper()
+ ret := m.ctrl.Call(m, "AssumeRole", arg0, arg1, arg2)
+ ret0, _ := ret[0].(ELBV2)
+ return ret0
+}
+
+// AssumeRole indicates an expected call of AssumeRole.
+func (mr *MockELBV2MockRecorder) AssumeRole(arg0, arg1, arg2 interface{}) *gomock.Call {
+ mr.mock.ctrl.T.Helper()
+ return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AssumeRole", reflect.TypeOf((*MockELBV2)(nil).AssumeRole), arg0, arg1, arg2)
+}
+
// CreateListenerWithContext mocks base method.
func (m *MockELBV2) CreateListenerWithContext(arg0 context.Context, arg1 *elasticloadbalancingv2.CreateListenerInput) (*elasticloadbalancingv2.CreateListenerOutput, error) {
m.ctrl.T.Helper()
diff --git a/pkg/deploy/stack_deployer.go b/pkg/deploy/stack_deployer.go
index bcfc6254f..eddba59a9 100644
--- a/pkg/deploy/stack_deployer.go
+++ b/pkg/deploy/stack_deployer.go
@@ -2,8 +2,9 @@ package deploy
import (
"context"
+
"github.com/go-logr/logr"
- "sigs.k8s.io/aws-load-balancer-controller/pkg/aws"
+ "sigs.k8s.io/aws-load-balancer-controller/pkg/aws/services"
"sigs.k8s.io/aws-load-balancer-controller/pkg/config"
"sigs.k8s.io/aws-load-balancer-controller/pkg/deploy/ec2"
"sigs.k8s.io/aws-load-balancer-controller/pkg/deploy/elbv2"
@@ -23,7 +24,7 @@ type StackDeployer interface {
}
// NewDefaultStackDeployer constructs new defaultStackDeployer.
-func NewDefaultStackDeployer(cloud aws.Cloud, k8sClient client.Client,
+func NewDefaultStackDeployer(cloud services.Cloud, k8sClient client.Client,
networkingSGManager networking.SecurityGroupManager, networkingSGReconciler networking.SecurityGroupReconciler,
elbv2TaggingManager elbv2.TaggingManager,
config config.ControllerConfig, tagPrefix string, logger logr.Logger) *defaultStackDeployer {
@@ -58,7 +59,7 @@ var _ StackDeployer = &defaultStackDeployer{}
// defaultStackDeployer is the default implementation for StackDeployer
type defaultStackDeployer struct {
- cloud aws.Cloud
+ cloud services.Cloud
k8sClient client.Client
controllerConfig config.ControllerConfig
addonsConfig config.AddonsConfig
diff --git a/pkg/targetgroupbinding/resource_manager.go b/pkg/targetgroupbinding/resource_manager.go
index af25a824f..666d25b1c 100644
--- a/pkg/targetgroupbinding/resource_manager.go
+++ b/pkg/targetgroupbinding/resource_manager.go
@@ -3,12 +3,13 @@ package targetgroupbinding
import (
"context"
"fmt"
- elbv2types "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2/types"
- "github.com/aws/smithy-go"
"net/netip"
lbcmetrics "sigs.k8s.io/aws-load-balancer-controller/pkg/metrics/lbc"
"time"
+ elbv2types "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2/types"
+ "github.com/aws/smithy-go"
+
"k8s.io/client-go/tools/record"
awssdk "github.com/aws/aws-sdk-go-v2/aws"
@@ -95,6 +96,7 @@ func (m *defaultResourceManager) Reconcile(ctx context.Context, tgb *elbv2api.Ta
var oldCheckPoint string
var isDeferred bool
var err error
+ AnnotationsToFields(tgb)
if *tgb.Spec.TargetType == elbv2api.TargetTypeIP {
newCheckPoint, oldCheckPoint, isDeferred, err = m.reconcileWithIPTargetType(ctx, tgb)
@@ -114,6 +116,7 @@ func (m *defaultResourceManager) Reconcile(ctx context.Context, tgb *elbv2api.Ta
}
func (m *defaultResourceManager) Cleanup(ctx context.Context, tgb *elbv2api.TargetGroupBinding) error {
+ AnnotationsToFields(tgb)
if err := m.cleanupTargets(ctx, tgb); err != nil {
return err
}
@@ -168,9 +171,7 @@ func (m *defaultResourceManager) reconcileWithIPTargetType(ctx context.Context,
return newCheckPoint, oldCheckPoint, true, nil
}
- tgARN := tgb.Spec.TargetGroupARN
- vpcID := tgb.Spec.VpcID
- targets, err := m.targetsManager.ListTargets(ctx, tgARN)
+ targets, err := m.targetsManager.ListTargets(ctx, tgb)
if err != nil {
return "", "", false, err
}
@@ -211,7 +212,7 @@ func (m *defaultResourceManager) reconcileWithIPTargetType(ctx context.Context,
updateTrackedTargets := false
if len(unmatchedTargets) > 0 {
- updateTrackedTargets, err = m.deregisterTargets(ctx, tgb, tgARN, unmatchedTargets)
+ updateTrackedTargets, err = m.deregisterTargets(ctx, tgb, unmatchedTargets)
if err != nil {
return "", "", false, err
}
@@ -234,7 +235,7 @@ func (m *defaultResourceManager) reconcileWithIPTargetType(ctx context.Context,
return "", "", false, err
}
- if err := m.registerPodEndpoints(ctx, tgARN, vpcID, unmatchedEndpoints); err != nil {
+ if err := m.registerPodEndpoints(ctx, tgb, unmatchedEndpoints); err != nil {
return "", "", false, err
}
}
@@ -298,8 +299,7 @@ func (m *defaultResourceManager) reconcileWithInstanceTargetType(ctx context.Con
return newCheckPoint, oldCheckPoint, true, nil
}
- tgARN := tgb.Spec.TargetGroupARN
- targets, err := m.targetsManager.ListTargets(ctx, tgARN)
+ targets, err := m.targetsManager.ListTargets(ctx, tgb)
if err != nil {
return "", "", false, err
}
@@ -325,7 +325,7 @@ func (m *defaultResourceManager) reconcileWithInstanceTargetType(ctx context.Con
updateTrackedTargets := false
if len(unmatchedTargets) > 0 {
- updateTrackedTargets, err = m.deregisterTargets(ctx, tgb, tgARN, unmatchedTargets)
+ updateTrackedTargets, err = m.deregisterTargets(ctx, tgb, unmatchedTargets)
if err != nil {
return "", "", false, err
}
@@ -337,7 +337,7 @@ func (m *defaultResourceManager) reconcileWithInstanceTargetType(ctx context.Con
return "", "", false, err
}
- if err := m.registerNodePortEndpoints(ctx, tgARN, unmatchedEndpoints); err != nil {
+ if err := m.registerNodePortEndpoints(ctx, tgb, unmatchedEndpoints); err != nil {
return "", "", false, err
}
}
@@ -351,7 +351,7 @@ func (m *defaultResourceManager) reconcileWithInstanceTargetType(ctx context.Con
}
func (m *defaultResourceManager) cleanupTargets(ctx context.Context, tgb *elbv2api.TargetGroupBinding) error {
- targets, err := m.targetsManager.ListTargets(ctx, tgb.Spec.TargetGroupARN)
+ targets, err := m.targetsManager.ListTargets(ctx, tgb)
if err != nil {
if isELBV2TargetGroupNotFoundError(err) {
return nil
@@ -361,7 +361,7 @@ func (m *defaultResourceManager) cleanupTargets(ctx context.Context, tgb *elbv2a
return err
}
- _, err = m.deregisterTargets(ctx, tgb, tgb.Spec.TargetGroupARN, targets)
+ _, err = m.deregisterTargets(ctx, tgb, targets)
if err != nil {
if isELBV2TargetGroupNotFoundError(err) {
@@ -527,7 +527,7 @@ func (m *defaultResourceManager) updatePodAsHealthyForDeletedTGB(ctx context.Con
return nil
}
-func (m *defaultResourceManager) deregisterTargets(ctx context.Context, tgb *elbv2api.TargetGroupBinding, tgARN string, targets []TargetInfo) (bool, error) {
+func (m *defaultResourceManager) deregisterTargets(ctx context.Context, tgb *elbv2api.TargetGroupBinding, targets []TargetInfo) (bool, error) {
filteredTargets, updateTrackedTargets, err := m.multiClusterManager.FilterTargetsForDeregistration(ctx, tgb, targets)
if err != nil {
return false, err
@@ -541,16 +541,34 @@ func (m *defaultResourceManager) deregisterTargets(ctx context.Context, tgb *elb
for _, target := range filteredTargets {
sdkTargets = append(sdkTargets, target.Target)
}
- return true, m.targetsManager.DeregisterTargets(ctx, tgARN, sdkTargets)
+ return true, m.targetsManager.DeregisterTargets(ctx, tgb, sdkTargets)
}
-func (m *defaultResourceManager) registerPodEndpoints(ctx context.Context, tgARN, tgVpcID string, endpoints []backend.PodEndpoint) error {
+func (m *defaultResourceManager) registerPodEndpoints(ctx context.Context, tgb *elbv2api.TargetGroupBinding, endpoints []backend.PodEndpoint) error {
vpcID := m.vpcID
// Target group is in a different VPC from the cluster's VPC
- if tgVpcID != "" && tgVpcID != m.vpcID {
- vpcID = tgVpcID
- m.logger.Info("registering endpoints using the targetGroup's vpcID", "TG VPC", tgVpcID,
- "cluster's vpcID", m.vpcID)
+ if tgb.Spec.VpcID != "" && tgb.Spec.VpcID != m.vpcID {
+ vpcID = tgb.Spec.VpcID
+ m.logger.Info(fmt.Sprintf(
+ "registering endpoints using the targetGroup's vpcID %s which is different from the cluster's vpcID %s", tgb.Spec.VpcID, m.vpcID))
+
+ if tgb.Spec.IamRoleArnToAssume != "" {
+ // since we need to assume a role for this TGB,
+ // it is from a different account
+ // so the packets will need to leave the VPC and therefore
+ // target.AvailabilityZone = awssdk.String("all") must be set
+ // or else nothing will work
+ sdkTargets := make([]elbv2types.TargetDescription, 0, len(endpoints))
+ for _, endpoint := range endpoints {
+ target := elbv2types.TargetDescription{
+ Id: awssdk.String(endpoint.IP),
+ Port: awssdk.Int32(endpoint.Port),
+ }
+ target.AvailabilityZone = awssdk.String("all")
+ sdkTargets = append(sdkTargets, target)
+ }
+ return m.targetsManager.RegisterTargets(ctx, tgb, sdkTargets)
+ }
}
vpcInfo, err := m.vpcInfoProvider.FetchVPCInfo(ctx, vpcID)
if err != nil {
@@ -579,10 +597,10 @@ func (m *defaultResourceManager) registerPodEndpoints(ctx context.Context, tgARN
}
sdkTargets = append(sdkTargets, target)
}
- return m.targetsManager.RegisterTargets(ctx, tgARN, sdkTargets)
+ return m.targetsManager.RegisterTargets(ctx, tgb, sdkTargets)
}
-func (m *defaultResourceManager) registerNodePortEndpoints(ctx context.Context, tgARN string, endpoints []backend.NodePortEndpoint) error {
+func (m *defaultResourceManager) registerNodePortEndpoints(ctx context.Context, tgb *elbv2api.TargetGroupBinding, endpoints []backend.NodePortEndpoint) error {
sdkTargets := make([]elbv2types.TargetDescription, 0, len(endpoints))
for _, endpoint := range endpoints {
sdkTargets = append(sdkTargets, elbv2types.TargetDescription{
@@ -590,7 +608,7 @@ func (m *defaultResourceManager) registerNodePortEndpoints(ctx context.Context,
Port: awssdk.Int32(endpoint.Port),
})
}
- return m.targetsManager.RegisterTargets(ctx, tgARN, sdkTargets)
+ return m.targetsManager.RegisterTargets(ctx, tgb, sdkTargets)
}
func (m *defaultResourceManager) updateTGBCheckPoint(ctx context.Context, tgb *elbv2api.TargetGroupBinding, newCheckPoint, previousCheckPoint string) error {
diff --git a/pkg/targetgroupbinding/targets_manager.go b/pkg/targetgroupbinding/targets_manager.go
index b32eb350e..b00f95a9b 100644
--- a/pkg/targetgroupbinding/targets_manager.go
+++ b/pkg/targetgroupbinding/targets_manager.go
@@ -2,14 +2,16 @@ package targetgroupbinding
import (
"context"
+ "sync"
+ "time"
+
"github.com/aws/aws-sdk-go-v2/aws"
elbv2sdk "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2"
elbv2types "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2/types"
"github.com/go-logr/logr"
"k8s.io/apimachinery/pkg/util/cache"
+ elbv2api "sigs.k8s.io/aws-load-balancer-controller/apis/elbv2/v1beta1"
"sigs.k8s.io/aws-load-balancer-controller/pkg/aws/services"
- "sync"
- "time"
)
const (
@@ -21,13 +23,13 @@ const (
// TargetsManager is an abstraction around ELBV2's targets API.
type TargetsManager interface {
// Register Targets into TargetGroup.
- RegisterTargets(ctx context.Context, tgARN string, targets []elbv2types.TargetDescription) error
+ RegisterTargets(ctx context.Context, tgb *elbv2api.TargetGroupBinding, targets []elbv2types.TargetDescription) error
// Deregister Targets from TargetGroup.
- DeregisterTargets(ctx context.Context, tgARN string, targets []elbv2types.TargetDescription) error
+ DeregisterTargets(ctx context.Context, tgb *elbv2api.TargetGroupBinding, targets []elbv2types.TargetDescription) error
// List Targets from TargetGroup.
- ListTargets(ctx context.Context, tgARN string) ([]TargetInfo, error)
+ ListTargets(ctx context.Context, tgb *elbv2api.TargetGroupBinding) ([]TargetInfo, error)
}
// NewCachedTargetsManager constructs new cachedTargetsManager
@@ -76,7 +78,8 @@ type targetsCacheItem struct {
targets []TargetInfo
}
-func (m *cachedTargetsManager) RegisterTargets(ctx context.Context, tgARN string, targets []elbv2types.TargetDescription) error {
+func (m *cachedTargetsManager) RegisterTargets(ctx context.Context, tgb *elbv2api.TargetGroupBinding, targets []elbv2types.TargetDescription) error {
+ tgARN := tgb.Spec.TargetGroupARN
targetsChunks := chunkTargetDescriptions(targets, m.registerTargetsChunkSize)
for _, targetsChunk := range targetsChunks {
req := &elbv2sdk.RegisterTargetsInput{
@@ -86,7 +89,7 @@ func (m *cachedTargetsManager) RegisterTargets(ctx context.Context, tgARN string
m.logger.Info("registering targets",
"arn", tgARN,
"targets", targetsChunk)
- _, err := m.elbv2Client.RegisterTargetsWithContext(ctx, req)
+ _, err := m.elbv2Client.AssumeRole(ctx, tgb.Spec.IamRoleArnToAssume, tgb.Spec.AssumeRoleExternalId).RegisterTargetsWithContext(ctx, req)
if err != nil {
return err
}
@@ -97,7 +100,8 @@ func (m *cachedTargetsManager) RegisterTargets(ctx context.Context, tgARN string
return nil
}
-func (m *cachedTargetsManager) DeregisterTargets(ctx context.Context, tgARN string, targets []elbv2types.TargetDescription) error {
+func (m *cachedTargetsManager) DeregisterTargets(ctx context.Context, tgb *elbv2api.TargetGroupBinding, targets []elbv2types.TargetDescription) error {
+ tgARN := tgb.Spec.TargetGroupARN
targetsChunks := chunkTargetDescriptions(targets, m.deregisterTargetsChunkSize)
for _, targetsChunk := range targetsChunks {
req := &elbv2sdk.DeregisterTargetsInput{
@@ -107,7 +111,7 @@ func (m *cachedTargetsManager) DeregisterTargets(ctx context.Context, tgARN stri
m.logger.Info("deRegistering targets",
"arn", tgARN,
"targets", targetsChunk)
- _, err := m.elbv2Client.DeregisterTargetsWithContext(ctx, req)
+ _, err := m.elbv2Client.AssumeRole(ctx, tgb.Spec.IamRoleArnToAssume, tgb.Spec.AssumeRoleExternalId).DeregisterTargetsWithContext(ctx, req)
if err != nil {
return err
}
@@ -118,7 +122,8 @@ func (m *cachedTargetsManager) DeregisterTargets(ctx context.Context, tgARN stri
return nil
}
-func (m *cachedTargetsManager) ListTargets(ctx context.Context, tgARN string) ([]TargetInfo, error) {
+func (m *cachedTargetsManager) ListTargets(ctx context.Context, tgb *elbv2api.TargetGroupBinding) ([]TargetInfo, error) {
+ tgARN := tgb.Spec.TargetGroupARN
m.targetsCacheMutex.Lock()
defer m.targetsCacheMutex.Unlock()
@@ -126,7 +131,7 @@ func (m *cachedTargetsManager) ListTargets(ctx context.Context, tgARN string) ([
targetsCacheItem := rawTargetsCacheItem.(*targetsCacheItem)
targetsCacheItem.mutex.Lock()
defer targetsCacheItem.mutex.Unlock()
- refreshedTargets, err := m.refreshUnhealthyTargets(ctx, tgARN, targetsCacheItem.targets)
+ refreshedTargets, err := m.refreshUnhealthyTargets(ctx, tgb, targetsCacheItem.targets)
if err != nil {
return nil, err
}
@@ -134,7 +139,7 @@ func (m *cachedTargetsManager) ListTargets(ctx context.Context, tgARN string) ([
return cloneTargetInfoSlice(refreshedTargets), nil
}
- refreshedTargets, err := m.refreshAllTargets(ctx, tgARN)
+ refreshedTargets, err := m.refreshAllTargets(ctx, tgb)
if err != nil {
return nil, err
}
@@ -147,8 +152,8 @@ func (m *cachedTargetsManager) ListTargets(ctx context.Context, tgARN string) ([
}
// refreshAllTargets will refresh all targets for targetGroup.
-func (m *cachedTargetsManager) refreshAllTargets(ctx context.Context, tgARN string) ([]TargetInfo, error) {
- targets, err := m.listTargetsFromAWS(ctx, tgARN, nil)
+func (m *cachedTargetsManager) refreshAllTargets(ctx context.Context, tgb *elbv2api.TargetGroupBinding) ([]TargetInfo, error) {
+ targets, err := m.listTargetsFromAWS(ctx, tgb, nil)
if err != nil {
return nil, err
}
@@ -158,7 +163,7 @@ func (m *cachedTargetsManager) refreshAllTargets(ctx context.Context, tgARN stri
// refreshUnhealthyTargets will refresh targets that are not in healthy status for targetGroup.
// To save API calls, we don't refresh targets that are already healthy since once a target turns healthy, we'll unblock it's readinessProbe.
// we can do nothing from controller perspective when a healthy target becomes unhealthy.
-func (m *cachedTargetsManager) refreshUnhealthyTargets(ctx context.Context, tgARN string, cachedTargets []TargetInfo) ([]TargetInfo, error) {
+func (m *cachedTargetsManager) refreshUnhealthyTargets(ctx context.Context, tgb *elbv2api.TargetGroupBinding, cachedTargets []TargetInfo) ([]TargetInfo, error) {
var refreshedTargets []TargetInfo
var unhealthyTargets []elbv2types.TargetDescription
for _, cachedTarget := range cachedTargets {
@@ -172,7 +177,7 @@ func (m *cachedTargetsManager) refreshUnhealthyTargets(ctx context.Context, tgAR
return refreshedTargets, nil
}
- refreshedUnhealthyTargets, err := m.listTargetsFromAWS(ctx, tgARN, unhealthyTargets)
+ refreshedUnhealthyTargets, err := m.listTargetsFromAWS(ctx, tgb, unhealthyTargets)
if err != nil {
return nil, err
}
@@ -188,12 +193,13 @@ func (m *cachedTargetsManager) refreshUnhealthyTargets(ctx context.Context, tgAR
// listTargetsFromAWS will list targets for TargetGroup using ELBV2API.
// if specified targets is non-empty, only these targets will be listed.
// otherwise, all targets for targetGroup will be listed.
-func (m *cachedTargetsManager) listTargetsFromAWS(ctx context.Context, tgARN string, targets []elbv2types.TargetDescription) ([]TargetInfo, error) {
+func (m *cachedTargetsManager) listTargetsFromAWS(ctx context.Context, tgb *elbv2api.TargetGroupBinding, targets []elbv2types.TargetDescription) ([]TargetInfo, error) {
+ tgARN := tgb.Spec.TargetGroupARN
req := &elbv2sdk.DescribeTargetHealthInput{
TargetGroupArn: aws.String(tgARN),
Targets: pointerizeTargetDescriptions(targets),
}
- resp, err := m.elbv2Client.DescribeTargetHealthWithContext(ctx, req)
+ resp, err := m.elbv2Client.AssumeRole(ctx, tgb.Spec.IamRoleArnToAssume, tgb.Spec.AssumeRoleExternalId).DescribeTargetHealthWithContext(ctx, req)
if err != nil {
return nil, err
}
diff --git a/pkg/targetgroupbinding/targets_manager_test.go b/pkg/targetgroupbinding/targets_manager_test.go
index 1a291ffd1..f4f476fe0 100644
--- a/pkg/targetgroupbinding/targets_manager_test.go
+++ b/pkg/targetgroupbinding/targets_manager_test.go
@@ -2,19 +2,34 @@ package targetgroupbinding
import (
"context"
+ "sync"
+ "testing"
+ "time"
+
awssdk "github.com/aws/aws-sdk-go-v2/aws"
elbv2sdk "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2"
elbv2types "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2/types"
- "github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
+
+ "github.com/golang/mock/gomock"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/cache"
+ elbv2api "sigs.k8s.io/aws-load-balancer-controller/apis/elbv2/v1beta1"
"sigs.k8s.io/aws-load-balancer-controller/pkg/aws/services"
"sigs.k8s.io/controller-runtime/pkg/log"
- "sync"
- "testing"
- "time"
)
+func makeTargetGroupBinding(tgARN string) *elbv2api.TargetGroupBinding {
+ return &elbv2api.TargetGroupBinding{
+ ObjectMeta: metav1.ObjectMeta{
+ Annotations: map[string]string{},
+ },
+ Spec: elbv2api.TargetGroupBindingSpec{
+ TargetGroupARN: tgARN,
+ },
+ }
+}
+
func Test_cachedTargetsManager_RegisterTargets(t *testing.T) {
type registerTargetsWithContextCall struct {
req *elbv2sdk.RegisterTargetsInput
@@ -262,8 +277,10 @@ func Test_cachedTargetsManager_RegisterTargets(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
elbv2Client := services.NewMockELBV2(ctrl)
+ ctx := context.Background()
for _, call := range tt.fields.registerTargetsWithContextCalls {
elbv2Client.EXPECT().RegisterTargetsWithContext(gomock.Any(), call.req).Return(call.resp, call.err)
+ elbv2Client.EXPECT().AssumeRole(ctx, gomock.Any(), gomock.Any()).Return(elbv2Client)
}
targetsCache := cache.NewExpiring()
@@ -282,8 +299,7 @@ func Test_cachedTargetsManager_RegisterTargets(t *testing.T) {
logger: log.Log,
}
- ctx := context.Background()
- err := m.RegisterTargets(ctx, tt.args.tgARN, tt.args.targets)
+ err := m.RegisterTargets(ctx, makeTargetGroupBinding(tt.args.tgARN), tt.args.targets)
if tt.wantErr != nil {
assert.EqualError(t, err, tt.wantErr.Error())
} else {
@@ -507,8 +523,10 @@ func Test_cachedTargetsManager_DeregisterTargets(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
elbv2Client := services.NewMockELBV2(ctrl)
+ ctx := context.Background()
for _, call := range tt.fields.deregisterTargetsWithContextCalls {
elbv2Client.EXPECT().DeregisterTargetsWithContext(gomock.Any(), call.req).Return(call.resp, call.err)
+ elbv2Client.EXPECT().AssumeRole(ctx, gomock.Any(), gomock.Any()).Return(elbv2Client)
}
targetsCache := cache.NewExpiring()
@@ -527,8 +545,7 @@ func Test_cachedTargetsManager_DeregisterTargets(t *testing.T) {
logger: log.Log,
}
- ctx := context.Background()
- err := m.DeregisterTargets(ctx, tt.args.tgARN, tt.args.targets)
+ err := m.DeregisterTargets(ctx, makeTargetGroupBinding(tt.args.tgARN), tt.args.targets)
if tt.wantErr != nil {
assert.EqualError(t, err, tt.wantErr.Error())
} else {
@@ -770,10 +787,12 @@ func Test_cachedTargetsManager_ListTargets(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
+ ctx := context.Background()
elbv2Client := services.NewMockELBV2(ctrl)
for _, call := range tt.fields.describeTargetHealthWithContextCalls {
elbv2Client.EXPECT().DescribeTargetHealthWithContext(gomock.Any(), call.req).Return(call.resp, call.err)
+ elbv2Client.EXPECT().AssumeRole(ctx, gomock.Any(), gomock.Any()).Return(elbv2Client)
}
targetsCache := cache.NewExpiring()
targetsCacheTTL := 1 * time.Minute
@@ -790,8 +809,7 @@ func Test_cachedTargetsManager_ListTargets(t *testing.T) {
targetsCacheTTL: targetsCacheTTL,
}
- ctx := context.Background()
- got, err := m.ListTargets(ctx, tt.args.tgARN)
+ got, err := m.ListTargets(ctx, makeTargetGroupBinding(tt.args.tgARN))
if tt.wantErr != nil {
assert.EqualError(t, err, tt.wantErr.Error())
} else {
@@ -1180,16 +1198,17 @@ func Test_cachedTargetsManager_refreshUnhealthyTargets(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
+ ctx := context.Background()
elbv2Client := services.NewMockELBV2(ctrl)
for _, call := range tt.fields.describeTargetHealthWithContextCalls {
elbv2Client.EXPECT().DescribeTargetHealthWithContext(gomock.Any(), call.req).Return(call.resp, call.err)
+ elbv2Client.EXPECT().AssumeRole(ctx, gomock.Any(), gomock.Any()).Return(elbv2Client)
}
m := &cachedTargetsManager{
elbv2Client: elbv2Client,
}
- ctx := context.Background()
- got, err := m.refreshUnhealthyTargets(ctx, tt.args.tgARN, tt.args.cachedTargets)
+ got, err := m.refreshUnhealthyTargets(ctx, makeTargetGroupBinding(tt.args.tgARN), tt.args.cachedTargets)
if tt.wantErr != nil {
assert.EqualError(t, err, tt.wantErr.Error())
} else {
@@ -1341,18 +1360,20 @@ func Test_cachedTargetsManager_listTargetsFromAWS(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
+ ctx := context.Background()
+
defer ctrl.Finish()
elbv2Client := services.NewMockELBV2(ctrl)
for _, call := range tt.fields.describeTargetHealthWithContextCalls {
elbv2Client.EXPECT().DescribeTargetHealthWithContext(gomock.Any(), call.req).Return(call.resp, call.err)
+ elbv2Client.EXPECT().AssumeRole(ctx, gomock.Any(), gomock.Any()).Return(elbv2Client)
}
m := &cachedTargetsManager{
elbv2Client: elbv2Client,
}
- ctx := context.Background()
- got, err := m.listTargetsFromAWS(ctx, tt.args.tgARN, tt.args.targets)
+ got, err := m.listTargetsFromAWS(ctx, makeTargetGroupBinding(tt.args.tgARN), tt.args.targets)
if tt.wantErr != nil {
assert.EqualError(t, err, tt.wantErr.Error())
} else {
diff --git a/pkg/targetgroupbinding/utils.go b/pkg/targetgroupbinding/utils.go
index 9b9cddabe..013c94081 100644
--- a/pkg/targetgroupbinding/utils.go
+++ b/pkg/targetgroupbinding/utils.go
@@ -3,6 +3,7 @@ package targetgroupbinding
import (
"encoding/json"
"fmt"
+
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
elbv2api "sigs.k8s.io/aws-load-balancer-controller/apis/elbv2/v1beta1"
@@ -24,8 +25,27 @@ const (
// Index Key for "ServiceReference" index.
IndexKeyServiceRefName = "spec.serviceRef.name"
+
+ // Annotation for IAM Role ARN to assume when calling AWS APIs.
+ AnnotationIamRoleArnToAssume = "alb.ingress.kubernetes.io/IamRoleArnToAssume"
+
+ // Annotation for IAM Role External ID to use when calling AWS APIs.
+ AnnotationAssumeRoleExternalId = "alb.ingress.kubernetes.io/AssumeRoleExternalId"
)
+// AnnotationsToFields converts annotations to fields. Currently it's tgb.Spec.IamRoleArnToAssume and tgb.Spec.AssumeRoleExternalId
+func AnnotationsToFields(tgb *elbv2api.TargetGroupBinding) {
+ for key, value := range tgb.Annotations {
+ if key == AnnotationIamRoleArnToAssume {
+ tgb.Spec.IamRoleArnToAssume = value
+ } else {
+ if key == AnnotationAssumeRoleExternalId {
+ tgb.Spec.AssumeRoleExternalId = value
+ }
+ }
+ }
+}
+
// BuildTargetHealthPodConditionType constructs the condition type for TargetHealth pod condition.
func BuildTargetHealthPodConditionType(tgb *elbv2api.TargetGroupBinding) corev1.PodConditionType {
return corev1.PodConditionType(fmt.Sprintf("%s/%s", TargetHealthPodConditionTypePrefix, tgb.Name))
diff --git a/test/framework/framework.go b/test/framework/framework.go
index 52171817a..9830647bb 100644
--- a/test/framework/framework.go
+++ b/test/framework/framework.go
@@ -8,6 +8,7 @@ import (
"k8s.io/client-go/rest"
elbv2api "sigs.k8s.io/aws-load-balancer-controller/apis/elbv2/v1beta1"
"sigs.k8s.io/aws-load-balancer-controller/pkg/aws"
+ "sigs.k8s.io/aws-load-balancer-controller/pkg/aws/services"
"sigs.k8s.io/aws-load-balancer-controller/pkg/aws/throttle"
"sigs.k8s.io/aws-load-balancer-controller/test/framework/controller"
"sigs.k8s.io/aws-load-balancer-controller/test/framework/helm"
@@ -23,7 +24,7 @@ type Framework struct {
Options Options
RestCfg *rest.Config
K8sClient client.Client
- Cloud aws.Cloud
+ Cloud services.Cloud
CTRLInstallationManager controller.InstallationManager
NSManager k8sresources.NamespaceManager
diff --git a/webhooks/elbv2/targetgroupbinding_mutator.go b/webhooks/elbv2/targetgroupbinding_mutator.go
index dd9fb557e..7818ce39d 100644
--- a/webhooks/elbv2/targetgroupbinding_mutator.go
+++ b/webhooks/elbv2/targetgroupbinding_mutator.go
@@ -2,15 +2,18 @@ package elbv2
import (
"context"
+
elbv2types "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2/types"
awssdk "github.com/aws/aws-sdk-go-v2/aws"
elbv2sdk "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2"
+
"github.com/go-logr/logr"
"github.com/pkg/errors"
"k8s.io/apimachinery/pkg/runtime"
elbv2api "sigs.k8s.io/aws-load-balancer-controller/apis/elbv2/v1beta1"
"sigs.k8s.io/aws-load-balancer-controller/pkg/aws/services"
+ "sigs.k8s.io/aws-load-balancer-controller/pkg/targetgroupbinding"
"sigs.k8s.io/aws-load-balancer-controller/pkg/webhook"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
@@ -45,6 +48,7 @@ func (m *targetGroupBindingMutator) MutateCreate(ctx context.Context, obj runtim
if err := m.getArnFromNameIfNeeded(ctx, tgb); err != nil {
return nil, err
}
+ targetgroupbinding.AnnotationsToFields(tgb)
if err := m.defaultingTargetType(ctx, tgb); err != nil {
return nil, err
}
@@ -76,8 +80,7 @@ func (m *targetGroupBindingMutator) defaultingTargetType(ctx context.Context, tg
if tgb.Spec.TargetType != nil {
return nil
}
- tgARN := tgb.Spec.TargetGroupARN
- sdkTargetType, err := m.obtainSDKTargetTypeFromAWS(ctx, tgARN)
+ sdkTargetType, err := m.obtainSDKTargetTypeFromAWS(ctx, tgb)
if err != nil {
return errors.Wrap(err, "couldn't determine TargetType")
}
@@ -99,7 +102,7 @@ func (m *targetGroupBindingMutator) defaultingIPAddressType(ctx context.Context,
if tgb.Spec.IPAddressType != nil {
return nil
}
- targetGroupIPAddressType, err := m.getTargetGroupIPAddressTypeFromAWS(ctx, tgb.Spec.TargetGroupARN)
+ targetGroupIPAddressType, err := m.getTargetGroupIPAddressTypeFromAWS(ctx, tgb)
if err != nil {
return errors.Wrap(err, "unable to get target group IP address type")
}
@@ -111,7 +114,7 @@ func (m *targetGroupBindingMutator) defaultingVpcID(ctx context.Context, tgb *el
if tgb.Spec.VpcID != "" {
return nil
}
- vpcId, err := m.getVpcIDFromAWS(ctx, tgb.Spec.TargetGroupARN)
+ vpcId, err := m.getVpcIDFromAWS(ctx, tgb)
if err != nil {
return errors.Wrap(err, "unable to get target group VpcID")
}
@@ -119,8 +122,8 @@ func (m *targetGroupBindingMutator) defaultingVpcID(ctx context.Context, tgb *el
return nil
}
-func (m *targetGroupBindingMutator) obtainSDKTargetTypeFromAWS(ctx context.Context, tgARN string) (string, error) {
- targetGroup, err := m.getTargetGroupFromAWS(ctx, tgARN)
+func (m *targetGroupBindingMutator) obtainSDKTargetTypeFromAWS(ctx context.Context, tgb *elbv2api.TargetGroupBinding) (string, error) {
+ targetGroup, err := m.getTargetGroupFromAWS(ctx, tgb)
if err != nil {
return "", err
}
@@ -128,8 +131,8 @@ func (m *targetGroupBindingMutator) obtainSDKTargetTypeFromAWS(ctx context.Conte
}
// getTargetGroupIPAddressTypeFromAWS returns the target group IP address type of AWS target group
-func (m *targetGroupBindingMutator) getTargetGroupIPAddressTypeFromAWS(ctx context.Context, tgARN string) (elbv2api.TargetGroupIPAddressType, error) {
- targetGroup, err := m.getTargetGroupFromAWS(ctx, tgARN)
+func (m *targetGroupBindingMutator) getTargetGroupIPAddressTypeFromAWS(ctx context.Context, tgb *elbv2api.TargetGroupBinding) (elbv2api.TargetGroupIPAddressType, error) {
+ targetGroup, err := m.getTargetGroupFromAWS(ctx, tgb)
if err != nil {
return "", err
}
@@ -145,11 +148,12 @@ func (m *targetGroupBindingMutator) getTargetGroupIPAddressTypeFromAWS(ctx conte
return ipAddressType, nil
}
-func (m *targetGroupBindingMutator) getTargetGroupFromAWS(ctx context.Context, tgARN string) (*elbv2types.TargetGroup, error) {
+func (m *targetGroupBindingMutator) getTargetGroupFromAWS(ctx context.Context, tgb *elbv2api.TargetGroupBinding) (*elbv2types.TargetGroup, error) {
+ tgARN := tgb.Spec.TargetGroupARN
req := &elbv2sdk.DescribeTargetGroupsInput{
TargetGroupArns: []string{tgARN},
}
- tgList, err := m.elbv2Client.DescribeTargetGroupsAsList(ctx, req)
+ tgList, err := m.elbv2Client.AssumeRole(ctx, tgb.Spec.IamRoleArnToAssume, tgb.Spec.AssumeRoleExternalId).DescribeTargetGroupsAsList(ctx, req)
if err != nil {
return nil, err
}
@@ -173,8 +177,8 @@ func (m *targetGroupBindingMutator) getTargetGroupsByNameFromAWS(ctx context.Con
return &tgList[0], nil
}
-func (m *targetGroupBindingMutator) getVpcIDFromAWS(ctx context.Context, tgARN string) (string, error) {
- targetGroup, err := m.getTargetGroupFromAWS(ctx, tgARN)
+func (m *targetGroupBindingMutator) getVpcIDFromAWS(ctx context.Context, tgb *elbv2api.TargetGroupBinding) (string, error) {
+ targetGroup, err := m.getTargetGroupFromAWS(ctx, tgb)
if err != nil {
return "", err
}
diff --git a/webhooks/elbv2/targetgroupbinding_mutator_test.go b/webhooks/elbv2/targetgroupbinding_mutator_test.go
index f23692f80..032440ad1 100644
--- a/webhooks/elbv2/targetgroupbinding_mutator_test.go
+++ b/webhooks/elbv2/targetgroupbinding_mutator_test.go
@@ -2,20 +2,33 @@ package elbv2
import (
"context"
- elbv2types "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2/types"
"testing"
+ elbv2types "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2/types"
+
awssdk "github.com/aws/aws-sdk-go-v2/aws"
elbv2sdk "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2"
"github.com/go-logr/logr"
"github.com/golang/mock/gomock"
"github.com/pkg/errors"
"github.com/stretchr/testify/assert"
+ metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
elbv2api "sigs.k8s.io/aws-load-balancer-controller/apis/elbv2/v1beta1"
"sigs.k8s.io/aws-load-balancer-controller/pkg/aws/services"
"sigs.k8s.io/controller-runtime/pkg/log"
)
+func makeTargetGroupBinding(tgARN string) *elbv2api.TargetGroupBinding {
+ return &elbv2api.TargetGroupBinding{
+ ObjectMeta: metav1.ObjectMeta{
+ Annotations: map[string]string{},
+ },
+ Spec: elbv2api.TargetGroupBindingSpec{
+ TargetGroupARN: tgARN,
+ },
+ }
+}
+
func Test_targetGroupBindingMutator_MutateCreate(t *testing.T) {
type describeTargetGroupsAsListCall struct {
req *elbv2sdk.DescribeTargetGroupsInput
@@ -292,8 +305,10 @@ func Test_targetGroupBindingMutator_MutateCreate(t *testing.T) {
ctrl := gomock.NewController(t)
defer ctrl.Finish()
elbv2Client := services.NewMockELBV2(ctrl)
+ ctx := context.Background()
for _, call := range tt.fields.describeTargetGroupsAsListCalls {
elbv2Client.EXPECT().DescribeTargetGroupsAsList(gomock.Any(), call.req).Return(call.resp, call.err).AnyTimes()
+ elbv2Client.EXPECT().AssumeRole(ctx, gomock.Any(), gomock.Any()).Return(elbv2Client).AnyTimes()
}
m := &targetGroupBindingMutator{
@@ -394,17 +409,20 @@ func Test_targetGroupBindingMutator_obtainSDKTargetTypeFromAWS(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
+ ctx := context.Background()
+
defer ctrl.Finish()
elbv2Client := services.NewMockELBV2(ctrl)
for _, call := range tt.fields.describeTargetGroupsAsListCalls {
elbv2Client.EXPECT().DescribeTargetGroupsAsList(gomock.Any(), call.req).Return(call.resp, call.err)
+ elbv2Client.EXPECT().AssumeRole(ctx, gomock.Any(), gomock.Any()).Return(elbv2Client).AnyTimes()
}
m := &targetGroupBindingMutator{
elbv2Client: elbv2Client,
logger: logr.New(&log.NullLogSink{}),
}
- got, err := m.obtainSDKTargetTypeFromAWS(context.Background(), tt.args.tgARN)
+ got, err := m.obtainSDKTargetTypeFromAWS(context.Background(), makeTargetGroupBinding(tt.args.tgARN))
if tt.wantErr != nil {
assert.EqualError(t, err, tt.wantErr.Error())
} else {
@@ -521,17 +539,20 @@ func Test_targetGroupBindingMutator_getIPAddressTypeFromAWS(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
+ ctx := context.Background()
+
defer ctrl.Finish()
elbv2Client := services.NewMockELBV2(ctrl)
for _, call := range tt.fields.describeTargetGroupsAsListCalls {
elbv2Client.EXPECT().DescribeTargetGroupsAsList(gomock.Any(), call.req).Return(call.resp, call.err)
+ elbv2Client.EXPECT().AssumeRole(ctx, gomock.Any(), gomock.Any()).Return(elbv2Client).AnyTimes()
}
m := &targetGroupBindingMutator{
elbv2Client: elbv2Client,
logger: logr.New(&log.NullLogSink{}),
}
- got, err := m.getTargetGroupIPAddressTypeFromAWS(context.Background(), tt.args.tgARN)
+ got, err := m.getTargetGroupIPAddressTypeFromAWS(context.Background(), makeTargetGroupBinding(tt.args.tgARN))
if tt.wantErr != nil {
assert.EqualError(t, err, tt.wantErr.Error())
} else {
@@ -604,17 +625,20 @@ func Test_targetGroupBindingMutator_obtainSDKVpcIDFromAWS(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
+ ctx := context.Background()
+
defer ctrl.Finish()
elbv2Client := services.NewMockELBV2(ctrl)
for _, call := range tt.fields.describeTargetGroupsAsListCalls {
elbv2Client.EXPECT().DescribeTargetGroupsAsList(gomock.Any(), call.req).Return(call.resp, call.err)
+ elbv2Client.EXPECT().AssumeRole(ctx, gomock.Any(), gomock.Any()).Return(elbv2Client).AnyTimes()
}
m := &targetGroupBindingMutator{
elbv2Client: elbv2Client,
logger: logr.New(&log.NullLogSink{}),
}
- got, err := m.getVpcIDFromAWS(context.Background(), tt.args.tgARN)
+ got, err := m.getVpcIDFromAWS(context.Background(), makeTargetGroupBinding(tt.args.tgARN))
if tt.wantErr != nil {
assert.EqualError(t, err, tt.wantErr.Error())
} else {
diff --git a/webhooks/elbv2/targetgroupbinding_validator.go b/webhooks/elbv2/targetgroupbinding_validator.go
index c4aa4df90..bb6ee770a 100644
--- a/webhooks/elbv2/targetgroupbinding_validator.go
+++ b/webhooks/elbv2/targetgroupbinding_validator.go
@@ -3,10 +3,11 @@ package elbv2
import (
"context"
"fmt"
- elbv2types "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2/types"
"regexp"
"strings"
+ elbv2types "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2/types"
+
awssdk "github.com/aws/aws-sdk-go-v2/aws"
elbv2sdk "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2"
"github.com/go-logr/logr"
@@ -15,6 +16,7 @@ import (
elbv2api "sigs.k8s.io/aws-load-balancer-controller/apis/elbv2/v1beta1"
"sigs.k8s.io/aws-load-balancer-controller/pkg/aws/services"
"sigs.k8s.io/aws-load-balancer-controller/pkg/k8s"
+ "sigs.k8s.io/aws-load-balancer-controller/pkg/targetgroupbinding"
"sigs.k8s.io/aws-load-balancer-controller/pkg/webhook"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
@@ -54,6 +56,7 @@ func (v *targetGroupBindingValidator) Prototype(_ admission.Request) (runtime.Ob
func (v *targetGroupBindingValidator) ValidateCreate(ctx context.Context, obj runtime.Object) error {
tgb := obj.(*elbv2api.TargetGroupBinding)
+ targetgroupbinding.AnnotationsToFields(tgb)
if err := v.checkRequiredFields(ctx, tgb); err != nil {
return err
}
@@ -75,6 +78,7 @@ func (v *targetGroupBindingValidator) ValidateCreate(ctx context.Context, obj ru
func (v *targetGroupBindingValidator) ValidateUpdate(ctx context.Context, obj runtime.Object, oldObj runtime.Object) error {
tgb := obj.(*elbv2api.TargetGroupBinding)
oldTgb := oldObj.(*elbv2api.TargetGroupBinding)
+ targetgroupbinding.AnnotationsToFields(tgb)
if err := v.checkRequiredFields(ctx, tgb); err != nil {
return err
}
@@ -180,7 +184,7 @@ func (v *targetGroupBindingValidator) checkNodeSelector(tgb *elbv2api.TargetGrou
// checkTargetGroupIPAddressType ensures IP address type matches with that on the AWS target group
func (v *targetGroupBindingValidator) checkTargetGroupIPAddressType(ctx context.Context, tgb *elbv2api.TargetGroupBinding) error {
- targetGroupIPAddressType, err := v.getTargetGroupIPAddressTypeFromAWS(ctx, tgb.Spec.TargetGroupARN)
+ targetGroupIPAddressType, err := v.getTargetGroupIPAddressTypeFromAWS(ctx, tgb)
if err != nil {
return errors.Wrap(err, "unable to get target group IP address type")
}
@@ -199,7 +203,7 @@ func (v *targetGroupBindingValidator) checkTargetGroupVpcID(ctx context.Context,
if !vpcIDPatternRegex.MatchString(tgb.Spec.VpcID) {
return errors.Errorf(vpcIDValidationErr, tgb.Spec.VpcID)
}
- vpcID, err := v.getVpcIDFromAWS(ctx, tgb.Spec.TargetGroupARN)
+ vpcID, err := v.getVpcIDFromAWS(ctx, tgb)
if err != nil {
return errors.Wrap(err, "unable to get target group VpcID")
}
@@ -210,8 +214,8 @@ func (v *targetGroupBindingValidator) checkTargetGroupVpcID(ctx context.Context,
}
// getTargetGroupIPAddressTypeFromAWS returns the target group IP address type of AWS target group
-func (v *targetGroupBindingValidator) getTargetGroupIPAddressTypeFromAWS(ctx context.Context, tgARN string) (elbv2api.TargetGroupIPAddressType, error) {
- targetGroup, err := v.getTargetGroupFromAWS(ctx, tgARN)
+func (v *targetGroupBindingValidator) getTargetGroupIPAddressTypeFromAWS(ctx context.Context, tgb *elbv2api.TargetGroupBinding) (elbv2api.TargetGroupIPAddressType, error) {
+ targetGroup, err := v.getTargetGroupFromAWS(ctx, tgb)
if err != nil {
return "", err
}
@@ -228,11 +232,12 @@ func (v *targetGroupBindingValidator) getTargetGroupIPAddressTypeFromAWS(ctx con
}
// getTargetGroupFromAWS returns the AWS target group corresponding to the ARN
-func (v *targetGroupBindingValidator) getTargetGroupFromAWS(ctx context.Context, tgARN string) (*elbv2types.TargetGroup, error) {
+func (v *targetGroupBindingValidator) getTargetGroupFromAWS(ctx context.Context, tgb *elbv2api.TargetGroupBinding) (*elbv2types.TargetGroup, error) {
+ tgARN := tgb.Spec.TargetGroupARN
req := &elbv2sdk.DescribeTargetGroupsInput{
TargetGroupArns: []string{tgARN},
}
- tgList, err := v.elbv2Client.DescribeTargetGroupsAsList(ctx, req)
+ tgList, err := v.elbv2Client.AssumeRole(ctx, tgb.Spec.IamRoleArnToAssume, tgb.Spec.AssumeRoleExternalId).DescribeTargetGroupsAsList(ctx, req)
if err != nil {
return nil, err
}
@@ -242,8 +247,8 @@ func (v *targetGroupBindingValidator) getTargetGroupFromAWS(ctx context.Context,
return &tgList[0], nil
}
-func (v *targetGroupBindingValidator) getVpcIDFromAWS(ctx context.Context, tgARN string) (string, error) {
- targetGroup, err := v.getTargetGroupFromAWS(ctx, tgARN)
+func (v *targetGroupBindingValidator) getVpcIDFromAWS(ctx context.Context, tgb *elbv2api.TargetGroupBinding) (string, error) {
+ targetGroup, err := v.getTargetGroupFromAWS(ctx, tgb)
if err != nil {
return "", err
}
diff --git a/webhooks/elbv2/targetgroupbinding_validator_test.go b/webhooks/elbv2/targetgroupbinding_validator_test.go
index a023e526a..488960494 100644
--- a/webhooks/elbv2/targetgroupbinding_validator_test.go
+++ b/webhooks/elbv2/targetgroupbinding_validator_test.go
@@ -4,12 +4,13 @@ import (
"context"
"crypto/rand"
"fmt"
- elbv2types "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2/types"
- "github.com/google/uuid"
"math/big"
"strings"
"testing"
+ elbv2types "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2/types"
+ "github.com/google/uuid"
+
awssdk "github.com/aws/aws-sdk-go-v2/aws"
elbv2sdk "github.com/aws/aws-sdk-go-v2/service/elasticloadbalancingv2"
"github.com/go-logr/logr"
@@ -322,6 +323,8 @@ func Test_targetGroupBindingValidator_ValidateCreate(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
+ ctx := context.Background()
+
defer ctrl.Finish()
k8sSchema := runtime.NewScheme()
clientgoscheme.AddToScheme(k8sSchema)
@@ -330,6 +333,7 @@ func Test_targetGroupBindingValidator_ValidateCreate(t *testing.T) {
elbv2Client := services.NewMockELBV2(ctrl)
for _, call := range tt.fields.describeTargetGroupsAsListCalls {
elbv2Client.EXPECT().DescribeTargetGroupsAsList(gomock.Any(), call.req).Return(call.resp, call.err)
+ elbv2Client.EXPECT().AssumeRole(ctx, gomock.Any(), gomock.Any()).Return(elbv2Client).AnyTimes()
}
v := &targetGroupBindingValidator{
k8sClient: k8sClient,
@@ -1381,6 +1385,8 @@ func Test_targetGroupBindingValidator_checkTargetGroupVpcID(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ctrl := gomock.NewController(t)
+ ctx := context.Background()
+
defer ctrl.Finish()
k8sSchema := runtime.NewScheme()
clientgoscheme.AddToScheme(k8sSchema)
@@ -1389,6 +1395,7 @@ func Test_targetGroupBindingValidator_checkTargetGroupVpcID(t *testing.T) {
elbv2Client := services.NewMockELBV2(ctrl)
for _, call := range tt.fields.describeTargetGroupsAsListCalls {
elbv2Client.EXPECT().DescribeTargetGroupsAsList(gomock.Any(), call.req).Return(call.resp, call.err)
+ elbv2Client.EXPECT().AssumeRole(ctx, gomock.Any(), gomock.Any()).Return(elbv2Client).AnyTimes()
}
v := &targetGroupBindingValidator{
k8sClient: k8sClient,
|