Skip to content

Commit 4e11d86

Browse files
Elad Ben-Israelmergify[bot]
authored andcommitted
feat(eks): programmatic definition of kubernetes resources (#3510)
* chore: update package-lock.json * feat(eks): define kubernetes resources This change allows defining arbitrary Kubernetes resources within an EKS cluster. * nice! * update readme * Update README.md * feat(events): ability to add cross-account targets (#3323) This adds the capability of adding a target to an event rule that belongs to a different account than the rule itself. Required for things like cross-account CodePipelines with source actions triggered by events. * chore(ci): add mergify config file (#3502) * chore: update jsii to 0.14.3 (#3513) * fix(iam): correctly limit the default PolicyName to 128 characters (#3487) Our logic for trimming the length of the default IAM policy name was not working, as it wasn't updated when logicalId became a Token rather than a literate string, and so it was never actually triggered (it just checked that the display name of the Token was less than 128 characters, which it always is). The fix is to resolve the logical ID Token before applying the trimming logic. Fixes #3402 * v1.3.0 (#3516) See CHANGELOG * fix: typo in restapi.ts (#3530) * feat(ecs): container dependencies (#3032) Add new addContainerDependencies method to allow for container dependencies Fixes #2490 * feat(s3-deployment): CloudFront invalidation (#3213) see #3106 * docs(core): findChild gets direct child only (#3512) * doc(iam): update references to addManagedPolicy (#3511) * fix(sqs): do not emit grants to the AWS-managed encryption key (#3169) Grants on the `alias/aws/sqs` KMS key alias are not necessary since the key will implicitly allow for it's intended usage to be fulfilled (as opposed to how you have to manage grants yourself when using a user-managed key instead). This removes the statement that was generated using an invalid resource entry. Fixes #2794 * fix(lambda): allow ArnPrincipal in grantInvoke (#3501) Fixes #3264 I'm trying to allow a lambda function in another account to be able to invoke my CDK generated lambda function. This works through the CLI like so: aws lambda add-permission --function-name=myFunction --statement-id=ABoldStatement --action=lambda:InvokeFunction --principal=arn:aws:iam::{account_id}:role/a_lambda_execution_role But CDK doesn't seem to allow me to add an ArnPrincipal doing something like this: myFunction.grantInvoke(new iam.ArnPrincipal(props.myARN)) With the error: Invalid principal type for Lambda permission statement: ArnPrincipal. Supported: AccountPrincipal, ServicePrincipal This PR allows ArnPrincipal to be passed to lambda.grantInvoke. There might be some additional validation required on the exact ARN as I believe only some ARNs are supported by lambda add-permission * chore(contrib): remove API stabilization disclaimer * fix(ssm): add GetParameters action to grantRead() (#3546) * misc * rename `KubernetesManifest` to `KubernetesResource` and `addResource` * move AWS Auth APIs to `cluster.awsAuth` and expose `AwsAuth` * remove the yaml library (we can just use a JSON stream) * add support for adding accounts to aws-auth * fix cluster deletion bug * move kubctl app info to constants * addManifest => addResource * update test expectations * add unit test for customresrouce.ref * fix sample link
1 parent 7158e45 commit 4e11d86

24 files changed

+4001
-103
lines changed

packages/@aws-cdk/aws-cloudformation/lib/custom-resource.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,17 @@ export class CustomResource extends Resource {
100100
this.resource.applyRemovalPolicy(props.removalPolicy, { default: RemovalPolicy.DESTROY });
101101
}
102102

103+
/**
104+
* The physical name of this custom resource.
105+
*/
106+
public get ref() {
107+
return this.resource.ref;
108+
}
109+
110+
/**
111+
* An attribute of this custom resource
112+
* @param attributeName the attribute name
113+
*/
103114
public getAtt(attributeName: string) {
104115
return this.resource.getAtt(attributeName);
105116
}

packages/@aws-cdk/aws-cloudformation/test/test.resource.ts

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -196,9 +196,21 @@ export = testCase({
196196
},
197197

198198
},
199+
200+
'.ref returns the intrinsic reference (physical name)'(test: Test) {
201+
// GIVEN
202+
const stack = new cdk.Stack();
203+
const res = new TestCustomResource(stack, 'myResource');
204+
205+
// THEN
206+
test.deepEqual(stack.resolve(res.resource.ref), { Ref: 'myResourceC6A188A9' });
207+
test.done();
208+
}
199209
});
200210

201211
class TestCustomResource extends cdk.Construct {
212+
public readonly resource: CustomResource;
213+
202214
constructor(scope: cdk.Construct, id: string, opts: { removalPolicy?: cdk.RemovalPolicy } = {}) {
203215
super(scope, id);
204216

@@ -210,7 +222,7 @@ class TestCustomResource extends cdk.Construct {
210222
timeout: cdk.Duration.minutes(5),
211223
});
212224

213-
new CustomResource(this, 'Resource', {
225+
this.resource = new CustomResource(this, 'Resource', {
214226
...opts,
215227
provider: CustomResourceProvider.lambda(singletonLambda),
216228
});

packages/@aws-cdk/aws-eks/README.md

Lines changed: 229 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -15,20 +15,176 @@
1515
---
1616
<!--END STABILITY BANNER-->
1717

18-
This construct library allows you to define and create [Amazon Elastic Container Service for Kubernetes (EKS)](https://aws.amazon.com/eks/) clusters programmatically.
18+
This construct library allows you to define [Amazon Elastic Container Service
19+
for Kubernetes (EKS)](https://aws.amazon.com/eks/) clusters programmatically.
1920

20-
### Example
21+
This library also supports programmatically defining Kubernetes resource
22+
manifests within EKS clusters.
2123

22-
The following example shows how to start an EKS cluster and how to
23-
add worker nodes to it:
24+
This example defines an Amazon EKS cluster with a single pod:
2425

25-
[starting a cluster example](test/integ.eks-cluster.lit.ts)
26+
```ts
27+
const cluster = new eks.Cluster(this, 'hello-eks', { vpc });
2628

27-
After deploying the previous CDK app you still need to configure `kubectl`
28-
and manually add the nodes to your cluster, as described [in the EKS user
29-
guide](https://docs.aws.amazon.com/eks/latest/userguide/launch-workers.html).
29+
cluster.addCapacity('default', {
30+
instanceType: new ec2.InstanceType('t2.medium'),
31+
desiredCapacity: 10,
32+
});
3033

31-
### SSH into your nodes
34+
cluster.addResource('mypod', {
35+
apiVersion: 'v1',
36+
kind: 'Pod',
37+
metadata: { name: 'mypod' },
38+
spec: {
39+
containers: [
40+
{
41+
name: 'hello',
42+
image: 'paulbouwer/hello-kubernetes:1.5',
43+
ports: [ { containerPort: 8080 } ]
44+
}
45+
]
46+
}
47+
});
48+
```
49+
50+
**NOTE**: in order to determine the default AMI for for Amazon EKS instances the
51+
`eks.Cluster` resource must be defined within a stack that is configured with an
52+
explicit `env.region`. See [Environments](https://docs.aws.amazon.com/cdk/latest/guide/environments.html)
53+
in the AWS CDK Developer Guide for more details.
54+
55+
Here is a [complete sample](https://github.com/aws/aws-cdk/blob/master/packages/%40aws-cdk/aws-eks/test/integ.eks-kubectl.lit.ts).
56+
57+
### Interacting with Your Cluster
58+
59+
The Amazon EKS construct library allows you to specify an IAM role that will be
60+
granted `system:masters` privileges on your cluster.
61+
62+
Without specifying a `mastersRole`, you will not be able to interact manually
63+
with the cluster.
64+
65+
The following example defines an IAM role that can be assumed by all users
66+
in the account and shows how to use the `mastersRole` property to map this
67+
role to the Kubernetes `system:masters` group:
68+
69+
```ts
70+
// first define the role
71+
const clusterAdmin = new iam.Role(this, 'AdminRole', {
72+
assumedBy: new iam.AccountRootPrincipal()
73+
});
74+
75+
// now define the cluster and map role to "masters" RBAC group
76+
new eks.Cluster(this, 'Cluster', {
77+
vpc: vpc,
78+
mastersRole: clusterAdmin
79+
});
80+
```
81+
82+
Now, given AWS credentials for a user that is trusted by the masters role, you
83+
will be able to interact with your cluster like this:
84+
85+
```console
86+
$ aws eks update-kubeconfig --name CLUSTER-NAME
87+
$ kubectl get all -n kube-system
88+
...
89+
```
90+
91+
For your convenience, an AWS CloudFormation output will automatically be
92+
included in your template and will be printed when running `cdk deploy`.
93+
94+
**NOTE**: if the cluster is configured with `kubectlEnabled: false`, it
95+
will be created with the role/user that created the AWS CloudFormation
96+
stack. See [Kubectl Support](#kubectl-support) for details.
97+
98+
### Defining Kubernetes Resources
99+
100+
The `KubernetesResource` construct or `cluster.addResource` method can be used
101+
to apply Kubernetes resource manifests to this cluster.
102+
103+
The following examples will deploy the [paulbouwer/hello-kubernetes](https://github.com/paulbouwer/hello-kubernetes)
104+
service on the cluster:
105+
106+
```ts
107+
const appLabel = { app: "hello-kubernetes" };
108+
109+
const deployment = {
110+
apiVersion: "apps/v1",
111+
kind: "Deployment",
112+
metadata: { name: "hello-kubernetes" },
113+
spec: {
114+
replicas: 3,
115+
selector: { matchLabels: appLabel },
116+
template: {
117+
metadata: { labels: appLabel },
118+
spec: {
119+
containers: [
120+
{
121+
name: "hello-kubernetes",
122+
image: "paulbouwer/hello-kubernetes:1.5",
123+
ports: [ { containerPort: 8080 } ]
124+
}
125+
]
126+
}
127+
}
128+
}
129+
};
130+
131+
const service = {
132+
apiVersion: "v1",
133+
kind: "Service",
134+
metadata: { name: "hello-kubernetes" },
135+
spec: {
136+
type: "LoadBalancer",
137+
ports: [ { port: 80, targetPort: 8080 } ],
138+
selector: appLabel
139+
}
140+
};
141+
142+
// option 1: use a construct
143+
new KubernetesResource(this, 'hello-kub', {
144+
cluster,
145+
manifest: [ deployment, service ]
146+
});
147+
148+
// or, option2: use `addResource`
149+
cluster.addResource('hello-kub', service, deployment);
150+
```
151+
152+
Since Kubernetes resources are implemented as CloudFormation resources in the
153+
CDK. This means that if the resource is deleted from your code (or the stack is
154+
deleted), the next `cdk deploy` will issue a `kubectl delete` command and the
155+
Kubernetes resources will be deleted.
156+
157+
### AWS IAM Mapping
158+
159+
As described in the [Amazon EKS User Guide](https://docs.aws.amazon.com/en_us/eks/latest/userguide/add-user-role.html),
160+
you can map AWS IAM users and roles to [Kubernetes Role-based access control (RBAC)](https://kubernetes.io/docs/reference/access-authn-authz/rbac).
161+
162+
The Amazon EKS construct manages the **aws-auth ConfigMap** Kubernetes resource
163+
on your behalf and exposes an API through the `cluster.awsAuth` for mapping
164+
users, roles and accounts.
165+
166+
Furthermore, when auto-scaling capacity is added to the cluster (through
167+
`cluster.addCapacity` or `cluster.addAutoScalingGroup`), the IAM instance role
168+
of the auto-scaling group will be automatically mapped to RBAC so nodes can
169+
connect to the cluster. No manual mapping is required any longer.
170+
171+
> NOTE: `cluster.awsAuth` will throw an error if your cluster is created with `kubectlEnabled: false`.
172+
173+
For example, let's say you want to grant an IAM user administrative privileges
174+
on your cluster:
175+
176+
```ts
177+
const adminUser = new iam.User(this, 'Admin');
178+
cluster.awsAuth.addUserMapping(adminUser, { groups: [ 'system:masters' ]});
179+
```
180+
181+
A convenience method for mapping a role to the `system:masters` group is also available:
182+
183+
```ts
184+
cluster.awsAuth.addMastersRole(role)
185+
```
186+
187+
### Node ssh Access
32188

33189
If you want to be able to SSH into your worker nodes, you must already
34190
have an SSH key in the region you're connecting to and pass it, and you must
@@ -41,7 +197,69 @@ If you want to SSH into nodes in a private subnet, you should set up a
41197
bastion host in a public subnet. That setup is recommended, but is
42198
unfortunately beyond the scope of this documentation.
43199

200+
### kubectl Support
201+
202+
When you create an Amazon EKS cluster, the IAM entity user or role, such as a
203+
[federated user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers.html)
204+
that creates the cluster, is automatically granted `system:masters` permissions
205+
in the cluster's RBAC configuration.
206+
207+
In order to allow programmatically defining **Kubernetes resources** in your AWS
208+
CDK app and provisioning them through AWS CloudFormation, we will need to assume
209+
this "masters" role every time we want to issue `kubectl` operations against your
210+
cluster.
211+
212+
At the moment, the [AWS::EKS::Cluster](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-eks-cluster.html)
213+
AWS CloudFormation resource does not support this behavior, so in order to
214+
support "programmatic kubectl", such as applying manifests
215+
and mapping IAM roles from within your CDK application, the Amazon EKS
216+
construct library uses a custom resource for provisioning the cluster.
217+
This custom resource is executed with an IAM role that we can then use
218+
to issue `kubectl` commands.
219+
220+
The default behavior of this library is to use this custom resource in order
221+
to retain programmatic control over the cluster. In other words: to allow
222+
you to define Kubernetes resources in your CDK code instead of having to
223+
manage your Kubernetes applications through a separate system.
224+
225+
One of the implications of this design is that, by default, the user who
226+
provisioned the AWS CloudFormation stack (executed `cdk deploy`) will
227+
not have administrative privileges on the EKS cluster.
228+
229+
1. Additional resources will be synthesized into your template (the AWS Lambda
230+
function, the role and policy).
231+
2. As described in [Interacting with Your Cluster](#interacting-with-your-cluster),
232+
if you wish to be able to manually interact with your cluster, you will need
233+
to map an IAM role or user to the `system:masters` group. This can be either
234+
done by specifying a `mastersRole` when the cluster is defined, calling
235+
`cluster.addMastersRole` or explicitly mapping an IAM role or IAM user to the
236+
relevant Kubernetes RBAC groups using `cluster.addRoleMapping` and/or
237+
`cluster.addUserMapping`.
238+
239+
If you wish to disable the programmatic kubectl behavior and use the standard
240+
AWS::EKS::Cluster resource, you can specify `kubectlEnabled: false` when you define
241+
the cluster:
242+
243+
```ts
244+
new eks.Cluster(this, 'cluster', {
245+
vpc: vpc,
246+
kubectlEnabled: false
247+
});
248+
```
249+
250+
**Take care**: a change in this property will cause the cluster to be destroyed
251+
and a new cluster to be created.
252+
253+
When kubectl is disabled, you should be aware of the following:
254+
255+
1. When you log-in to your cluster, you don't need to specify `--role-arn` as long as you are using the same user that created
256+
the cluster.
257+
2. As described in the Amazon EKS User Guide, you will need to manually
258+
edit the [aws-auth ConfigMap](https://docs.aws.amazon.com/eks/latest/userguide/add-user-role.html) when you add capacity in order to map
259+
the IAM instance role to RBAC to allow nodes to join the cluster.
260+
3. Any `eks.Cluster` APIs that depend on programmatic kubectl support will fail with an error: `cluster.addResource`, `cluster.awsAuth`, `props.mastersRole`.
261+
44262
### Roadmap
45263

46-
- [ ] Add ability to start tasks on clusters using CDK (similar to ECS's "`Service`" concept).
47-
- [ ] Describe how to set up AutoScaling (how to combine EC2 and Kubernetes scaling)
264+
- [ ] AutoScaling (combine EC2 and Kubernetes scaling)
265+
- [ ] Spot fleet support
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
2+
export interface Mapping {
3+
/**
4+
* The user name within Kubernetes to map to the IAM role.
5+
*
6+
* @default - By default, the user name is the ARN of the IAM role.
7+
*/
8+
readonly username?: string;
9+
10+
/**
11+
* A list of groups within Kubernetes to which the role is mapped.
12+
*
13+
* @see https://kubernetes.io/docs/reference/access-authn-authz/rbac/#default-roles-and-role-bindings
14+
*/
15+
readonly groups: string[];
16+
}

0 commit comments

Comments
 (0)