├── .github ├── actions │ └── terratest │ │ ├── Dockerfile │ │ ├── action.yml │ │ └── entrypoint.sh ├── release.yml └── workflows │ ├── ci.yml │ └── tfsec_pr_commenter.yml ├── .gitignore ├── .terraform-version ├── .trivyignore ├── CODEOWNERS ├── LICENSE ├── README.md ├── RELEASING.md ├── UPGRADING.md ├── addons.tf ├── aws_ebs_csi_driver_iam.tf ├── cluster_iam.tf ├── data.tf ├── docs ├── roll_nodes.md └── service_out_asg_node_group.md ├── examples ├── cluster │ ├── .terraform.lock.hcl │ ├── environment.tf │ ├── environment │ │ ├── .terraform-version │ │ ├── .terraform.lock.hcl │ │ ├── README.md │ │ ├── backend.tf │ │ ├── main.tf │ │ ├── outputs.tf │ │ └── variables.tf │ ├── main.tf │ ├── outputs.tf │ ├── test_iam_role.tf │ └── variables.tf └── iam_permissions │ └── main.tf ├── fargate.tf ├── hack ├── assume_role.sh ├── cleanup.sh ├── kubeconfig.sh ├── test.sh ├── update_1_15.sh └── versions ├── main.tf ├── modules ├── karpenter │ ├── README.md │ ├── controller_iam.tf │ ├── data.tf │ ├── fargate.tf │ ├── interruption_queue.tf │ ├── node_iam.tf │ ├── outputs.tf │ ├── variables.tf │ └── versions.tf └── vpc │ ├── README.md │ ├── outputs.tf │ ├── providers.tf │ ├── subnets.tf │ ├── variables.tf │ └── vpc.tf ├── outputs.tf ├── required_providers.tf ├── scripts └── create_github_releases │ ├── README.md │ ├── go.mod │ ├── go.sum │ ├── main.go │ └── main_test.go ├── security_groups.tf ├── test ├── cluster_test.go ├── common.go ├── go.mod └── go.sum ├── variables.tf └── versions.tf /.github/actions/terratest/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM golang:1.24.1-alpine3.20 2 | 3 | WORKDIR / 4 | 5 | ARG TERRAFORM_VERSION=1.11.3 6 | ARG KUBECTL_VERSION=1.32.3 7 | ARG HELM_VERSION=3.17.0 8 | 9 | RUN apk add --no-cache \ 10 | bash \ 11 | gcc \ 12 | musl-dev \ 13 | curl \ 14 | git \ 15 | jq \ 16 | perl-utils \ 17 | aws-cli && \ 18 | git clone https://github.com/tfutils/tfenv.git ~/.tfenv && \ 19 | echo 'export PATH="$HOME/.tfenv/bin:$PATH"' >> ~/.bash_profile && ln -s ~/.tfenv/bin/* /usr/local/bin && \ 20 | tfenv install $TERRAFORM_VERSION && \ 21 | echo $TERRAFORM_VERSION > ~/.tfenv/version && \ 22 | curl -sfSLO https://dl.k8s.io/release/v${KUBECTL_VERSION}/bin/linux/amd64/kubectl && \ 23 | chmod u+x kubectl && \ 24 | mv ./kubectl /usr/local/bin/kubectl && \ 25 | kubectl version --client=true && \ 26 | curl -sfSLO https://get.helm.sh/helm-v${HELM_VERSION}-linux-amd64.tar.gz && \ 27 | tar -zxvf helm-v${HELM_VERSION}-linux-amd64.tar.gz && \ 28 | mv linux-amd64/helm /usr/local/bin/helm && \ 29 | rm -rf linux-amd64 helm-v${HELM_VERSION}-linux-amd64.tar.gz && \ 30 | helm version 31 | 32 | 33 | COPY *.sh ./ 34 | ENTRYPOINT ["/entrypoint.sh"] 35 | -------------------------------------------------------------------------------- /.github/actions/terratest/action.yml: -------------------------------------------------------------------------------- 1 | name: 'Terratest' 2 | description: 'Run terratest integration tests' 3 | runs: 4 | using: 'docker' 5 | image: 'Dockerfile' 6 | -------------------------------------------------------------------------------- /.github/actions/terratest/entrypoint.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -euo pipefail 4 | 5 | # If the terraform version is specified install the correct one 6 | tfenv install || true 7 | 8 | cd test 9 | go test -v -timeout 90m "$@" | grep -v "constructing many client instances from the same exec auth config" 10 | -------------------------------------------------------------------------------- /.github/release.yml: -------------------------------------------------------------------------------- 1 | # release.yml 2 | 3 | changelog: 4 | exclude: 5 | labels: 6 | - ignore-for-release 7 | authors: 8 | - octocat 9 | categories: 10 | - title: Enhancements 🎉 11 | labels: 12 | - enhancement 13 | - title: Breaking Changes 💥 14 | labels: 15 | - breaking change 16 | - title: Bug Fixes 🚧 17 | labels: 18 | - bug 19 | - title: Other Changes 20 | labels: 21 | - "*" 22 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | permissions: 2 | id-token: write # This is required for requesting the JWT 3 | contents: read # This is required for actions/checkout 4 | on: 5 | pull_request: 6 | paths-ignore: 7 | - '*.md' 8 | - 'docs/**' 9 | 10 | push: 11 | paths-ignore: 12 | - '*.md' 13 | - 'docs/**' 14 | branches: 15 | - main 16 | - release-* 17 | schedule: 18 | - cron: "0 11 * * 1-5" 19 | jobs: 20 | lint: 21 | name: Linting 22 | if: "!contains(github.event.head_commit.message, '[skip ci]')" 23 | runs-on: ubuntu-latest 24 | steps: 25 | - uses: actions/checkout@v4 26 | - uses: hashicorp/setup-terraform@v3 27 | with: 28 | terraform_version: 1.8.1 29 | - name: 'Terraform Format' 30 | run: terraform fmt -check -recursive 31 | - name: 'Terraform Init cluster' 32 | run: terraform init 33 | working-directory: 'examples/cluster' 34 | - name: Configure AWS Credentials 35 | uses: aws-actions/configure-aws-credentials@v4 36 | with: 37 | aws-region: us-east-1 38 | role-to-assume: ${{ secrets.AWS_ROLE_TO_ASSUME }} 39 | role-session-name: github-actions-ci 40 | - name: 'Terraform Validate cluster' 41 | run: terraform validate 42 | working-directory: 'examples/cluster' 43 | cluster-test: 44 | name: Test cluster module 45 | if: "!contains(github.event.head_commit.message, '[skip ci]')" 46 | runs-on: ubuntu-latest 47 | steps: 48 | - name: 'Checkout' 49 | uses: actions/checkout@main 50 | - name: Configure AWS Credentials 51 | uses: aws-actions/configure-aws-credentials@v4 52 | with: 53 | aws-region: us-east-1 54 | role-to-assume: ${{ secrets.AWS_ROLE_TO_ASSUME }} 55 | role-session-name: github-actions-ci 56 | - name: 'Terratest' 57 | uses: ./.github/actions/terratest 58 | with: 59 | args: "-run TestTerraformAwsEksCluster" 60 | -------------------------------------------------------------------------------- /.github/workflows/tfsec_pr_commenter.yml: -------------------------------------------------------------------------------- 1 | name: trivy-pr-commenter 2 | on: 3 | pull_request: 4 | jobs: 5 | trivy: 6 | name: trivy PR commenter 7 | runs-on: ubuntu-latest 8 | steps: 9 | - name: Clone repo 10 | uses: actions/checkout@v4 11 | - name: trivy 12 | uses: reviewdog/action-trivy@v1.13.10 13 | with: 14 | github_token: ${{ secrets.GITHUB_TOKEN }} 15 | trivy_command: config 16 | trivy_target: . 17 | level: info 18 | reporter: github-pr-review 19 | filter_mode: nofilter 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | **/.terraform/** 2 | **/terraform.tfstate** 3 | **/.test-data/** 4 | !.terraform-version 5 | -------------------------------------------------------------------------------- /.terraform-version: -------------------------------------------------------------------------------- 1 | 1.11.3 2 | -------------------------------------------------------------------------------- /.trivyignore: -------------------------------------------------------------------------------- 1 | # Github actions must run as root user https://docs.github.com/en/actions/sharing-automations/creating-actions/dockerfile-support-for-github-actions#user 2 | AVD-DS-0002 3 | 4 | # Healthcheck is not relevent for github action 5 | AVD-DS-0026 6 | -------------------------------------------------------------------------------- /CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @cookpad/platform-task-force 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Terraform EKS Module 2 | 3 | ![.github/workflows/ci.yml](https://github.com/cookpad/terraform-aws-eks/workflows/.github/workflows/ci.yml/badge.svg) 4 | 5 | This repo contains a set of Terraform modules that can be used to provision 6 | an Elastic Kubernetes (EKS) cluster on AWS. 7 | 8 | This module provides a way to provision an EKS cluster based on the current 9 | best practices employed at Cookpad. 10 | 11 | ## Using this module 12 | 13 | To provision an EKS cluster you need (as a minimum) to specify 14 | a name, and the details of the VPC network you will create it in. 15 | 16 | ```hcl 17 | module "cluster" { 18 | source = "cookpad/eks/aws" 19 | version = "~> 1.32" 20 | 21 | name = "hal-9000" 22 | 23 | vpc_config = { 24 | vpc_id = "vpc-345abc" 25 | 26 | public_subnet_ids = { 27 | use-east-1a = subnet-000af1234 28 | use-east-1b = subnet-123ae3456 29 | use-east-1c = subnet-456ab6789 30 | } 31 | 32 | private_subnet_ids = { 33 | use-east-1a = subnet-123af1234 34 | use-east-1b = subnet-456bc3456 35 | use-east-1c = subnet-789fe6789 36 | } 37 | } 38 | } 39 | 40 | provider "kubernetes" { 41 | host = module.cluster.config.endpoint 42 | cluster_ca_certificate = base64decode(module.cluster.config.ca_data) 43 | 44 | exec { 45 | api_version = "client.authentication.k8s.io/v1beta1" 46 | command = "aws" 47 | args = ["eks", "get-token", "--cluster-name", module.cluster.config.name] 48 | } 49 | } 50 | ``` 51 | 52 | There are many options that can be set to configure your cluster. 53 | Check the [input documentation](https://registry.terraform.io/modules/cookpad/eks/aws/latest?tab=inputs) for more information. 54 | 55 | 56 | ## Networking 57 | 58 | If you only have simple networking requirements you can use the 59 | submodule `cookpad/eks/aws/modules/vpc` to create a VPC, it's output 60 | variable `config` can be used to configure the `vpc_config` variable. 61 | 62 | Check the [VPC module documentation](https://registry.terraform.io/modules/cookpad/eks/aws/latest/submodules/vpc) for more extensive information. 63 | 64 | ## Karpenter 65 | 66 | We use karpenter to provision the nodes that run the workloads in 67 | our clusters. You can use the submodule `cookpad/eks/aws/modules/vpc` 68 | to provision the resources required to use karpenter, and a fargate 69 | profile to run the karpenter pods. 70 | 71 | Check the [Karpenter module documentation](https://registry.terraform.io/modules/cookpad/eks/aws/latest/submodules/karpenter) for more information. 72 | 73 | ## Requirements 74 | 75 | In order for this module to communicate with kubernetes correctly this module 76 | requires the `aws` cli to be installed and on your path. 77 | 78 | You will need to initialise the kuberntes provider as shown in the 79 | example. 80 | 81 | ## Multi User Environments 82 | 83 | In an environment where multiple IAM users are used to running `terraform run` 84 | and `terraform apply` it is recommended to use the assume role functionality 85 | to assume a common IAM role in the aws provider definition. 86 | 87 | ```hcl 88 | provider "aws" { 89 | region = "us-east-1" 90 | assume_role { 91 | role_arn = "arn:aws:iam:::role/Terraform" 92 | } 93 | } 94 | ``` 95 | 96 | [see an example role here](https://github.com/cookpad/terraform-aws-eks/blob/main/examples/iam_permissions/main.tf) 97 | 98 | 99 | Alternatively you should ensure that all users who need to run terraform 100 | are listed in the `aws_auth_user_map` variable of the cluster module. 101 | -------------------------------------------------------------------------------- /RELEASING.md: -------------------------------------------------------------------------------- 1 | # Releasing 2 | 3 | This file contains notes explaining release and versioning procedures. 4 | 5 | # Versioning 6 | 7 | This module is versioned with a 3 part version number: 8 | 9 | The Major and Minor parts of the version number follow the Kubernetes Major 10 | and Minor version numbers. 11 | 12 | The patch version version tracks patch releases of this module (not Kubernetes), 13 | EKS only allows users to specify Major and Minor K8s versions. 14 | 15 | # Compatibility 16 | 17 | Upgrading the patch version of this module should not: 18 | 19 | * Cause major downtime 20 | * Require any additional manual steps 21 | 22 | The exception to this is where either of the above are required to fix a 23 | security issue (in this case the release notes will document this). 24 | 25 | Upgrading the Major or minor version of this module: 26 | 27 | * Upgrades the Kubernetes version 28 | * Will require multiple terraform apply steps 29 | * May require additional manual steps 30 | * May cause short downtime of some components (where unavoidable) 31 | 32 | The release notes will document this. 33 | 34 | Pre release versions may be tagged. There are no guarantees attached to these 35 | as they are intended for testing purposes only. They may well cause downtime 36 | or otherwise break a cluster. 37 | 38 | # Branching 39 | 40 | `main` is the main development branch for this module. Changes to the module 41 | and updates should be merged here via pull request. `main` should be maintained 42 | with the most up-to date working configuration. 43 | 44 | Once a particular version is ready for pre-production testing a branch named 45 | `release--` is created to maintain stable releases for that version. 46 | 47 | Pre-Release versions, and release versions (once we are satisfied) are tagged 48 | from these branches. 49 | 50 | We expect to cherry-pick or backport essential changes to release branches. 51 | 52 | ## Release Cadence and Support 53 | 54 | AWS release a new minor version of EKS approximately once per quarter (see the [EKS Kubernetes release calendar](https://docs.aws.amazon.com/eks/latest/userguide/kubernetes-versions.html#kubernetes-release-calendar)). We aim to release a new stable minor version of `terraform-aws-eks` within one month of the upstream EKS release. 55 | 56 | We will continue to support the latest 3 minor EKS versions. Security fixes will be back-ported and released on as a new patch version. Other major bugs may be back-ported based on user demand. 57 | 58 | # Release Procedure 59 | 60 | We use GitHub's [automated release note](https://docs.github.com/en/repositories/releasing-projects-on-github/automatically-generated-release-notes) feature to generate release notes for this module. Please follow the steps below to enforce our release policies described in this page. 61 | 62 | * Review the pull requests merged since the last release, and ensure all required labels have been applied. 63 | * Run `cd scripts/create_github_releases && go run main.go` and follow instructions to open a new GitHub Release page. 64 | * Check the version has been published at https://registry.terraform.io/modules/cookpad/eks/aws 65 | -------------------------------------------------------------------------------- /UPGRADING.md: -------------------------------------------------------------------------------- 1 | # Upgrade Notes 2 | 3 | ## All Upgrades 4 | 5 | * Check the notes for the Kubernetes version you are upgrading to at https://docs.aws.amazon.com/eks/latest/userguide/kubernetes-versions.html 6 | * After upgrading the terraform module, remember to follow the [roll nodes](docs/roll_nodes.md) procedure to roll out upgraded nodes to your cluster. 7 | * If providing custom `configuration_values` for any EKS addons, check for compatibility with the upgraded EKS addon version, using `aws eks describe-addon-configuration`. You can find the EKS addon versions in [addons.tf](modules/cluster/addons.tf) 8 | 9 | ## 1.24 -> 1.25 10 | * Check the [API deprecation guide](https://kubernetes.io/docs/reference/using-api/deprecation-guide/#v1-25) 11 | * If you are using aws-load-balancer-controller, check you are on version 2.4.7+ 12 | * Check that you are not using Pod Security Policies (PSPs) 13 | * Run `kubectl get psp --all-namespaces` to check - `eks.privileged` is OK as it will be automaticly migrated during the upgrade! 14 | * Check [The AWS blogpost about this version](https://aws.amazon.com/blogs/containers/amazon-eks-now-supports-kubernetes-version-1-25/) 15 | * IAM module was removed 16 | * By default the module now makes IAM roles for each cluster rather than using shared roles 17 | * ⚠️ if you are upgrading an existing cluster be sure to set `cluster_role_arn` to it's previous default value, i.e. `arn:aws:iam:::role/eksServiceRole` This value cannot be changed, so terraform will attempt to delete and recreate the cluster. ⚠️ 18 | * Cluster module is no longer a submodule 19 | * change `source` from `cookpad/eks/aws//modules/cluster` to `cookpad/eks/aws` 20 | * `node_group` submodule was removed 21 | * We recommend to use karpenter to provision nodes for eks clusters 22 | * A new submodule [`cookpad/eks/aws//modules/karpenter`](https://github.com/cookpad/terraform-aws-eks/tree/release-1-25/modules/karpenter) was added that provisions the resources required to use karpenter. 23 | * Module now uses terraform kubernetes provider 24 | * Provider config should be added to your project - [check the example in the README](https://github.com/cookpad/terraform-aws-eks/tree/release-1-25#using-this-module) 25 | * Take special care to correctly configure the provider if you are managing more than one EKS cluster in the same terraform project. 26 | * If upgrading an existing cluster import existing `aws-auth` configmap from your cluster - e.g. `terraform import module.cluster.kubernetes_config_map.aws_auth kube-system/aws-auth` 27 | * 1.25+ uses fargate to run cluster critical pods from `kube-system`, `flux-system` and optionaly `fargate` 28 | * It is recomended to first upgrade the module to 1.24.3+ and add the karpenter sub-module before upgrading to 1.25 - so that the fargate profiles are created 29 | before the ASG that managed these "critical" addons is removed. 30 | * We removed the `hack/roll_nodes.sh` script from version 1.25 31 | * To replace fargate nodes with new version it is recomended to: 32 | * kubectl get deployment in each of the enabled namespaces e.g. kube-system, flux-system, karpenter 33 | * kubectl rollout restart deployment/ for each deployment 34 | * To have karpenter rollout the new version to the nodes that it manages: 35 | * Consider using the [drift](https://karpenter.sh/preview/concepts/disruption/#drift) feature 36 | * `kubectl edit configmap -n karpenter karpenter-global-settings` 37 | * set `featureGates.driftEnabled` to true 38 | * `kubectl rollout restart deploy karpenter -n karpenter` to restart karpenter with the drift feature enabled 39 | * 📝 this feature is currently in alpha, so consider if you want to leave it perminantly enabled 40 | 41 | ## 1.23 -> 1.24 42 | * Dockershim support is removed. Make sure none of your workload requires Docker functions specifically. Read more [here](https://docs.aws.amazon.com/eks/latest/userguide/dockershim-deprecation.html). 43 | * IPv6 is enabled for pods by default. Check your multi-container pods, make sure they can bind to all loopback interfaces IP address (IPv6 is the default for communication). 44 | 45 | ## 1.22 -> 1.23 46 | * [324](https://github.com/cookpad/terraform-aws-eks/pull/324) EBS CSI driver is now non-optional. Check your cluster module's `aws_ebs_csi_driver` variable. Refer to [this AWS FAQ](https://docs.aws.amazon.com/eks/latest/userguide/ebs-csi-migration-faq.html). 47 | 48 | ## 1.21 -> 1.22 49 | * Removed yaml k8s addons: nvidia, aws-node-termination-handler, metrics-server, pod_nanny (PR) only remains cluster-autoscaler, The idea is that terraform doesn't manage anymore k8s components in future releases, just the AWS Addons. So Flux or any GitOps system should manage k8s components. 50 | 51 | ## 1.20 -> 1.21 52 | * [261](https://github.com/cookpad/terraform-aws-eks/issues/267/) 💥 Breaking Change. Modules now require terraform version >=1.0. 53 | 54 | ## 1.19 -> 1.20 55 | * [247](https://github.com/cookpad/terraform-aws-eks/pull/247) 💥 Breaking Change. The `k8s_version` variable has been removed. Use the correct version of the module for the k8s version you want to use. 56 | * [156](https://github.com/cookpad/terraform-aws-eks/issues/156) 💥 Breaking Change. The root module has been removed. Please refactor using the README as a guide. 57 | * [276](https://github.com/cookpad/terraform-aws-eks/pull/276) 💥 Breaking Change. The `dns_cluster_ip` variable has been removed from the `asg_node_group` module. 58 | * [240](https://github.com/cookpad/terraform-aws-eks/pull/240/) 💥 Breaking Change. Public access to EKS Clusters is disabled by default. 59 | * [261](https://github.com/cookpad/terraform-aws-eks/pull/261/) 💥 Breaking Change. Node module requires terraform version >=0.14, upgrade your terraform version if using <= 0.13. 60 | 61 | ## 1.18 -> 1.19 62 | 63 | * [#204](https://github.com/cookpad/terraform-aws-eks/pull/204) EKS no longer adds `kubernetes.io/cluster/` to subnets. They will not be removed on upgrading to 1.19, but we recommend to codify the tags yourself for completeness if you are not using the vpc module and you want to keep using auto-discovery with eks-load-balancer-controller. 64 | * [#203](https://github.com/cookpad/terraform-aws-eks/pull/203) removes `failure-domain.beta.kubernetes.io/zone` label which is deprecated in favour of `topology.kubernetes.io/zone`. Use the new label in any affinity specs. 65 | * [#195](https://github.com/cookpad/terraform-aws-eks/pull/295) / [#225](https://github.com/cookpad/terraform-aws-eks/pull/225) removes the `aws-alb-ingress-controller` addon. The upgrade will not delete the addon from the cluster but takes it out of control of the module, so users should manage the package themselves through another mechanism. 66 | 67 | ## 1.18.3+ 68 | 69 | This release updated ebs-csi-driver, 70 | The upgrade renamed the ebs-csi-controller-pod-disruption-budget resource. 71 | 72 | Due to the way that we apply manifests this will result in a duplicated pod disruption 73 | budget, that can cause issues when trying to drain nodes. 74 | 75 | Ensure you run `kubectl -n kube-system delete pdb ebs-csi-controller-pod-disruption-budget` 76 | after upgrading to this version of the module to avoid this issue. 77 | 78 | 79 | ## 1.17 -> 1.18 80 | 81 | * [#170](https://github.com/cookpad/terraform-aws-eks/pull/170) renames the cluster-module and root module outputs 82 | `odic_config` -> `oidc_config`. If you are using this output you will need to update it. 83 | 84 | ## 1.15 -> 1.16 85 | 86 | Some deprecated API versions are removed by this version of Kubernetes. 87 | 88 | Make sure you follow the instructions at https://docs.aws.amazon.com/eks/latest/userguide/update-cluster.html#1-16-prequisites 89 | before upgrading your cluster. 90 | 91 | --- 92 | 93 | Metrics Server and Prometheus Node Exporter will not be managed by this module 94 | by default. 95 | 96 | To retain the previous behaviour set: 97 | 98 | ``` 99 | metrics_server = true 100 | prometheus_node_exporter = true 101 | ``` 102 | 103 | 📝 existing resources won't be removed by this update, so you will need to remove 104 | them manually if they are no longer required. This change means that they will not 105 | be created in a new cluster, or receive updates from this module! 106 | 107 | ## 1.14 -> 1.15 108 | 109 | ### Cluster Security Group 110 | 111 | Existing clusters will be using separately managed security groups for cluster 112 | and nodes. To continue to use these (and avoid recreating the cluster) set 113 | `legacy_security_groups = true` on the cluster module. 114 | 115 | Update terraform state: 116 | 117 | ```shell 118 | wget https://raw.githubusercontent.com/cookpad/terraform-aws-eks/main/hack/update_1_15.sh 119 | chmod +x update_1_15.sh 120 | ./update_1_15.sh example-cluster-module 121 | ``` 122 | -------------------------------------------------------------------------------- /addons.tf: -------------------------------------------------------------------------------- 1 | resource "aws_eks_addon" "vpc-cni" { 2 | cluster_name = aws_eks_cluster.control_plane.name 3 | addon_name = "vpc-cni" 4 | addon_version = local.versions.vpc_cni 5 | resolve_conflicts_on_create = "OVERWRITE" 6 | resolve_conflicts_on_update = "OVERWRITE" 7 | configuration_values = var.vpc_cni_configuration_values 8 | } 9 | 10 | resource "aws_eks_addon" "kube-proxy" { 11 | cluster_name = aws_eks_cluster.control_plane.name 12 | addon_name = "kube-proxy" 13 | addon_version = local.versions.kube_proxy 14 | resolve_conflicts_on_create = "OVERWRITE" 15 | resolve_conflicts_on_update = "OVERWRITE" 16 | configuration_values = var.kube_proxy_configuration_values 17 | } 18 | 19 | resource "aws_eks_addon" "coredns" { 20 | cluster_name = aws_eks_cluster.control_plane.name 21 | addon_name = "coredns" 22 | addon_version = local.versions.coredns 23 | resolve_conflicts_on_create = "OVERWRITE" 24 | resolve_conflicts_on_update = "OVERWRITE" 25 | configuration_values = var.coredns_configuration_values 26 | depends_on = [aws_eks_fargate_profile.critical_pods] 27 | } 28 | 29 | resource "aws_eks_addon" "ebs-csi" { 30 | cluster_name = aws_eks_cluster.control_plane.name 31 | addon_name = "aws-ebs-csi-driver" 32 | addon_version = local.versions.aws_ebs_csi_driver 33 | service_account_role_arn = aws_iam_role.aws_ebs_csi_driver.arn 34 | resolve_conflicts_on_create = "OVERWRITE" 35 | resolve_conflicts_on_update = "OVERWRITE" 36 | configuration_values = var.ebs_csi_configuration_values 37 | depends_on = [aws_eks_fargate_profile.critical_pods] 38 | } 39 | -------------------------------------------------------------------------------- /aws_ebs_csi_driver_iam.tf: -------------------------------------------------------------------------------- 1 | resource "aws_iam_role" "aws_ebs_csi_driver" { 2 | name = "${var.iam_role_name_prefix}EksEBSCSIDriver-${var.name}" 3 | assume_role_policy = data.aws_iam_policy_document.aws_ebs_csi_driver_assume_role_policy.json 4 | description = "EKS CSI driver role for ${var.name} cluster" 5 | } 6 | 7 | data "aws_iam_policy_document" "aws_ebs_csi_driver_assume_role_policy" { 8 | statement { 9 | actions = ["sts:AssumeRoleWithWebIdentity"] 10 | effect = "Allow" 11 | 12 | condition { 13 | test = "StringEquals" 14 | variable = "${replace(aws_iam_openid_connect_provider.cluster_oidc.url, "https://", "")}:sub" 15 | values = ["system:serviceaccount:kube-system:ebs-csi-controller-sa", "system:serviceaccount:kube-system:ebs-snapshot-controller"] 16 | } 17 | 18 | condition { 19 | test = "StringEquals" 20 | variable = "${replace(aws_iam_openid_connect_provider.cluster_oidc.url, "https://", "")}:aud" 21 | values = ["sts.amazonaws.com"] 22 | } 23 | 24 | principals { 25 | identifiers = [aws_iam_openid_connect_provider.cluster_oidc.arn] 26 | type = "Federated" 27 | } 28 | } 29 | } 30 | 31 | resource "aws_iam_role_policy_attachment" "aws_ebs_csi_driver" { 32 | role = aws_iam_role.aws_ebs_csi_driver.id 33 | policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonEBSCSIDriverPolicy" 34 | } 35 | -------------------------------------------------------------------------------- /cluster_iam.tf: -------------------------------------------------------------------------------- 1 | locals { 2 | eks_cluster_role_arn = length(var.cluster_role_arn) == 0 ? aws_iam_role.eks_cluster_role[0].arn : var.cluster_role_arn 3 | } 4 | 5 | resource "aws_iam_role" "eks_cluster_role" { 6 | count = length(var.cluster_role_arn) == 0 ? 1 : 0 7 | name = "${var.iam_role_name_prefix}EksCluster-${var.name}" 8 | assume_role_policy = data.aws_iam_policy_document.eks_assume_role_policy.json 9 | } 10 | 11 | resource "aws_iam_role_policy" "deny_log_group_creation" { 12 | count = length(var.cluster_role_arn) == 0 ? 1 : 0 13 | name = "DenyLogGroupCreation" 14 | role = aws_iam_role.eks_cluster_role[0].id 15 | 16 | # Resources running on the cluster are still generating logs when destroying the module resources 17 | # which results in the log group being re-created even after Terraform destroys it. Removing the 18 | # ability for the cluster role to create the log group prevents this log group from being re-created 19 | # outside of Terraform due to services still generating logs during destroy process 20 | policy = jsonencode({ 21 | Version = "2012-10-17" 22 | Statement = [ 23 | { 24 | Action = ["logs:CreateLogGroup"] 25 | Effect = "Deny" 26 | Resource = "*" 27 | }, 28 | ] 29 | }) 30 | } 31 | 32 | data "aws_iam_policy_document" "eks_assume_role_policy" { 33 | statement { 34 | principals { 35 | type = "Service" 36 | identifiers = ["eks.amazonaws.com"] 37 | } 38 | actions = ["sts:AssumeRole"] 39 | effect = "Allow" 40 | } 41 | } 42 | 43 | resource "aws_iam_role_policy_attachment" "eks_cluster_policy" { 44 | count = length(var.cluster_role_arn) == 0 ? 1 : 0 45 | role = aws_iam_role.eks_cluster_role[0].name 46 | policy_arn = "arn:aws:iam::aws:policy/AmazonEKSClusterPolicy" 47 | } 48 | -------------------------------------------------------------------------------- /data.tf: -------------------------------------------------------------------------------- 1 | data "aws_partition" "current" {} 2 | data "aws_caller_identity" "current" {} 3 | data "aws_region" "current" {} 4 | -------------------------------------------------------------------------------- /docs/roll_nodes.md: -------------------------------------------------------------------------------- 1 | # Roll Nodes Procedure 2 | 3 | When upgrading Kubernetes, or rolling out some other node configuration 4 | change you may want to replace all of the nodes in the cluster, so you 5 | can use the new configuration as soon as possible. 6 | 7 | This repo includes a script `hack/roll_nodes.sh` that can be used to perform 8 | this task in a relatively safe way. 9 | 10 | ⚠️ ⚠️ ⚠️ WARNING ⚠️ ⚠️ ⚠️ 11 | * This guide assumes that the cluster autoscaler is enabled (and working) 12 | * This guide assumes that you have correctly configured kubectl's current context to point at the cluster you are working with, and have configured the aws cli so it can perform operations on the nodes in your cluster. 13 | * This guide recommends running a script that performs potentially destructive actions, make sure you understand what it is doing and why before you run it, anything you break is your own fault! 14 | 15 | # Overview 16 | 17 | The `hack/roll_nodes.sh` performs the following actions. 18 | 19 | * Cordon every node in the cluster, this ensures that we don't reschedule 20 | workloads to nodes that we will shortly be removing from the cluster. 21 | * For each node in the cluster: 22 | * Detach the underlying ec2 instance from it's auto scaling group (ASG) - this triggers a new node to be launched and added to the cluster. 23 | * Wait for the new node to be ready 24 | * Run kubectl drain so that workloads are migrated to another node 25 | * Terminate the underlying ec2 node 26 | * Wait for the number of pods that are not in the Running or Succeeded phase to become 0 27 | 28 | # Notes 29 | 30 | 📝 Since the script uses the `kubectl drain` command it should respect pod disruption 31 | budget. If your application is particularly sensitive to disruption, you 32 | might want to review your configured pod disruption budgets before running the script. 33 | See: https://kubernetes.io/docs/concepts/workloads/pods/disruptions/#pod-disruption-budgets 34 | 35 | 📝 If you have to pass any flags when you use the aws cli in your environment 36 | update the script on line 13. 37 | -------------------------------------------------------------------------------- /docs/service_out_asg_node_group.md: -------------------------------------------------------------------------------- 1 | # Service out asg_node_group 2 | 3 | When removing a asg_node_group from your cluster, follow the following 4 | guide to avoid disruption to your services. 5 | 6 | 1. Ensure that you have other node groups that can accept the pods 7 | currently running on the group you want to service out. 8 | 2. Set `cluster_autoscaler = false` on the node group you want to service out, `terraform apply`. 9 | 3. Run `hack/drain_nodes.sh group_name` to drain each of the nodes in the group. 10 | 4. Remove the `asg_node_group` from your terraform configuration, `terraform apply`. 11 | -------------------------------------------------------------------------------- /examples/cluster/.terraform.lock.hcl: -------------------------------------------------------------------------------- 1 | # This file is maintained automatically by "terraform init". 2 | # Manual edits may be lost in future updates. 3 | 4 | provider "registry.terraform.io/hashicorp/aws" { 5 | version = "5.93.0" 6 | constraints = ">= 4.47.0" 7 | hashes = [ 8 | "h1:Gix6sLHGKwqKg4L1V/gBa5tcjIj5UrqH4kW9AX/agl0=", 9 | "h1:ODfuqpsLGW3WShNNPgImLOOXlphVs4u/fFdLkScqi8U=", 10 | "h1:OOAfaIREMxRhe2minsNofE7gn8VDA0XQ659/Eq2hJAc=", 11 | "h1:SbzGotY1leY5nnLo/PJOcwIlNTHdZpAErxJSrfr2tTg=", 12 | "zh:00e1b15e6f02cdc788fe855232b63ccce6652930080eac3ba4b8a2e35db02b23", 13 | "zh:3a77ee12e4f5ab2e7b320a0f507389c9171ab82c50d39ae7caa5a1fb2bd95cb3", 14 | "zh:3e32d58e139d098d867eef37914fef01fffb08504d828e0f384c2ffc18d71f80", 15 | "zh:41cf69a525f0fbe0fdb71d26be7ff5e20bb90ccdf5af32c83ed53f0ca2f071b5", 16 | "zh:43055bdd0786855cf7242638a74b579f74f4f1a8e7c7e5e0e50230c8f6b908cb", 17 | "zh:4ac4c29aa0de842ad91145c5a5fba21338531ffca13a510927d445e007a24938", 18 | "zh:57e510498b3aeb6d6155c10fa195e1d5502e763899251057e59e73f653d1e262", 19 | "zh:8f749645b27dba1a07d06aaf9d5596fc4213123f12f3808d68539e78ab16996e", 20 | "zh:9b12af85486a96aedd8d7984b0ff811a4b42e3d88dad1a3fb4c0b580d04fa425", 21 | "zh:aaca5934ac6273d48922ad7685c5fc2aa7ef5275346a9e70366b7a180a788d41", 22 | "zh:b7585b720a97467302f2e29f0688a5a746778f7b73c30eb085c25831decba1e1", 23 | "zh:c16ae0a46d796858c49a89dd90e5ca92f793e646474fadeafaf701def4a4aa83", 24 | "zh:d66bdc9cd5108452d9dba44082e504ff5e3a3001c8f853bbcaff850cb2127a21", 25 | "zh:ee1aec6c44b117a6c8b7159ee7dc82f1ddac6ba434b4e6c493717738326f0a99", 26 | "zh:f0da48692e00ecacea72d7104714d9721f6be40ba094490c442bb3e68d2e2604", 27 | ] 28 | } 29 | 30 | provider "registry.terraform.io/hashicorp/http" { 31 | version = "3.4.5" 32 | hashes = [ 33 | "h1:ZDXm3QR3UhjciYS49A+KrjVg1qDQ23HyQ24JFdWQEKk=", 34 | "h1:a5N46MBO9glM3c6umjB4LthCtZTtq1k2rNKoiKZstyc=", 35 | "h1:ceAVZEuaQd7jQX13qf5w7hy3ioiXpuwUaaDRsnAiMLM=", 36 | "h1:eSVCYfvn5JyV3LC0+mrLlLtgLv4B+RWeNqz02miBcMY=", 37 | "zh:2072006c177efc101471f3d5eb8e1d8e6c68778cbfd6db3d3f22f59cfe6ce6ae", 38 | "zh:3ac4cc0efe11ee054300769cfcc37491433937a8824621d1f8f7a18e7401da87", 39 | "zh:63997e5457c9ddf9cfff17bd7bf9f083cbeff3105452045662109dd6be499ef9", 40 | "zh:78d5eefdd9e494defcb3c68d282b8f96630502cac21d1ea161f53cfe9bb483b3", 41 | "zh:826819bb8ab7d6e3095f597083d5b1ab93d1854312b9e1b6c18288fff9664f34", 42 | "zh:8ad74e7d8ec2e226a73d49c7c317108f61a4cb803972fb3f945d1709d5115fcd", 43 | "zh:a609ca9e0c91d250ac80295e39d5f524e8c0872d33ba8fde3c3e41893b4b015d", 44 | "zh:ae07d19babc452f63f6a6511b944990e819dc20687b6c8f01d1676812f5ada53", 45 | "zh:b7c827dc32a1a5d77185a78cd391b01217894b384f58169f98a96d683730d8ce", 46 | "zh:d045e3db9f5e39ce78860d3fd94e04604fcbe246f6fe346ee50a971f936e9ccd", 47 | "zh:ec28f9b52c74edd47eebbb5c254a6df5706360cde5ccd65097976efca23a2977", 48 | "zh:f24982eaa7d34fd66554c3cf94873713a0dff14da9ea4c4be0cc76f1a6146d59", 49 | ] 50 | } 51 | 52 | provider "registry.terraform.io/hashicorp/kubernetes" { 53 | version = "2.36.0" 54 | constraints = ">= 2.10.0" 55 | hashes = [ 56 | "h1:94wlXkBzfXwyLVuJVhMdzK+VGjFnMjdmFkYhQ1RUFhI=", 57 | "h1:GLR3jKampPSDrt77O+cjTQrcE/EpQIiIA6sreenoon0=", 58 | "h1:PjjQs2jN1zKWjDt84r1RK2ffbfi4Y2N3Aoa3avYWMZc=", 59 | "h1:vdY0sxo7ahwuz/y7flXTE04tSwn0Zhxyg6n62aTmAHI=", 60 | "zh:07f38fcb7578984a3e2c8cf0397c880f6b3eb2a722a120a08a634a607ea495ca", 61 | "zh:1adde61769c50dbb799d8bf8bfd5c8c504a37017dfd06c7820f82bcf44ca0d39", 62 | "zh:39707f23ab58fd0e686967c0f973c0f5a39c14d6ccfc757f97c345fdd0cd4624", 63 | "zh:4cc3dc2b5d06cc22d1c734f7162b0a8fdc61990ff9efb64e59412d65a7ccc92a", 64 | "zh:8382dcb82ba7303715b5e67939e07dd1c8ecddbe01d12f39b82b2b7d7357e1d9", 65 | "zh:88e8e4f90034186b8bfdea1b8d394621cbc46a064ff2418027e6dba6807d5227", 66 | "zh:a6276a75ad170f76d88263fdb5f9558998bf3a3f7650d7bd3387b396410e59f3", 67 | "zh:bc816c7e0606e5df98a0c7634b240bb0c8100c3107b8b17b554af702edc6a0c5", 68 | "zh:cb2f31d58f37020e840af52755c18afd1f09a833c4903ac59270ab440fab57b7", 69 | "zh:ee0d103b8d0089fb1918311683110b4492a9346f0471b136af46d3b019576b22", 70 | "zh:f569b65999264a9416862bca5cd2a6177d94ccb0424f3a4ef424428912b9cb3c", 71 | "zh:f688b9ec761721e401f6859c19c083e3be20a650426f4747cd359cdc079d212a", 72 | ] 73 | } 74 | -------------------------------------------------------------------------------- /examples/cluster/environment.tf: -------------------------------------------------------------------------------- 1 | # In the test we provision the network and IAM resources using the environment 2 | # module, we then lookup the relevant config here! 3 | # This is in order to simulate launching a cluster in an existing VPC! 4 | 5 | data "terraform_remote_state" "environment" { 6 | backend = "s3" 7 | 8 | config = { 9 | bucket = "cookpad-terraform-aws-eks-testing" 10 | key = "test-environment" 11 | region = "us-east-1" 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /examples/cluster/environment/.terraform-version: -------------------------------------------------------------------------------- 1 | 1.2.3 2 | -------------------------------------------------------------------------------- /examples/cluster/environment/.terraform.lock.hcl: -------------------------------------------------------------------------------- 1 | # This file is maintained automatically by "terraform init". 2 | # Manual edits may be lost in future updates. 3 | 4 | provider "registry.terraform.io/hashicorp/aws" { 5 | version = "5.19.0" 6 | constraints = ">= 3.49.0, ~> 5.0" 7 | hashes = [ 8 | "h1:6eqz2MG2/F3KMkgwzOfwGlNl0tKIDjZmgyNMkrgwXqA=", 9 | "h1:MJclj56jijp7T4V4g5tzHXS3M8vUdJAcBRjEstBh0Hc=", 10 | "h1:QUX8nqmzZAlmG1eKzNLWqXUnsnvQ222cB9n/9J2U4Eo=", 11 | "h1:rgsqMIwX/2b2Ghrfd3lPasPoHupkWsEA+fcXod60+v8=", 12 | "zh:03aa0f857c6dfce5f46c9bf3aad45534b9421e68983994b6f9dd9812beaece9c", 13 | "zh:0639818c5bf9f9943667f39ec38bb945c9786983025dff407390133fa1ca5041", 14 | "zh:0b82ad42ced8fb4a138eaf2fd37cf6059ca0bb482114b35fb84f22fc1500324a", 15 | "zh:173e8c19a9f1d8f6457c80f4a73a92f420a81d650fc4ad0f97a5dc4b9485bba8", 16 | "zh:42913a40ddfe9b4f3c78ad2e3cdc1dcfd48151bc132dc6b49fc32cd6da79db21", 17 | "zh:452db5caca2e53d5f7090979d518e77aa5fd98385514b11ee2ce76a46e89cb53", 18 | "zh:9b12af85486a96aedd8d7984b0ff811a4b42e3d88dad1a3fb4c0b580d04fa425", 19 | "zh:a12377ade89ee18d9be116436e411e8396898bd70b21ab027c161c785e86238d", 20 | "zh:aa9e4746ba49044ad5b4dda57fcdba7bc16fe65f696766fb2c55c30a27abf844", 21 | "zh:adfaee76d283f1c321fad2e4154be88d57da8c2ecfdca9516c8920bd2ece36ed", 22 | "zh:bf6fbc6d60661c03ed2214173c1deced908dc62480dd41e67ac399fa4abd7467", 23 | "zh:cb685da03ad00d1a27891f3d366d75e8795ac81f1b427888b434e6832ca40633", 24 | "zh:e0432c78dfaf2baebe2bf5c0ad8087f547c69c2c5a00e4c1dcd5a6344ce726df", 25 | "zh:e0ec9ccb8d34d6d0d8bf7f8628c223951832b4d50ea8887fc711fa854b3a28b4", 26 | "zh:f274397ada4ef3c1dce2f70e719c8ccf19fc4e7a2e3f45d018764c6267fd7157", 27 | ] 28 | } 29 | -------------------------------------------------------------------------------- /examples/cluster/environment/README.md: -------------------------------------------------------------------------------- 1 | This example provisions an environment that is used in the cluster example. 2 | This is order that we can simulate using the module to launch a cluster using 3 | IAM and VPC resources managed externally. 4 | -------------------------------------------------------------------------------- /examples/cluster/environment/backend.tf: -------------------------------------------------------------------------------- 1 | terraform { 2 | backend "s3" { 3 | bucket = "cookpad-terraform-aws-eks-testing" 4 | key = "test-environment" 5 | region = "us-east-1" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /examples/cluster/environment/main.tf: -------------------------------------------------------------------------------- 1 | provider "aws" { 2 | region = "us-east-1" 3 | allowed_account_ids = ["214219211678"] 4 | } 5 | 6 | #trivy:ignore:AVD-AWS-0178 trivy:ignore:AVD-AWS-0164 7 | module "vpc" { 8 | source = "../../../modules/vpc" 9 | 10 | name = var.vpc_name 11 | cidr_block = var.cidr_block 12 | availability_zones = ["us-east-1a", "us-east-1b", "us-east-1d"] 13 | } 14 | -------------------------------------------------------------------------------- /examples/cluster/environment/outputs.tf: -------------------------------------------------------------------------------- 1 | output "vpc_id" { 2 | value = module.vpc.config.vpc_id 3 | } 4 | 5 | output "public_subnet_ids" { 6 | value = values(module.vpc.config.public_subnet_ids) 7 | } 8 | 9 | output "private_subnet_ids" { 10 | value = values(module.vpc.config.private_subnet_ids) 11 | } 12 | 13 | output "vpc_config" { 14 | value = module.vpc.config 15 | } 16 | -------------------------------------------------------------------------------- /examples/cluster/environment/variables.tf: -------------------------------------------------------------------------------- 1 | variable "vpc_name" { 2 | type = string 3 | default = "terraform-aws-eks-test-environment" 4 | } 5 | 6 | variable "cidr_block" { 7 | type = string 8 | default = "10.0.0.0/18" 9 | } 10 | -------------------------------------------------------------------------------- /examples/cluster/main.tf: -------------------------------------------------------------------------------- 1 | provider "aws" { 2 | region = "us-east-1" 3 | allowed_account_ids = ["214219211678"] 4 | } 5 | 6 | provider "kubernetes" { 7 | host = module.cluster.config.endpoint 8 | cluster_ca_certificate = base64decode(module.cluster.config.ca_data) 9 | 10 | exec { 11 | api_version = "client.authentication.k8s.io/v1beta1" 12 | command = "aws" 13 | args = ["eks", "get-token", "--cluster-name", module.cluster.config.name] 14 | } 15 | } 16 | 17 | data "http" "ip" { 18 | url = "https://ipv4.icanhazip.com" 19 | } 20 | 21 | #trivy:ignore:AVD-AWS-0040 22 | module "cluster" { 23 | source = "../../" 24 | 25 | name = var.cluster_name 26 | 27 | vpc_config = data.terraform_remote_state.environment.outputs.vpc_config 28 | 29 | endpoint_public_access = true 30 | endpoint_public_access_cidrs = ["${chomp(data.http.ip.response_body)}/32"] 31 | 32 | 33 | aws_auth_role_map = [ 34 | { 35 | username = aws_iam_role.test_role.name 36 | rolearn = aws_iam_role.test_role.arn 37 | groups = ["system:masters"] 38 | }, 39 | { 40 | username = "system:node:{{EC2PrivateDNSName}}" 41 | rolearn = module.karpenter.node_role_arn 42 | groups = [ 43 | "system:bootstrappers", 44 | "system:nodes", 45 | ] 46 | }, 47 | ] 48 | 49 | tags = { 50 | Project = "terraform-aws-eks" 51 | } 52 | } 53 | 54 | module "karpenter" { 55 | source = "../../modules/karpenter" 56 | 57 | cluster_config = module.cluster.config 58 | oidc_config = module.cluster.oidc_config 59 | } 60 | 61 | data "aws_security_group" "nodes" { 62 | id = module.cluster.config.node_security_group 63 | } 64 | -------------------------------------------------------------------------------- /examples/cluster/outputs.tf: -------------------------------------------------------------------------------- 1 | output "cluster_name" { 2 | value = var.cluster_name 3 | } 4 | 5 | output "test_role_arn" { 6 | value = aws_iam_role.test_role.arn 7 | } 8 | 9 | output "cluster_config" { 10 | value = module.cluster.config 11 | sensitive = true 12 | } 13 | 14 | output "node_security_group_name" { 15 | value = data.aws_security_group.nodes.name 16 | } 17 | -------------------------------------------------------------------------------- /examples/cluster/test_iam_role.tf: -------------------------------------------------------------------------------- 1 | data "aws_caller_identity" "current" {} 2 | 3 | resource "aws_iam_role" "test_role" { 4 | name_prefix = "TerraformAWSEKS" 5 | assume_role_policy = < 10 | 11 | outputs the local variables with the latest addon 12 | version numbers for a particular k8s release 13 | INFO 14 | 15 | exit 1 16 | end 17 | 18 | ADDONS = %w(vpc-cni kube-proxy coredns aws-ebs-csi-driver) 19 | PADDING = ADDONS.map(&:size).max 20 | 21 | def pad(string) 22 | string.ljust(PADDING) 23 | end 24 | 25 | addons = [] 26 | 27 | ADDONS.each do |addon| 28 | addons += JSON.load(`aws eks describe-addon-versions --kubernetes-version #{K8S_VERSION} --addon-name #{addon}`)["addons"] 29 | end 30 | 31 | puts <<-VERSION 32 | # Run hack/versions k8sVersionNumber > versions.tf 33 | # to generate the latest values for this 34 | locals { 35 | versions = { 36 | #{pad("k8s")} = "#{K8S_VERSION}" 37 | VERSION 38 | 39 | addons.each do |addon| 40 | addon_version = addon["addonVersions"].sort_by { |v| Gem::Version.new(v["addonVersion"][1..-1]) }.last["addonVersion"] 41 | puts <<-VERSION 42 | #{pad(addon["addonName"].gsub("-", "_"))} = "#{ addon_version }" 43 | VERSION 44 | end 45 | 46 | puts <<-END 47 | } 48 | } 49 | END 50 | -------------------------------------------------------------------------------- /main.tf: -------------------------------------------------------------------------------- 1 | /* 2 | EKS control plane 3 | */ 4 | 5 | resource "aws_eks_cluster" "control_plane" { 6 | name = var.name 7 | role_arn = local.eks_cluster_role_arn 8 | tags = var.tags 9 | 10 | version = local.versions.k8s 11 | 12 | enabled_cluster_log_types = var.cluster_log_types 13 | 14 | vpc_config { 15 | endpoint_private_access = true 16 | endpoint_public_access = var.endpoint_public_access 17 | public_access_cidrs = var.endpoint_public_access_cidrs 18 | security_group_ids = concat(aws_security_group.control_plane.*.id, var.security_group_ids) 19 | subnet_ids = concat(values(var.vpc_config.public_subnet_ids), values(var.vpc_config.private_subnet_ids)) 20 | } 21 | 22 | encryption_config { 23 | resources = ["secrets"] 24 | 25 | provider { 26 | key_arn = local.kms_cmk_arn 27 | } 28 | } 29 | 30 | depends_on = [aws_cloudwatch_log_group.control_plane] 31 | } 32 | 33 | 34 | 35 | resource "aws_iam_openid_connect_provider" "cluster_oidc" { 36 | url = aws_eks_cluster.control_plane.identity.0.oidc.0.issuer 37 | thumbprint_list = var.oidc_root_ca_thumbprints 38 | client_id_list = ["sts.amazonaws.com"] 39 | } 40 | 41 | resource "aws_cloudwatch_log_group" "control_plane" { 42 | name = "/aws/eks/${var.name}/cluster" 43 | retention_in_days = 7 44 | tags = var.tags 45 | kms_key_id = local.kms_cmk_arn 46 | } 47 | /* 48 | Allow nodes to join the cluster 49 | */ 50 | 51 | locals { 52 | aws_auth_configmap_data = { 53 | mapRoles = yamlencode(concat( 54 | [ 55 | { 56 | rolearn = aws_iam_role.fargate.arn 57 | username = "system:node:{{SessionName}}" 58 | groups = [ 59 | "system:bootstrappers", 60 | "system:nodes", 61 | "system:node-proxier", 62 | ] 63 | }, 64 | ], 65 | var.aws_auth_role_map, 66 | )) 67 | mapUsers = yamlencode(var.aws_auth_user_map) 68 | } 69 | } 70 | 71 | resource "kubernetes_config_map" "aws_auth" { 72 | metadata { 73 | name = "aws-auth" 74 | namespace = "kube-system" 75 | } 76 | 77 | data = local.aws_auth_configmap_data 78 | 79 | lifecycle { 80 | # We are ignoring the data here since we will manage it with the resource below 81 | # This is only intended to be used in scenarios where the configmap does not exist 82 | ignore_changes = [data, metadata[0].labels, metadata[0].annotations] 83 | } 84 | } 85 | 86 | resource "kubernetes_config_map_v1_data" "aws_auth" { 87 | force = true 88 | 89 | metadata { 90 | name = "aws-auth" 91 | namespace = "kube-system" 92 | } 93 | 94 | data = local.aws_auth_configmap_data 95 | 96 | depends_on = [ 97 | # Required for instances where the configmap does not exist yet to avoid race condition 98 | kubernetes_config_map.aws_auth, 99 | ] 100 | } 101 | 102 | locals { 103 | create_key = length(var.kms_cmk_arn) == 0 104 | kms_cmk_arn = local.create_key ? aws_kms_key.cmk.*.arn[0] : var.kms_cmk_arn 105 | } 106 | 107 | 108 | data "aws_iam_policy_document" "cloudwatch" { 109 | policy_id = "key-policy-cloudwatch" 110 | statement { 111 | sid = "Enable IAM User Permissions" 112 | actions = [ 113 | "kms:*", 114 | ] 115 | effect = "Allow" 116 | principals { 117 | type = "AWS" 118 | identifiers = [ 119 | format( 120 | "arn:%s:iam::%s:root", 121 | data.aws_partition.current.partition, 122 | data.aws_caller_identity.current.account_id 123 | ) 124 | ] 125 | } 126 | resources = ["*"] 127 | } 128 | statement { 129 | sid = "AllowCloudWatchLogs" 130 | actions = [ 131 | "kms:Encrypt*", 132 | "kms:Decrypt*", 133 | "kms:ReEncrypt*", 134 | "kms:GenerateDataKey*", 135 | "kms:Describe*" 136 | ] 137 | effect = "Allow" 138 | principals { 139 | type = "Service" 140 | identifiers = [ 141 | format( 142 | "logs.%s.amazonaws.com", 143 | data.aws_region.current.name 144 | ) 145 | ] 146 | } 147 | resources = ["*"] 148 | condition { 149 | test = "ArnEquals" 150 | variable = "kms:EncryptionContext:aws:logs:arn" 151 | values = [ 152 | format( 153 | "arn:aws:logs:%s:%s:log-group:/aws/eks/%s/cluster", 154 | data.aws_region.current.name, 155 | data.aws_caller_identity.current.account_id, 156 | var.name, 157 | ) 158 | ] 159 | } 160 | } 161 | } 162 | 163 | 164 | resource "aws_kms_key" "cmk" { 165 | count = local.create_key ? 1 : 0 166 | description = "eks secrets cmk: ${var.name}" 167 | enable_key_rotation = true 168 | policy = data.aws_iam_policy_document.cloudwatch.json 169 | } 170 | -------------------------------------------------------------------------------- /modules/karpenter/README.md: -------------------------------------------------------------------------------- 1 | # Karpenter 2 | 3 | This module configures the resources required to run the 4 | karpenter node-provisioning tool in an eks cluster. 5 | 6 | * Fargate Profile - to run karpenter 7 | * IAM roles for the fargate controller and nodes to be provisioned by karpenter 8 | * SQS queue to provide events (spot interruption etc) to karpenter 9 | 10 | It does not install karpenter itself to the cluster - and we recomend 11 | that you use helm as per the [karpenter documentation](https://karpenter.sh/docs/getting-started/getting-started-with-karpenter/#4-install-karpenter) 12 | 13 | It is provided as a submodule so the core module is less opinionated. 14 | 15 | However we test the core module and the karpenter module 16 | in our test suite to ensure that the different components we use in our 17 | clusters at cookpad intergrate correctly. 18 | 19 | 20 | ## Example 21 | 22 | You should pass cluster and oidc config from the cluster to the karpenter module. 23 | 24 | You will also need to add the IAM role of nodes created by karpenter to the aws_auth_role_map 25 | so they can connect to the cluster. 26 | 27 | ```hcl 28 | module "cluster" { 29 | source = "cookpad/eks/aws" 30 | name = "hal-9000" 31 | vpc_config = module.vpc.config 32 | 33 | aws_auth_role_map = [ 34 | { 35 | username = "system:node:{{EC2PrivateDNSName}}" 36 | rolearn = module.karpenter.node_role_arn 37 | groups = [ 38 | "system:bootstrappers", 39 | "system:nodes", 40 | ] 41 | }, 42 | ] 43 | } 44 | 45 | module "karpenter" { 46 | source = "cookpad/eks/aws//modules/karpenter" 47 | 48 | cluster_config = module.cluster.config 49 | oidc_config = module.cluster.oidc_config 50 | } 51 | ``` 52 | -------------------------------------------------------------------------------- /modules/karpenter/controller_iam.tf: -------------------------------------------------------------------------------- 1 | resource "aws_iam_role" "karpenter_controller" { 2 | name = "${var.cluster_config.iam_role_name_prefix}Karpenter-${var.cluster_config.name}" 3 | assume_role_policy = data.aws_iam_policy_document.karpenter_controller_assume_role_policy.json 4 | description = "Karpenter controller role for ${var.cluster_config.name} cluster" 5 | } 6 | 7 | data "aws_iam_policy_document" "karpenter_controller_assume_role_policy" { 8 | statement { 9 | actions = ["sts:AssumeRoleWithWebIdentity"] 10 | effect = "Allow" 11 | 12 | condition { 13 | test = "StringEquals" 14 | variable = "${replace(var.oidc_config.url, "https://", "")}:sub" 15 | values = ["system:serviceaccount:karpenter:karpenter"] 16 | } 17 | 18 | condition { 19 | test = "StringEquals" 20 | variable = "${replace(var.oidc_config.url, "https://", "")}:aud" 21 | values = ["sts.amazonaws.com"] 22 | } 23 | 24 | principals { 25 | identifiers = [var.oidc_config.arn] 26 | type = "Federated" 27 | } 28 | } 29 | } 30 | 31 | resource "aws_iam_role_policy" "karpenter_controller_v1_beta" { 32 | count = var.v1beta ? 1 : 0 33 | name = "KarpenterController-v1beta" 34 | role = aws_iam_role.karpenter_controller.id 35 | policy = data.aws_iam_policy_document.karpenter_controller_v1_beta.json 36 | } 37 | 38 | moved { 39 | from = aws_iam_role_policy.karpenter_controller_v1_beta 40 | to = aws_iam_role_policy.karpenter_controller_v1_beta[0] 41 | } 42 | 43 | data "aws_iam_policy_document" "karpenter_controller_v1_beta" { 44 | statement { 45 | sid = "AllowScopedEC2InstanceAccessActions" 46 | effect = "Allow" 47 | 48 | resources = [ 49 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}::image/*", 50 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}::snapshot/*", 51 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:security-group/*", 52 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:subnet/*", 53 | ] 54 | 55 | actions = [ 56 | "ec2:RunInstances", 57 | "ec2:CreateFleet", 58 | ] 59 | } 60 | 61 | statement { 62 | sid = "AllowScopedEC2LaunchTemplateAccessActions" 63 | effect = "Allow" 64 | 65 | resources = [ 66 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:launch-template/*", 67 | ] 68 | 69 | actions = [ 70 | "ec2:RunInstances", 71 | "ec2:CreateFleet", 72 | ] 73 | 74 | condition { 75 | test = "StringEquals" 76 | variable = "aws:ResourceTag/kubernetes.io/cluster/${var.cluster_config.name}" 77 | values = ["owned"] 78 | } 79 | 80 | condition { 81 | test = "StringLike" 82 | variable = "aws:ResourceTag/karpenter.sh/nodepool" 83 | values = ["*"] 84 | } 85 | } 86 | 87 | statement { 88 | sid = "AllowScopedEC2InstanceActionsWithTags" 89 | effect = "Allow" 90 | 91 | resources = [ 92 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:fleet/*", 93 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:instance/*", 94 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:volume/*", 95 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:network-interface/*", 96 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:launch-template/*", 97 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:spot-instances-request/*", 98 | ] 99 | 100 | actions = [ 101 | "ec2:RunInstances", 102 | "ec2:CreateFleet", 103 | "ec2:CreateLaunchTemplate", 104 | ] 105 | 106 | condition { 107 | test = "StringEquals" 108 | variable = "aws:RequestTag/kubernetes.io/cluster/${var.cluster_config.name}" 109 | values = ["owned"] 110 | } 111 | 112 | condition { 113 | test = "StringLike" 114 | variable = "aws:RequestTag/karpenter.sh/nodepool" 115 | values = ["*"] 116 | } 117 | } 118 | 119 | statement { 120 | sid = "AllowScopedResourceCreationTagging" 121 | effect = "Allow" 122 | 123 | resources = [ 124 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:fleet/*", 125 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:instance/*", 126 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:volume/*", 127 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:network-interface/*", 128 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:launch-template/*", 129 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:spot-instances-request/*", 130 | ] 131 | 132 | actions = ["ec2:CreateTags"] 133 | 134 | condition { 135 | test = "StringEquals" 136 | variable = "aws:RequestTag/kubernetes.io/cluster/${var.cluster_config.name}" 137 | values = ["owned"] 138 | } 139 | 140 | condition { 141 | test = "StringEquals" 142 | variable = "ec2:CreateAction" 143 | 144 | values = [ 145 | "RunInstances", 146 | "CreateFleet", 147 | "CreateLaunchTemplate", 148 | ] 149 | } 150 | 151 | condition { 152 | test = "StringLike" 153 | variable = "aws:RequestTag/karpenter.sh/nodepool" 154 | values = ["*"] 155 | } 156 | } 157 | 158 | statement { 159 | sid = "AllowScopedResourceTagging" 160 | effect = "Allow" 161 | 162 | resources = ["arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:instance/*"] 163 | actions = ["ec2:CreateTags"] 164 | 165 | condition { 166 | test = "StringEquals" 167 | variable = "aws:ResourceTag/kubernetes.io/cluster/${var.cluster_config.name}" 168 | values = ["owned"] 169 | } 170 | 171 | condition { 172 | test = "StringLike" 173 | variable = "aws:ResourceTag/karpenter.sh/nodepool" 174 | values = ["*"] 175 | } 176 | 177 | condition { 178 | test = "ForAllValues:StringEquals" 179 | variable = "aws:TagKeys" 180 | values = ["karpenter.sh/nodeclaim", "Name"] 181 | } 182 | } 183 | 184 | 185 | statement { 186 | sid = "AllowScopedDeletion" 187 | effect = "Allow" 188 | 189 | resources = [ 190 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:instance/*", 191 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:launch-template/*", 192 | ] 193 | 194 | actions = [ 195 | "ec2:TerminateInstances", 196 | "ec2:DeleteLaunchTemplate", 197 | ] 198 | 199 | condition { 200 | test = "StringEquals" 201 | variable = "aws:ResourceTag/kubernetes.io/cluster/${var.cluster_config.name}" 202 | values = ["owned"] 203 | } 204 | 205 | condition { 206 | test = "StringLike" 207 | variable = "aws:ResourceTag/karpenter.sh/nodepool" 208 | values = ["*"] 209 | } 210 | } 211 | 212 | statement { 213 | sid = "AllowRegionalReadActions" 214 | effect = "Allow" 215 | resources = ["*"] 216 | 217 | actions = [ 218 | "ec2:DescribeAvailabilityZones", 219 | "ec2:DescribeImages", 220 | "ec2:DescribeInstances", 221 | "ec2:DescribeInstanceTypeOfferings", 222 | "ec2:DescribeInstanceTypes", 223 | "ec2:DescribeLaunchTemplates", 224 | "ec2:DescribeSecurityGroups", 225 | "ec2:DescribeSpotPriceHistory", 226 | "ec2:DescribeSubnets", 227 | ] 228 | 229 | condition { 230 | test = "StringEquals" 231 | variable = "aws:RequestedRegion" 232 | values = [data.aws_region.current.name] 233 | } 234 | } 235 | 236 | statement { 237 | sid = "AllowSSMReadActions" 238 | effect = "Allow" 239 | resources = ["arn:${data.aws_partition.current.partition}:ssm:${data.aws_region.current.name}::parameter/aws/service/*"] 240 | actions = ["ssm:GetParameter"] 241 | } 242 | 243 | statement { 244 | sid = "AllowPricingReadActions" 245 | effect = "Allow" 246 | resources = ["*"] 247 | actions = ["pricing:GetProducts"] 248 | } 249 | 250 | statement { 251 | sid = "AllowInterruptionQueueActions" 252 | effect = "Allow" 253 | resources = [aws_sqs_queue.karpenter_interruption.arn] 254 | 255 | actions = [ 256 | "sqs:DeleteMessage", 257 | "sqs:GetQueueUrl", 258 | "sqs:ReceiveMessage", 259 | ] 260 | } 261 | 262 | statement { 263 | sid = "AllowPassingInstanceRole" 264 | effect = "Allow" 265 | resources = concat([aws_iam_role.karpenter_node.arn], var.additional_node_role_arns) 266 | actions = ["iam:PassRole"] 267 | 268 | condition { 269 | test = "StringEquals" 270 | variable = "iam:PassedToService" 271 | values = ["ec2.amazonaws.com"] 272 | } 273 | } 274 | 275 | statement { 276 | sid = "AllowScopedInstanceProfileCreationActions" 277 | effect = "Allow" 278 | resources = ["*"] 279 | actions = ["iam:CreateInstanceProfile"] 280 | 281 | condition { 282 | test = "StringEquals" 283 | variable = "aws:RequestTag/kubernetes.io/cluster/${var.cluster_config.name}" 284 | values = ["owned"] 285 | } 286 | 287 | condition { 288 | test = "StringEquals" 289 | variable = "aws:RequestTag/topology.kubernetes.io/region" 290 | values = [data.aws_region.current.name] 291 | } 292 | 293 | condition { 294 | test = "StringLike" 295 | variable = "aws:RequestTag/karpenter.k8s.aws/ec2nodeclass" 296 | values = ["*"] 297 | } 298 | } 299 | 300 | statement { 301 | sid = "AllowScopedInstanceProfileTagActions" 302 | effect = "Allow" 303 | resources = ["*"] 304 | actions = ["iam:TagInstanceProfile"] 305 | 306 | condition { 307 | test = "StringEquals" 308 | variable = "aws:ResourceTag/kubernetes.io/cluster/${var.cluster_config.name}" 309 | values = ["owned"] 310 | } 311 | 312 | condition { 313 | test = "StringEquals" 314 | variable = "aws:ResourceTag/topology.kubernetes.io/region" 315 | values = [data.aws_region.current.name] 316 | } 317 | 318 | condition { 319 | test = "StringEquals" 320 | variable = "aws:RequestTag/kubernetes.io/cluster/${var.cluster_config.name}" 321 | values = ["owned"] 322 | } 323 | 324 | condition { 325 | test = "StringEquals" 326 | variable = "aws:RequestTag/topology.kubernetes.io/region" 327 | values = [data.aws_region.current.name] 328 | } 329 | 330 | condition { 331 | test = "StringLike" 332 | variable = "aws:ResourceTag/karpenter.k8s.aws/ec2nodeclass" 333 | values = ["*"] 334 | } 335 | 336 | condition { 337 | test = "StringLike" 338 | variable = "aws:RequestTag/karpenter.k8s.aws/ec2nodeclass" 339 | values = ["*"] 340 | } 341 | } 342 | 343 | statement { 344 | sid = "AllowScopedInstanceProfileActions" 345 | effect = "Allow" 346 | resources = ["*"] 347 | actions = [ 348 | "iam:AddRoleToInstanceProfile", 349 | "iam:RemoveRoleFromInstanceProfile", 350 | "iam:DeleteInstanceProfile", 351 | ] 352 | 353 | condition { 354 | test = "StringEquals" 355 | variable = "aws:ResourceTag/kubernetes.io/cluster/${var.cluster_config.name}" 356 | values = ["owned"] 357 | } 358 | 359 | condition { 360 | test = "StringEquals" 361 | variable = "aws:ResourceTag/topology.kubernetes.io/region" 362 | values = [data.aws_region.current.name] 363 | } 364 | 365 | condition { 366 | test = "StringLike" 367 | variable = "aws:ResourceTag/karpenter.k8s.aws/ec2nodeclass" 368 | values = ["*"] 369 | } 370 | } 371 | 372 | statement { 373 | sid = "AllowInstanceProfileReadActions" 374 | effect = "Allow" 375 | resources = ["*"] 376 | actions = ["iam:GetInstanceProfile"] 377 | } 378 | 379 | statement { 380 | sid = "AllowAPIServerEndpointDiscovery" 381 | effect = "Allow" 382 | resources = [var.cluster_config.arn] 383 | actions = ["eks:DescribeCluster"] 384 | } 385 | } 386 | 387 | resource "aws_iam_role_policy_attachment" "karpenter_controller_v1" { 388 | count = var.v1 ? 1 : 0 389 | role = aws_iam_role.karpenter_controller.id 390 | policy_arn = aws_iam_policy.karpenter_controller_v1[0].arn 391 | } 392 | 393 | resource "aws_iam_policy" "karpenter_controller_v1" { 394 | count = var.v1 ? 1 : 0 395 | name = "${var.cluster_config.iam_policy_name_prefix}KarpenterController-v1-${var.cluster_config.name}" 396 | policy = data.aws_iam_policy_document.karpenter_controller_v1.json 397 | } 398 | 399 | #trivy:ignore:AVD-AWS-0342 400 | data "aws_iam_policy_document" "karpenter_controller_v1" { 401 | statement { 402 | sid = "AllowScopedEC2InstanceAccessActions" 403 | effect = "Allow" 404 | 405 | resources = [ 406 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}::image/*", 407 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}::snapshot/*", 408 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:security-group/*", 409 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:subnet/*", 410 | ] 411 | 412 | actions = [ 413 | "ec2:RunInstances", 414 | "ec2:CreateFleet", 415 | ] 416 | } 417 | 418 | statement { 419 | sid = "AllowScopedEC2LaunchTemplateAccessActions" 420 | effect = "Allow" 421 | 422 | resources = [ 423 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:launch-template/*", 424 | ] 425 | 426 | actions = [ 427 | "ec2:RunInstances", 428 | "ec2:CreateFleet", 429 | ] 430 | 431 | condition { 432 | test = "StringEquals" 433 | variable = "aws:ResourceTag/kubernetes.io/cluster/${var.cluster_config.name}" 434 | values = ["owned"] 435 | } 436 | 437 | condition { 438 | test = "StringLike" 439 | variable = "aws:ResourceTag/karpenter.sh/nodepool" 440 | values = ["*"] 441 | } 442 | } 443 | 444 | statement { 445 | sid = "AllowScopedEC2InstanceActionsWithTags" 446 | effect = "Allow" 447 | 448 | resources = [ 449 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:fleet/*", 450 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:instance/*", 451 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:volume/*", 452 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:network-interface/*", 453 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:launch-template/*", 454 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:spot-instances-request/*", 455 | ] 456 | 457 | actions = [ 458 | "ec2:RunInstances", 459 | "ec2:CreateFleet", 460 | "ec2:CreateLaunchTemplate", 461 | ] 462 | 463 | condition { 464 | test = "StringEquals" 465 | variable = "aws:RequestTag/kubernetes.io/cluster/${var.cluster_config.name}" 466 | values = ["owned"] 467 | } 468 | 469 | condition { 470 | test = "StringEquals" 471 | variable = "aws:RequestTag/eks:eks-cluster-name" 472 | values = [var.cluster_config.name] 473 | } 474 | 475 | condition { 476 | test = "StringLike" 477 | variable = "aws:RequestTag/karpenter.sh/nodepool" 478 | values = ["*"] 479 | } 480 | } 481 | 482 | statement { 483 | sid = "AllowScopedResourceCreationTagging" 484 | effect = "Allow" 485 | 486 | resources = [ 487 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:fleet/*", 488 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:instance/*", 489 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:volume/*", 490 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:network-interface/*", 491 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:launch-template/*", 492 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:spot-instances-request/*", 493 | ] 494 | 495 | actions = ["ec2:CreateTags"] 496 | 497 | condition { 498 | test = "StringEquals" 499 | variable = "aws:RequestTag/kubernetes.io/cluster/${var.cluster_config.name}" 500 | values = ["owned"] 501 | } 502 | 503 | condition { 504 | test = "StringEquals" 505 | variable = "aws:RequestTag/eks:eks-cluster-name" 506 | values = [var.cluster_config.name] 507 | } 508 | 509 | condition { 510 | test = "StringEquals" 511 | variable = "ec2:CreateAction" 512 | 513 | values = [ 514 | "RunInstances", 515 | "CreateFleet", 516 | "CreateLaunchTemplate", 517 | ] 518 | } 519 | 520 | condition { 521 | test = "StringLike" 522 | variable = "aws:RequestTag/karpenter.sh/nodepool" 523 | values = ["*"] 524 | } 525 | } 526 | 527 | statement { 528 | sid = "AllowScopedResourceTagging" 529 | effect = "Allow" 530 | 531 | resources = ["arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:instance/*"] 532 | actions = ["ec2:CreateTags"] 533 | 534 | condition { 535 | test = "StringEquals" 536 | variable = "aws:ResourceTag/kubernetes.io/cluster/${var.cluster_config.name}" 537 | values = ["owned"] 538 | } 539 | 540 | condition { 541 | test = "StringLike" 542 | variable = "aws:ResourceTag/karpenter.sh/nodepool" 543 | values = ["*"] 544 | } 545 | 546 | condition { 547 | test = "StringEqualsIfExists" 548 | variable = "aws:RequestTag/eks:eks-cluster-name" 549 | values = [var.cluster_config.name] 550 | } 551 | 552 | condition { 553 | test = "ForAllValues:StringEquals" 554 | variable = "aws:TagKeys" 555 | values = ["eks:eks-cluster-name", "karpenter.sh/nodeclaim", "Name"] 556 | } 557 | } 558 | 559 | 560 | statement { 561 | sid = "AllowScopedDeletion" 562 | effect = "Allow" 563 | 564 | resources = [ 565 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:instance/*", 566 | "arn:${data.aws_partition.current.partition}:ec2:${data.aws_region.current.name}:*:launch-template/*", 567 | ] 568 | 569 | actions = [ 570 | "ec2:TerminateInstances", 571 | "ec2:DeleteLaunchTemplate", 572 | ] 573 | 574 | condition { 575 | test = "StringEquals" 576 | variable = "aws:ResourceTag/kubernetes.io/cluster/${var.cluster_config.name}" 577 | values = ["owned"] 578 | } 579 | 580 | condition { 581 | test = "StringLike" 582 | variable = "aws:ResourceTag/karpenter.sh/nodepool" 583 | values = ["*"] 584 | } 585 | } 586 | 587 | statement { 588 | sid = "AllowRegionalReadActions" 589 | effect = "Allow" 590 | resources = ["*"] 591 | 592 | actions = [ 593 | "ec2:DescribeAvailabilityZones", 594 | "ec2:DescribeImages", 595 | "ec2:DescribeInstances", 596 | "ec2:DescribeInstanceTypeOfferings", 597 | "ec2:DescribeInstanceTypes", 598 | "ec2:DescribeLaunchTemplates", 599 | "ec2:DescribeSecurityGroups", 600 | "ec2:DescribeSpotPriceHistory", 601 | "ec2:DescribeSubnets", 602 | ] 603 | 604 | condition { 605 | test = "StringEquals" 606 | variable = "aws:RequestedRegion" 607 | values = [data.aws_region.current.name] 608 | } 609 | } 610 | 611 | statement { 612 | sid = "AllowSSMReadActions" 613 | effect = "Allow" 614 | resources = ["arn:${data.aws_partition.current.partition}:ssm:${data.aws_region.current.name}::parameter/aws/service/*"] 615 | actions = ["ssm:GetParameter"] 616 | } 617 | 618 | statement { 619 | sid = "AllowPricingReadActions" 620 | effect = "Allow" 621 | resources = ["*"] 622 | actions = ["pricing:GetProducts"] 623 | } 624 | 625 | statement { 626 | sid = "AllowInterruptionQueueActions" 627 | effect = "Allow" 628 | resources = [aws_sqs_queue.karpenter_interruption.arn] 629 | 630 | actions = [ 631 | "sqs:DeleteMessage", 632 | "sqs:GetQueueUrl", 633 | "sqs:ReceiveMessage", 634 | ] 635 | } 636 | 637 | statement { 638 | sid = "AllowPassingInstanceRole" 639 | effect = "Allow" 640 | resources = concat([aws_iam_role.karpenter_node.arn], var.additional_node_role_arns) 641 | actions = ["iam:PassRole"] 642 | 643 | condition { 644 | test = "StringEquals" 645 | variable = "iam:PassedToService" 646 | values = ["ec2.amazonaws.com"] 647 | } 648 | } 649 | 650 | statement { 651 | sid = "AllowScopedInstanceProfileCreationActions" 652 | effect = "Allow" 653 | resources = ["arn:${data.aws_partition.current.partition}:iam::${data.aws_caller_identity.current.account_id}:instance-profile/*"] 654 | actions = ["iam:CreateInstanceProfile"] 655 | 656 | condition { 657 | test = "StringEquals" 658 | variable = "aws:RequestTag/kubernetes.io/cluster/${var.cluster_config.name}" 659 | values = ["owned"] 660 | } 661 | 662 | condition { 663 | test = "StringEquals" 664 | variable = "aws:RequestTag/eks:eks-cluster-name" 665 | values = [var.cluster_config.name] 666 | } 667 | 668 | condition { 669 | test = "StringEquals" 670 | variable = "aws:RequestTag/topology.kubernetes.io/region" 671 | values = [data.aws_region.current.name] 672 | } 673 | 674 | condition { 675 | test = "StringLike" 676 | variable = "aws:RequestTag/karpenter.k8s.aws/ec2nodeclass" 677 | values = ["*"] 678 | } 679 | } 680 | 681 | statement { 682 | sid = "AllowScopedInstanceProfileTagActions" 683 | effect = "Allow" 684 | resources = ["arn:${data.aws_partition.current.partition}:iam::${data.aws_caller_identity.current.account_id}:instance-profile/*"] 685 | actions = ["iam:TagInstanceProfile"] 686 | 687 | condition { 688 | test = "StringEquals" 689 | variable = "aws:ResourceTag/kubernetes.io/cluster/${var.cluster_config.name}" 690 | values = ["owned"] 691 | } 692 | 693 | condition { 694 | test = "StringEquals" 695 | variable = "aws:ResourceTag/topology.kubernetes.io/region" 696 | values = [data.aws_region.current.name] 697 | } 698 | 699 | condition { 700 | test = "StringEquals" 701 | variable = "aws:RequestTag/kubernetes.io/cluster/${var.cluster_config.name}" 702 | values = ["owned"] 703 | } 704 | 705 | condition { 706 | test = "StringEquals" 707 | variable = "aws:RequestTag/eks:eks-cluster-name" 708 | values = [var.cluster_config.name] 709 | } 710 | 711 | condition { 712 | test = "StringEquals" 713 | variable = "aws:RequestTag/topology.kubernetes.io/region" 714 | values = [data.aws_region.current.name] 715 | } 716 | 717 | condition { 718 | test = "StringLike" 719 | variable = "aws:ResourceTag/karpenter.k8s.aws/ec2nodeclass" 720 | values = ["*"] 721 | } 722 | 723 | condition { 724 | test = "StringLike" 725 | variable = "aws:RequestTag/karpenter.k8s.aws/ec2nodeclass" 726 | values = ["*"] 727 | } 728 | } 729 | 730 | statement { 731 | sid = "AllowScopedInstanceProfileActions" 732 | effect = "Allow" 733 | resources = ["arn:${data.aws_partition.current.partition}:iam::${data.aws_caller_identity.current.account_id}:instance-profile/*"] 734 | actions = [ 735 | "iam:AddRoleToInstanceProfile", 736 | "iam:RemoveRoleFromInstanceProfile", 737 | "iam:DeleteInstanceProfile", 738 | ] 739 | 740 | condition { 741 | test = "StringEquals" 742 | variable = "aws:ResourceTag/kubernetes.io/cluster/${var.cluster_config.name}" 743 | values = ["owned"] 744 | } 745 | 746 | condition { 747 | test = "StringEquals" 748 | variable = "aws:ResourceTag/topology.kubernetes.io/region" 749 | values = [data.aws_region.current.name] 750 | } 751 | 752 | condition { 753 | test = "StringLike" 754 | variable = "aws:ResourceTag/karpenter.k8s.aws/ec2nodeclass" 755 | values = ["*"] 756 | } 757 | } 758 | 759 | statement { 760 | sid = "AllowInstanceProfileReadActions" 761 | effect = "Allow" 762 | resources = ["arn:${data.aws_partition.current.partition}:iam::${data.aws_caller_identity.current.account_id}:instance-profile/*"] 763 | actions = ["iam:GetInstanceProfile"] 764 | } 765 | 766 | statement { 767 | sid = "AllowAPIServerEndpointDiscovery" 768 | effect = "Allow" 769 | resources = [var.cluster_config.arn] 770 | actions = ["eks:DescribeCluster"] 771 | } 772 | } 773 | -------------------------------------------------------------------------------- /modules/karpenter/data.tf: -------------------------------------------------------------------------------- 1 | data "aws_caller_identity" "current" {} 2 | data "aws_partition" "current" {} 3 | data "aws_region" "current" {} 4 | -------------------------------------------------------------------------------- /modules/karpenter/fargate.tf: -------------------------------------------------------------------------------- 1 | resource "aws_eks_fargate_profile" "critical_pods" { 2 | cluster_name = var.cluster_config.name 3 | fargate_profile_name = "${var.cluster_config.name}-karpenter" 4 | pod_execution_role_arn = var.cluster_config.fargate_execution_role_arn 5 | subnet_ids = values(var.cluster_config.private_subnet_ids) 6 | 7 | selector { 8 | namespace = "karpenter" 9 | labels = {} 10 | } 11 | 12 | timeouts { 13 | create = "10m" 14 | delete = "20m" 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /modules/karpenter/interruption_queue.tf: -------------------------------------------------------------------------------- 1 | resource "aws_sqs_queue" "karpenter_interruption" { 2 | name = "Karpenter-${var.cluster_config.name}" 3 | message_retention_seconds = 300 4 | sqs_managed_sse_enabled = true 5 | } 6 | 7 | resource "aws_sqs_queue_policy" "karpenter_interruption" { 8 | queue_url = aws_sqs_queue.karpenter_interruption.url 9 | policy = data.aws_iam_policy_document.karpenter_interruption_queue_policy.json 10 | } 11 | 12 | data "aws_iam_policy_document" "karpenter_interruption_queue_policy" { 13 | statement { 14 | sid = "SqsWrite" 15 | actions = ["sqs:SendMessage"] 16 | resources = [aws_sqs_queue.karpenter_interruption.arn] 17 | principals { 18 | type = "Service" 19 | identifiers = [ 20 | "events.amazonaws.com", 21 | "sqs.amazonaws.com", 22 | ] 23 | } 24 | } 25 | 26 | statement { 27 | sid = "DenyHTTP" 28 | effect = "Deny" 29 | actions = ["sqs:*"] 30 | resources = [aws_sqs_queue.karpenter_interruption.arn] 31 | condition { 32 | test = "Bool" 33 | variable = "aws:SecureTransport" 34 | values = [false] 35 | } 36 | } 37 | } 38 | 39 | locals { 40 | karpenter_events = { 41 | health_event = { 42 | name = "HealthEvent" 43 | description = "Karpenter interrupt - AWS health event" 44 | event_pattern = { 45 | source = ["aws.health"] 46 | detail-type = ["AWS Health Event"] 47 | } 48 | } 49 | spot_interupt = { 50 | name = "SpotInterrupt" 51 | description = "Karpenter interrupt - EC2 spot instance interruption warning" 52 | event_pattern = { 53 | source = ["aws.ec2"] 54 | detail-type = ["EC2 Spot Instance Interruption Warning"] 55 | } 56 | } 57 | instance_rebalance = { 58 | name = "InstanceRebalance" 59 | description = "Karpenter interrupt - EC2 instance rebalance recommendation" 60 | event_pattern = { 61 | source = ["aws.ec2"] 62 | detail-type = ["EC2 Instance Rebalance Recommendation"] 63 | } 64 | } 65 | instance_state_change = { 66 | name = "InstanceStateChange" 67 | description = "Karpenter interrupt - EC2 instance state-change notification" 68 | event_pattern = { 69 | source = ["aws.ec2"] 70 | detail-type = ["EC2 Instance State-change Notification"] 71 | } 72 | } 73 | } 74 | } 75 | 76 | resource "aws_cloudwatch_event_rule" "karpenter" { 77 | for_each = local.karpenter_events 78 | 79 | name = "Karpenter${each.value.name}-${var.cluster_config.name}" 80 | description = each.value.description 81 | event_pattern = jsonencode(each.value.event_pattern) 82 | } 83 | 84 | resource "aws_cloudwatch_event_target" "karpenter" { 85 | for_each = local.karpenter_events 86 | rule = aws_cloudwatch_event_rule.karpenter[each.key].name 87 | target_id = "KarpenterInterruptionQueueTarget" 88 | arn = aws_sqs_queue.karpenter_interruption.arn 89 | } 90 | -------------------------------------------------------------------------------- /modules/karpenter/node_iam.tf: -------------------------------------------------------------------------------- 1 | resource "aws_iam_role" "karpenter_node" { 2 | name = "${var.cluster_config.iam_role_name_prefix}KarpenterNode-${var.cluster_config.name}" 3 | assume_role_policy = data.aws_iam_policy_document.karpenter_node_assume_role_policy.json 4 | description = "Karpenter node role for ${var.cluster_config.name} cluster" 5 | } 6 | 7 | data "aws_iam_policy_document" "karpenter_node_assume_role_policy" { 8 | statement { 9 | sid = "EKSNodeAssumeRole" 10 | actions = ["sts:AssumeRole"] 11 | 12 | principals { 13 | type = "Service" 14 | identifiers = ["ec2.${data.aws_partition.current.dns_suffix}"] 15 | } 16 | } 17 | } 18 | 19 | 20 | resource "aws_iam_role_policy_attachment" "karpenter_node_managed_policies" { 21 | for_each = toset([ 22 | "arn:${data.aws_partition.current.partition}:iam::aws:policy/AmazonEKSWorkerNodePolicy", 23 | "arn:${data.aws_partition.current.partition}:iam::aws:policy/AmazonEKS_CNI_Policy", 24 | "arn:${data.aws_partition.current.partition}:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly", 25 | "arn:${data.aws_partition.current.partition}:iam::aws:policy/AmazonSSMManagedInstanceCore", 26 | ]) 27 | 28 | role = aws_iam_role.karpenter_node.id 29 | policy_arn = each.value 30 | } 31 | 32 | resource "aws_iam_instance_profile" "karpenter_node" { 33 | name = aws_iam_role.karpenter_node.name 34 | role = aws_iam_role.karpenter_node.name 35 | } 36 | -------------------------------------------------------------------------------- /modules/karpenter/outputs.tf: -------------------------------------------------------------------------------- 1 | output "node_role_arn" { 2 | value = aws_iam_role.karpenter_node.arn 3 | } 4 | -------------------------------------------------------------------------------- /modules/karpenter/variables.tf: -------------------------------------------------------------------------------- 1 | variable "cluster_config" { 2 | description = "EKS cluster config object" 3 | type = object({ 4 | name = string 5 | arn = string 6 | private_subnet_ids = map(string) 7 | iam_role_name_prefix = string 8 | iam_policy_name_prefix = string 9 | fargate_execution_role_arn = string 10 | }) 11 | } 12 | 13 | variable "oidc_config" { 14 | description = "OIDC config object" 15 | type = object({ 16 | url = string 17 | arn = string 18 | }) 19 | } 20 | 21 | variable "v1beta" { 22 | description = "Enable controller policy for v1beta resources (Karpenter >= 0.32.*)" 23 | type = bool 24 | default = true 25 | } 26 | 27 | variable "v1" { 28 | description = "Enable controller policy for v1 resources (Karpenter >= 1.*)" 29 | type = bool 30 | default = true 31 | } 32 | 33 | variable "additional_node_role_arns" { 34 | description = <<-EOF 35 | Additional Node Role ARNS that karpenter should manage 36 | 37 | This can be used where karpenter is using existing node 38 | roles, and you want to transition to the namespaced role 39 | created by this module 40 | EOF 41 | type = list(string) 42 | default = [] 43 | } 44 | -------------------------------------------------------------------------------- /modules/karpenter/versions.tf: -------------------------------------------------------------------------------- 1 | terraform { 2 | required_version = ">= 1.0" 3 | 4 | required_providers { 5 | aws = { 6 | source = "hashicorp/aws" 7 | version = ">= 4.47.0" 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /modules/vpc/README.md: -------------------------------------------------------------------------------- 1 | # VPC Module 2 | 3 | This module provisions an AWS VPC network that can be used to run EKS clusters. 4 | 5 | ## Usage 6 | 7 | ```hcl 8 | provider "aws" { 9 | region = "us-east-1" 10 | } 11 | 12 | module "vpc" { 13 | source = "cookpad/eks/aws//modules/vpc" 14 | 15 | name = "us-east-1" 16 | cidr_block = "10.0.0.0/16" 17 | availability_zones = ["us-east-1a", "us-east-1b", "us-east-1c"] 18 | } 19 | ``` 20 | 21 | This configuration will cause 6 subnets to be launched in the 3 chosen 22 | availability zones. 23 | 24 | 3 smaller "public" subnets, that can be used for external ingress etc. And 25 | 3 larger subnets that will be used for the Pod network, internal ingress and 26 | worker nodes. 27 | 28 | In this example the following subnets would be created: 29 | 30 | | zone | public | private | 31 | |--------------|---------------|----------------| 32 | | `us-east-1a` | `10.0.0.0/22` | `10.0.32.0/19` | 33 | | `us-east-1b` | `10.0.4.0/22` | `10.0.64.0/19` | 34 | | `us-east-1b` | `10.0.8.0/22` | `10.0.96.0/19` | 35 | 36 | This module outputs a [config object](./outputs.tf) that may be used to configure 37 | the cluster module's `vpc_config` variable. 38 | 39 | e.g: 40 | ```hcl 41 | module "network" { 42 | source = "cookpad/eks/aws//modules/vpc" 43 | 44 | name = "us-west-2" 45 | cidr_block = "10.5.0.0/16" 46 | availability_zones = ["us-west-2a", "us-west-2b", "us-west-2c"] 47 | } 48 | 49 | module "sal" { 50 | source = "cookpad/eks/aws" 51 | 52 | name = "sal-9000" 53 | vpc_config = module.network.config 54 | } 55 | ``` 56 | 57 | ## Features 58 | 59 | As well as configuring the subnets and route table of the provisioned VPC, this 60 | module also provisions internet and NAT gateways, to provide internet access to 61 | nodes running in all subnets. 62 | 63 | ## Restrictions 64 | 65 | In order to run an EKS cluster you must create subnets in at least 3 availability 66 | zones. 67 | 68 | Because of the way this module subdivides `cidr_block` it can only accommodate 69 | up to 7 subnet pairs. 70 | 71 | The size of each subnet is relative to the CIDR block chosen for the VPC. 72 | -------------------------------------------------------------------------------- /modules/vpc/outputs.tf: -------------------------------------------------------------------------------- 1 | output "config" { 2 | value = { 3 | vpc_id = aws_vpc.network.id 4 | public_subnet_ids = { for az, subnet in aws_subnet.public : az => subnet.id } 5 | private_subnet_ids = { for az, subnet in aws_subnet.private : az => subnet.id } 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /modules/vpc/providers.tf: -------------------------------------------------------------------------------- 1 | terraform { 2 | required_providers { 3 | aws = { 4 | source = "hashicorp/aws" 5 | version = ">= 3.49.0" 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /modules/vpc/subnets.tf: -------------------------------------------------------------------------------- 1 | locals { 2 | az_subnet_numbers = zipmap(var.availability_zones, range(0, length(var.availability_zones))) 3 | } 4 | 5 | resource "aws_subnet" "public" { 6 | for_each = local.az_subnet_numbers 7 | 8 | availability_zone = each.key 9 | cidr_block = cidrsubnet(var.cidr_block, 6, each.value) 10 | vpc_id = aws_vpc.network.id 11 | map_public_ip_on_launch = true 12 | 13 | tags = { 14 | Name = "${var.name}-public-${each.key}" 15 | "kubernetes.io/role/elb" = "1" 16 | "kubernetes.io/role/alb-ingress" = "1" 17 | } 18 | } 19 | 20 | resource "aws_route_table_association" "public" { 21 | for_each = aws_subnet.public 22 | subnet_id = each.value.id 23 | route_table_id = aws_route_table.public.id 24 | } 25 | 26 | # Private subnets 27 | resource "aws_subnet" "private" { 28 | for_each = local.az_subnet_numbers 29 | 30 | availability_zone = each.key 31 | cidr_block = cidrsubnet(var.cidr_block, 3, each.value + 1) 32 | vpc_id = aws_vpc.network.id 33 | map_public_ip_on_launch = false 34 | 35 | tags = { 36 | Name = "${var.name}-private-${each.key}" 37 | "kubernetes.io/role/internal-elb" = "1" 38 | "kubernetes.io/role/alb-ingress" = "1" 39 | } 40 | } 41 | 42 | resource "aws_route_table_association" "private" { 43 | for_each = aws_subnet.private 44 | subnet_id = each.value.id 45 | route_table_id = aws_default_route_table.private.id 46 | } 47 | -------------------------------------------------------------------------------- /modules/vpc/variables.tf: -------------------------------------------------------------------------------- 1 | variable "name" { 2 | type = string 3 | description = "A name for this network." 4 | } 5 | 6 | variable "cidr_block" { 7 | type = string 8 | description = "The CIDR block for the VPC." 9 | } 10 | 11 | variable "availability_zones" { 12 | description = "The availability zones to create subnets in" 13 | } 14 | -------------------------------------------------------------------------------- /modules/vpc/vpc.tf: -------------------------------------------------------------------------------- 1 | resource "aws_vpc" "network" { 2 | cidr_block = var.cidr_block 3 | enable_dns_hostnames = true 4 | tags = { 5 | Name = var.name 6 | } 7 | } 8 | 9 | # Internet gateway 10 | resource "aws_internet_gateway" "gateway" { 11 | vpc_id = aws_vpc.network.id 12 | 13 | tags = { 14 | Name = var.name 15 | } 16 | } 17 | 18 | # NAT gateway 19 | resource "aws_eip" "nat_gateway" { 20 | vpc = true 21 | depends_on = [aws_internet_gateway.gateway] 22 | 23 | tags = { 24 | Name = "${var.name}-nat-gateway" 25 | } 26 | } 27 | 28 | resource "aws_nat_gateway" "nat_gateway" { 29 | allocation_id = aws_eip.nat_gateway.id 30 | subnet_id = aws_subnet.public[var.availability_zones[0]].id 31 | 32 | tags = { 33 | Name = var.name 34 | } 35 | } 36 | 37 | resource "aws_route_table" "public" { 38 | vpc_id = aws_vpc.network.id 39 | 40 | tags = { 41 | Name = "${var.name}-public" 42 | } 43 | } 44 | 45 | resource "aws_route" "internet-gateway" { 46 | route_table_id = aws_route_table.public.id 47 | destination_cidr_block = "0.0.0.0/0" 48 | gateway_id = aws_internet_gateway.gateway.id 49 | } 50 | 51 | resource "aws_default_route_table" "private" { 52 | default_route_table_id = aws_vpc.network.default_route_table_id 53 | 54 | tags = { 55 | Name = "${var.name}-private" 56 | } 57 | } 58 | 59 | resource "aws_route" "nat-gateway" { 60 | route_table_id = aws_default_route_table.private.id 61 | destination_cidr_block = "0.0.0.0/0" 62 | nat_gateway_id = aws_nat_gateway.nat_gateway.id 63 | } 64 | -------------------------------------------------------------------------------- /outputs.tf: -------------------------------------------------------------------------------- 1 | locals { 2 | config = { 3 | name = aws_eks_cluster.control_plane.name 4 | endpoint = aws_eks_cluster.control_plane.endpoint 5 | arn = aws_eks_cluster.control_plane.arn 6 | ca_data = aws_eks_cluster.control_plane.certificate_authority[0].data 7 | vpc_id = var.vpc_config.vpc_id 8 | private_subnet_ids = var.vpc_config.private_subnet_ids 9 | node_security_group = aws_eks_cluster.control_plane.vpc_config.0.cluster_security_group_id 10 | tags = var.tags 11 | iam_role_name_prefix = var.iam_role_name_prefix 12 | iam_policy_name_prefix = var.iam_policy_name_prefix 13 | fargate_execution_role_arn = aws_iam_role.fargate.arn 14 | } 15 | } 16 | 17 | output "config" { 18 | value = local.config 19 | } 20 | 21 | output "oidc_config" { 22 | value = { 23 | url = aws_iam_openid_connect_provider.cluster_oidc.url 24 | arn = aws_iam_openid_connect_provider.cluster_oidc.arn 25 | condition = "${replace(aws_iam_openid_connect_provider.cluster_oidc.url, "https://", "")}:sub" 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /required_providers.tf: -------------------------------------------------------------------------------- 1 | terraform { 2 | required_version = ">= 1.0" 3 | 4 | required_providers { 5 | aws = { 6 | source = "hashicorp/aws" 7 | version = ">= 4.47.0" 8 | } 9 | 10 | kubernetes = { 11 | source = "hashicorp/kubernetes" 12 | version = ">= 2.10" 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /scripts/create_github_releases/README.md: -------------------------------------------------------------------------------- 1 | # Create new Github Releases 2 | 3 | This tiny script enforces the current [release policy](../../RELEASING.md) to create a new GitHub release. 4 | 5 | ## Usage 6 | 7 | ``` 8 | go run main.go 9 | ``` 10 | -------------------------------------------------------------------------------- /scripts/create_github_releases/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/cookpad/terraform-aws-eks/scripts/create_github_releases 2 | 3 | go 1.16 4 | 5 | require ( 6 | github.com/google/go-cmp v0.5.6 7 | github.com/pkg/errors v0.9.1 8 | ) 9 | -------------------------------------------------------------------------------- /scripts/create_github_releases/go.sum: -------------------------------------------------------------------------------- 1 | github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ= 2 | github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= 3 | github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= 4 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 5 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= 6 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= 7 | -------------------------------------------------------------------------------- /scripts/create_github_releases/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "log" 6 | "net/url" 7 | "os" 8 | "regexp" 9 | "strings" 10 | 11 | "github.com/pkg/errors" 12 | ) 13 | 14 | const repositoryURL = "https://github.com/cookpad/terraform-aws-eks" 15 | 16 | var ( 17 | // tag must specify major.minor.patch or major.minor.patch-rc# 18 | // (e.g. 1.12.1, 1.12.1-rc1) 19 | validTag = regexp.MustCompile(`^\d+\.\d+\.\d+(-rc\d+)?$`) 20 | // target must specify release branch for releasing 21 | // or main for release candidates 22 | validTarget = regexp.MustCompile(`^(release-\d+-\d+|main)$`) 23 | // true or false 24 | validPrerelease = regexp.MustCompile(`^(true|false)$`) 25 | // yes or no 26 | validYesNo = regexp.MustCompile(`^(yes|no)$`) 27 | ) 28 | 29 | func scanInputFromStdio(policy *regexp.Regexp, format *string, question, errMsg string) error { 30 | fmt.Println(question) 31 | fmt.Print("> ") 32 | fmt.Scanf("%s", format) 33 | 34 | // validate policy 35 | if !policy.Match([]byte(*format)) { 36 | return errors.New(errMsg) 37 | } 38 | return nil 39 | } 40 | 41 | // validateRelease validates policies for releases 42 | // used for release candidates. Return target branch name 43 | // based on the specified tag name. 44 | func validateRelease(tag, preRelease string) (string, error) { 45 | if strings.Contains(tag, "-rc") { 46 | // release candidates must be released as prereleases 47 | if preRelease == "false" { 48 | return "", errors.New("[ERROR] Prerelease must be true for release candidates") 49 | } 50 | // release candidates must use main branch as a target 51 | return "main", nil 52 | } else { 53 | versions := strings.Split(tag, ".") 54 | // naming convention for release branch is release-{major}-{minor} 55 | return fmt.Sprintf("release-%s-%s", versions[0], versions[1]), nil 56 | } 57 | } 58 | 59 | func main() { 60 | fmt.Println("Start creating new GitHub Release interactively!") 61 | 62 | var tag, target, preRelease, confirm string 63 | 64 | if err := scanInputFromStdio( 65 | validTag, 66 | &tag, 67 | "Q. Input version tag with the format {major}.{minor}.{patch} or {major}.{minor}.{patch}-{rc#} (e.g. 1.19.0 or 1.19.0-rc1)", 68 | "[ERROR] Version tag must follow the format {major}.{minor}.{patch} or {major}.{minor}.{patch}-{rc#}", 69 | ); err != nil { 70 | log.Fatalln(err.Error()) 71 | } 72 | 73 | if err := scanInputFromStdio( 74 | validPrerelease, 75 | &preRelease, 76 | "Q. Is prerelease? (Set true for release candidates) (e.g. true or false)", 77 | "[ERROR] Prerelease must be true or false", 78 | ); err != nil { 79 | log.Fatalln(err.Error()) 80 | } 81 | 82 | target, err := validateRelease(tag, preRelease) 83 | if err != nil { 84 | log.Fatal(err.Error()) 85 | } 86 | 87 | title := fmt.Sprintf("Release %s", tag) 88 | 89 | // Check inputs 90 | fmt.Println("# Check input to be used for a GitHub Release") 91 | fmt.Println("tag:", tag) 92 | fmt.Println("target branch:", target) 93 | fmt.Println("pre release:", preRelease) 94 | fmt.Println("title:", title) 95 | fmt.Println() 96 | 97 | if err := scanInputFromStdio( 98 | validYesNo, 99 | &confirm, 100 | "Are these inputs correct? (yes or no)", 101 | "[ERROR] Invalid confirmation", 102 | ); err != nil { 103 | log.Fatalln(err.Error()) 104 | } 105 | if confirm != "yes" { 106 | fmt.Println("Canceled interactive GitHub release creation.") 107 | os.Exit(0) 108 | } 109 | 110 | // https://docs.github.com/en/repositories/releasing-projects-on-github/automation-for-release-forms-with-query-parameters 111 | url, err := url.Parse( 112 | fmt.Sprintf("%s/releases/new?tag=%s&target=%s&title=%s&prerelease=%s", repositoryURL, tag, target, url.QueryEscape(title), preRelease), 113 | ) 114 | if err != nil { 115 | log.Fatal(err) 116 | } 117 | 118 | fmt.Println("Input for GitHub Releases are successfully passed. Please follow the steps below\n") 119 | fmt.Printf("Step 1: Access %s\n", url.String()) 120 | fmt.Println("Step 2: Click 'Auto-generate release notes' button on your GitHub Release page and check the generated contents before you publish this release.\n") 121 | } 122 | -------------------------------------------------------------------------------- /scripts/create_github_releases/main_test.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/google/go-cmp/cmp" 7 | "github.com/pkg/errors" 8 | ) 9 | 10 | type input struct { 11 | tag string 12 | preRelease string 13 | } 14 | 15 | type expect struct { 16 | target string 17 | err error 18 | } 19 | 20 | func TestMain_validateRelease(t *testing.T) { 21 | t.Parallel() 22 | 23 | tests := map[string]struct { 24 | input *input 25 | expect *expect 26 | }{ 27 | "release branch 1.19.0": { 28 | input: &input{tag: "1.19.0", preRelease: "true"}, 29 | expect: &expect{target: "release-1-19", err: nil}, 30 | }, 31 | "release branch 1.19.0 with false prerelease flag": { 32 | input: &input{tag: "1.19.0", preRelease: "false"}, 33 | expect: &expect{target: "release-1-19", err: nil}, 34 | }, 35 | "release candidate 1": { 36 | input: &input{tag: "1.19.0-rc1", preRelease: "true"}, 37 | expect: &expect{target: "main", err: nil}, 38 | }, 39 | "release candidate 1 with false prerelease flag": { 40 | input: &input{tag: "1.19.0-rc1", preRelease: "false"}, 41 | expect: &expect{target: "", err: errors.New("[ERROR] Prerelease must be true for release candidates")}, 42 | }, 43 | } 44 | 45 | for name, test := range tests { 46 | t.Run(name, func(t *testing.T) { 47 | t.Parallel() 48 | 49 | actual, err := validateRelease(test.input.tag, test.input.preRelease) 50 | if test.expect.err == nil && err != nil { 51 | t.Fatalf("err=%#v\n", err) 52 | } 53 | 54 | if diff := cmp.Diff(test.expect.target, actual); diff != "" { 55 | t.Errorf("\n(-expect, +actual)%s\n", diff) 56 | } 57 | 58 | }) 59 | } 60 | 61 | } 62 | -------------------------------------------------------------------------------- /security_groups.tf: -------------------------------------------------------------------------------- 1 | /* 2 | Control Plane Security Group 3 | */ 4 | 5 | resource "aws_security_group" "control_plane" { 6 | count = var.legacy_security_groups ? 1 : 0 7 | 8 | name = "eks-control-plane-${var.name}" 9 | description = "Cluster communication with worker nodes" 10 | vpc_id = var.vpc_config.vpc_id 11 | 12 | egress { 13 | from_port = 0 14 | to_port = 0 15 | protocol = "-1" 16 | cidr_blocks = ["0.0.0.0/0"] 17 | } 18 | 19 | tags = { 20 | Name = "eks-control-plane-${var.name}" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /test/cluster_test.go: -------------------------------------------------------------------------------- 1 | package test 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "os" 7 | "strings" 8 | "testing" 9 | "time" 10 | 11 | "github.com/gruntwork-io/terratest/modules/helm" 12 | "github.com/gruntwork-io/terratest/modules/k8s" 13 | "github.com/gruntwork-io/terratest/modules/random" 14 | "github.com/gruntwork-io/terratest/modules/terraform" 15 | test_structure "github.com/gruntwork-io/terratest/modules/test-structure" 16 | 17 | "github.com/stretchr/testify/assert" 18 | "github.com/stretchr/testify/require" 19 | 20 | authv1 "k8s.io/api/authorization/v1" 21 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 22 | ) 23 | 24 | func TestTerraformAwsEksCluster(t *testing.T) { 25 | t.Parallel() 26 | 27 | environmentDir := "../examples/cluster/environment" 28 | workingDir := "../examples/cluster" 29 | 30 | // At the end of the test, run `terraform destroy` to clean up any resources that were created. 31 | defer test_structure.RunTestStage(t, "cleanup_terraform", func() { 32 | cleanupTerraform(t, workingDir) 33 | }) 34 | 35 | test_structure.RunTestStage(t, "deploy_cluster", func() { 36 | uniqueId := random.UniqueId() 37 | clusterName := fmt.Sprintf("terraform-aws-eks-testing-%s", uniqueId) 38 | deployTerraform(t, environmentDir, map[string]interface{}{}) 39 | deployTerraform(t, workingDir, map[string]interface{}{ 40 | "cluster_name": clusterName, 41 | }) 42 | terraformOptions := test_structure.LoadTerraformOptions(t, workingDir) 43 | clusterName = terraform.Output(t, terraformOptions, "cluster_name") 44 | kubeconfig := writeKubeconfig(t, clusterName) 45 | defer os.Remove(kubeconfig) 46 | kubectlOptions := k8s.NewKubectlOptions("", kubeconfig, "default") 47 | waitForCluster(t, kubectlOptions) 48 | }) 49 | 50 | test_structure.RunTestStage(t, "install_karpenter", func() { 51 | terraformOptions := test_structure.LoadTerraformOptions(t, workingDir) 52 | clusterName := terraform.Output(t, terraformOptions, "cluster_name") 53 | sgName := terraform.Output(t, terraformOptions, "node_security_group_name") 54 | kubeconfig := writeKubeconfig(t, clusterName) 55 | defer os.Remove(kubeconfig) 56 | installKarpenter(t, kubeconfig, clusterName, sgName) 57 | }) 58 | 59 | test_structure.RunTestStage(t, "validate_cluster", func() { 60 | terraformOptions := test_structure.LoadTerraformOptions(t, workingDir) 61 | kubeconfig := writeKubeconfig(t, terraform.Output(t, terraformOptions, "cluster_name")) 62 | defer os.Remove(kubeconfig) 63 | validateSecretsBehaviour(t, kubeconfig) 64 | validateDNS(t, kubeconfig) 65 | admin_kubeconfig := writeKubeconfig(t, terraform.Output(t, terraformOptions, "cluster_name"), terraform.Output(t, terraformOptions, "test_role_arn")) 66 | defer os.Remove(admin_kubeconfig) 67 | validateAdminRole(t, admin_kubeconfig) 68 | validateKubeBench(t, kubeconfig) 69 | validateStorage(t, kubeconfig) 70 | }) 71 | } 72 | 73 | func installKarpenter(t *testing.T, kubeconfig, clusterName, sgName string) { 74 | kubectlOptions := k8s.NewKubectlOptions("", kubeconfig, "karpenter") 75 | helmOptions := helm.Options{ 76 | KubectlOptions: kubectlOptions, 77 | ExtraArgs: map[string][]string{ 78 | "upgrade": []string{"--create-namespace", "--version", "1.0.5", "--force"}, 79 | }, 80 | } 81 | helm.Upgrade(t, &helmOptions, "oci://public.ecr.aws/karpenter/karpenter-crd", "karpenter-crd") 82 | helmOptions = helm.Options{ 83 | SetValues: map[string]string{ 84 | "serviceAccount.annotations.eks\\.amazonaws\\.com/role-arn": "arn:aws:iam::214219211678:role/Karpenter-" + clusterName, 85 | "settings.clusterName": clusterName, 86 | "settings.interruptionQueueName": "Karpenter-" + clusterName, 87 | "controller.resources.requests.cpu": "1", 88 | "controller.resources.requests.memory": "1Gi", 89 | "controller.resources.limits.cpu": "1", 90 | "controller.resources.limits.memory": "1Gi", 91 | }, 92 | KubectlOptions: kubectlOptions, 93 | ExtraArgs: map[string][]string{ 94 | "upgrade": []string{"--create-namespace", "--version", "1.0.5"}, 95 | }, 96 | } 97 | helm.Upgrade(t, &helmOptions, "oci://public.ecr.aws/karpenter/karpenter", "karpenter") 98 | WaitUntilPodsAvailable(t, kubectlOptions, metav1.ListOptions{LabelSelector: "app.kubernetes.io/name=karpenter"}, 2, 30, 6*time.Second) 99 | provisionerManifest := fmt.Sprintf(KARPENTER_PROVISIONER, sgName, clusterName) 100 | k8s.KubectlApplyFromString(t, kubectlOptions, provisionerManifest) 101 | } 102 | 103 | const KARPENTER_PROVISIONER = `--- 104 | apiVersion: karpenter.sh/v1 105 | kind: NodePool 106 | metadata: 107 | name: default 108 | spec: 109 | template: 110 | spec: 111 | nodeClassRef: 112 | group: karpenter.k8s.aws 113 | kind: EC2NodeClass 114 | name: default 115 | requirements: 116 | - key: karpenter.k8s.aws/instance-family 117 | operator: In 118 | values: [t3] 119 | - key: karpenter.sh/capacity-type 120 | operator: In 121 | values: ["spot"] 122 | - key: karpenter.k8s.aws/instance-size 123 | operator: In 124 | values: [small, medium, large] 125 | --- 126 | apiVersion: karpenter.k8s.aws/v1 127 | kind: EC2NodeClass 128 | metadata: 129 | name: default 130 | spec: 131 | amiSelectorTerms: 132 | - alias: bottlerocket@latest 133 | subnetSelectorTerms: 134 | - tags: 135 | Name: terraform-aws-eks-test-environment-private* 136 | securityGroupSelectorTerms: 137 | - tags: 138 | Name: %s 139 | instanceProfile: 140 | KarpenterNode-%s 141 | ` 142 | 143 | func validateAdminRole(t *testing.T, kubeconfig string) { 144 | kubectlOptions := k8s.NewKubectlOptions("", kubeconfig, "default") 145 | k8s.CanIDo(t, kubectlOptions, authv1.ResourceAttributes{ 146 | Namespace: "*", 147 | Verb: "*", 148 | Group: "*", 149 | Version: "*", 150 | }) 151 | } 152 | 153 | func validateSecretsBehaviour(t *testing.T, kubeconfig string) { 154 | namespace := strings.ToLower(random.UniqueId()) 155 | kubectlOptions := k8s.NewKubectlOptions("", kubeconfig, namespace) 156 | secretManifest := fmt.Sprintf(EXAMPLE_SECRET, namespace, namespace) 157 | defer k8s.DeleteNamespace(t, kubectlOptions, namespace) 158 | k8s.KubectlApplyFromString(t, kubectlOptions, secretManifest) 159 | secret := k8s.GetSecret(t, kubectlOptions, "keys-to-the-kingdom") 160 | password := secret.Data["password"] 161 | assert.Equal(t, "Open Sesame", string(password)) 162 | } 163 | 164 | const EXAMPLE_SECRET = `--- 165 | apiVersion: v1 166 | kind: Namespace 167 | metadata: 168 | name: %s 169 | --- 170 | apiVersion: v1 171 | kind: Secret 172 | metadata: 173 | name: keys-to-the-kingdom 174 | namespace: %s 175 | type: Opaque 176 | data: 177 | password: T3BlbiBTZXNhbWU= 178 | ` 179 | 180 | func validateDNS(t *testing.T, kubeconfig string) { 181 | nameSuffix := strings.ToLower(random.UniqueId()) 182 | kubectlOptions := k8s.NewKubectlOptions("", kubeconfig, "default") 183 | test := fmt.Sprintf(DNS_TEST_JOB, nameSuffix) 184 | defer k8s.KubectlDeleteFromString(t, kubectlOptions, test) 185 | k8s.KubectlApplyFromString(t, kubectlOptions, test) 186 | WaitUntilPodsSucceeded(t, kubectlOptions, metav1.ListOptions{LabelSelector: "job-name=nslookup-" + nameSuffix}, 1, 30, 10*time.Second) 187 | } 188 | 189 | const DNS_TEST_JOB = `--- 190 | apiVersion: batch/v1 191 | kind: Job 192 | metadata: 193 | name: nslookup-%s 194 | namespace: default 195 | spec: 196 | template: 197 | spec: 198 | containers: 199 | - name: dnsutils 200 | image: gcr.io/kubernetes-e2e-test-images/dnsutils:1.3 201 | command: 202 | - nslookup 203 | - kubernetes.default 204 | imagePullPolicy: IfNotPresent 205 | restartPolicy: Never 206 | tolerations: 207 | - key: CriticalAddonsOnly 208 | operator: Exists 209 | backoffLimit: 4 210 | ` 211 | 212 | func validateStorage(t *testing.T, kubeconfig string) { 213 | // Generate some example workload 214 | namespace := strings.ToLower(random.UniqueId()) 215 | kubectlOptions := k8s.NewKubectlOptions("", kubeconfig, namespace) 216 | workload := fmt.Sprintf(EXAMPLE_STORAGE_WORKLOAD, namespace, namespace, namespace) 217 | defer k8s.DeleteNamespace(t, kubectlOptions, namespace) 218 | k8s.KubectlApplyFromString(t, kubectlOptions, workload) 219 | WaitUntilPodsSucceeded(t, kubectlOptions, metav1.ListOptions{LabelSelector: "app=storage-test-workload"}, 1, 30, 10*time.Second) 220 | } 221 | 222 | const EXAMPLE_STORAGE_WORKLOAD = `--- 223 | apiVersion: v1 224 | kind: Namespace 225 | metadata: 226 | name: %s 227 | --- 228 | apiVersion: v1 229 | kind: PersistentVolumeClaim 230 | metadata: 231 | name: ebs-claim 232 | namespace: %s 233 | spec: 234 | storageClassName: gp2 235 | accessModes: 236 | - ReadWriteOnce 237 | resources: 238 | requests: 239 | storage: 1Gi 240 | --- 241 | apiVersion: batch/v1 242 | kind: Job 243 | metadata: 244 | name: test-storage-workload 245 | namespace: %s 246 | spec: 247 | template: 248 | metadata: 249 | labels: 250 | app: storage-test-workload 251 | spec: 252 | restartPolicy: OnFailure 253 | containers: 254 | - name: app 255 | image: alpine 256 | command: ["/bin/sh"] 257 | args: ["-c", "echo $(date -u) >> /data/out.txt && cat /data/out.txt"] 258 | volumeMounts: 259 | - name: persistent-storage 260 | mountPath: /data 261 | volumes: 262 | - name: persistent-storage 263 | persistentVolumeClaim: 264 | claimName: ebs-claim 265 | ` 266 | 267 | func validateKubeBench(t *testing.T, kubeconfig string) { 268 | kubectlOptions := k8s.NewKubectlOptions("", kubeconfig, "kube-bench") 269 | defer k8s.DeleteNamespace(t, kubectlOptions, "kube-bench") 270 | k8s.KubectlApplyFromString(t, kubectlOptions, KUBEBENCH_MANIFEST) 271 | WaitUntilPodsSucceeded(t, kubectlOptions, metav1.ListOptions{LabelSelector: "app=kube-bench"}, 1, 30, 5*time.Second) 272 | output, err := k8s.RunKubectlAndGetOutputE(t, kubectlOptions, "logs", "-l", "app=kube-bench") 273 | require.NoError(t, err) 274 | resultWrapper := KubeBenchResult{} 275 | err = json.Unmarshal([]byte(output), &resultWrapper) 276 | require.NoError(t, err) 277 | result := resultWrapper.Totals 278 | if !assert.Equal(t, result.TotalFail, 0) { 279 | fmt.Printf(`unexpected total_fail: %d`, result.TotalFail) 280 | } 281 | if !assert.Equal(t, result.TotalWarn, 0) { 282 | fmt.Printf(`unexpected total_warn: %d`, result.TotalWarn) 283 | } 284 | } 285 | 286 | type KubeBenchResult struct { 287 | Totals KubeBenchResultTotals `json:"Totals"` 288 | } 289 | 290 | type KubeBenchResultTotals struct { 291 | TotalPass int `json:"total_pass"` 292 | TotalFail int `json:"total_fail"` 293 | TotalWarn int `json:"total_warn"` 294 | TotalInfo int `json:"total_info"` 295 | } 296 | 297 | //Skipped tests: 298 | //3.2.8: --hostname-override is used by bottlerocket to have hostname match the dns name of the ec2 instance, this is appropriate and not a security issue 299 | //3.2.9: eventRecordQPS is 50 by default, and can be overidden as required by users 300 | //3.2.11: See https://github.com/bottlerocket-os/bottlerocket/issues/3506 - the test checks for the presence of RotateKubeletServerCertificate feature gate, but this is set by default since k8s 1.12 so is not needed 301 | //3.3.1: Manual test: bottlerocket is a container-optimized OS so we pass this control 302 | 303 | const KUBEBENCH_MANIFEST = `--- 304 | apiVersion: v1 305 | kind: Namespace 306 | metadata: 307 | name: kube-bench 308 | --- 309 | apiVersion: batch/v1 310 | kind: Job 311 | metadata: 312 | name: kube-bench 313 | namespace: kube-bench 314 | spec: 315 | template: 316 | metadata: 317 | labels: 318 | app: kube-bench 319 | spec: 320 | hostPID: true 321 | containers: 322 | - name: kube-bench 323 | image: aquasec/kube-bench:v0.8.0 324 | command: ["kube-bench", "run", "--targets=node", "--benchmark", "eks-1.2.0", "--json", "--skip", "3.2.8,3.2.9,3.2.11,3.3.1"] 325 | volumeMounts: 326 | - name: var-lib-kubelet 327 | mountPath: /var/lib/kubelet 328 | readOnly: true 329 | - name: etc-systemd 330 | mountPath: /etc/systemd 331 | readOnly: true 332 | - name: etc-kubernetes 333 | mountPath: /etc/kubernetes 334 | readOnly: true 335 | restartPolicy: Never 336 | volumes: 337 | - name: var-lib-kubelet 338 | hostPath: 339 | path: "/var/lib/kubelet" 340 | - name: etc-systemd 341 | hostPath: 342 | path: "/etc/systemd" 343 | - name: etc-kubernetes 344 | hostPath: 345 | path: "/etc/kubernetes" 346 | tolerations: 347 | - key: nvidia.com/gpu 348 | operator: Exists 349 | ` 350 | -------------------------------------------------------------------------------- /test/common.go: -------------------------------------------------------------------------------- 1 | package test 2 | 3 | import ( 4 | "fmt" 5 | "io/ioutil" 6 | "os" 7 | "testing" 8 | "time" 9 | 10 | "github.com/gruntwork-io/terratest/modules/k8s" 11 | "github.com/gruntwork-io/terratest/modules/logger" 12 | "github.com/gruntwork-io/terratest/modules/retry" 13 | "github.com/gruntwork-io/terratest/modules/shell" 14 | "github.com/gruntwork-io/terratest/modules/terraform" 15 | test_structure "github.com/gruntwork-io/terratest/modules/test-structure" 16 | 17 | "github.com/stretchr/testify/require" 18 | 19 | corev1 "k8s.io/api/core/v1" 20 | metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 21 | ) 22 | 23 | func deployTerraform(t *testing.T, workingDir string, vars map[string]interface{}) { 24 | var terraformOptions *terraform.Options 25 | 26 | if test_structure.IsTestDataPresent(t, test_structure.FormatTestDataPath(workingDir, "TerraformOptions.json")) { 27 | terraformOptions = test_structure.LoadTerraformOptions(t, workingDir) 28 | for k, v := range vars { 29 | if _, ok := terraformOptions.Vars[k]; !ok { 30 | terraformOptions.Vars[k] = v 31 | } 32 | } 33 | } else { 34 | terraformOptions = &terraform.Options{ 35 | // The path to where our Terraform code is located 36 | TerraformDir: workingDir, 37 | Vars: vars, 38 | } 39 | 40 | // Save the Terraform Options struct, so future test stages can use it 41 | test_structure.SaveTerraformOptions(t, workingDir, terraformOptions) 42 | } 43 | 44 | // Run `terraform init` and `terraform apply`. Fail the test if there are any errors. 45 | terraform.InitAndApply(t, terraformOptions) 46 | } 47 | 48 | func cleanupTerraform(t *testing.T, workingDir string) { 49 | terraformOptions := test_structure.LoadTerraformOptions(t, workingDir) 50 | terraformOptions.RetryableTerraformErrors = map[string]string{ 51 | ".*operation error EKS: DeleteFargateProfile.*": "Fargate delete failed", 52 | } 53 | terraformOptions.MaxRetries = 15 54 | terraformOptions.TimeBetweenRetries = 3 * time.Minute 55 | terraform.Destroy(t, terraformOptions) 56 | test_structure.CleanupTestDataFolder(t, workingDir) 57 | } 58 | 59 | func writeKubeconfig(t *testing.T, opts ...string) string { 60 | file, err := ioutil.TempFile(os.TempDir(), "kubeconfig-") 61 | require.NoError(t, err) 62 | args := []string{ 63 | "eks", 64 | "update-kubeconfig", 65 | "--name", opts[0], 66 | "--kubeconfig", file.Name(), 67 | "--region", "us-east-1", 68 | } 69 | if len(opts) > 1 { 70 | args = append(args, "--role-arn", opts[1]) 71 | } 72 | shell.RunCommand(t, shell.Command{ 73 | Command: "aws", 74 | Args: args, 75 | }) 76 | return file.Name() 77 | } 78 | 79 | func waitForCluster(t *testing.T, kubectlOptions *k8s.KubectlOptions) { 80 | maxRetries := 40 81 | sleepBetweenRetries := 10 * time.Second 82 | retry.DoWithRetry(t, "Check that access to the k8s api works", maxRetries, sleepBetweenRetries, func() (string, error) { 83 | // Try an operation on the API to check it works 84 | _, err := k8s.GetServiceAccountE(t, kubectlOptions, "default") 85 | return "", err 86 | }) 87 | 88 | } 89 | 90 | func WaitUntilPodsAvailableE(t *testing.T, options *k8s.KubectlOptions, filters metav1.ListOptions, desiredCount, retries int, sleepBetweenRetries time.Duration) error { 91 | statusMsg := fmt.Sprintf("Wait for num pods available to match desired count %d.", desiredCount) 92 | message, err := retry.DoWithRetryE( 93 | t, 94 | statusMsg, 95 | retries, 96 | sleepBetweenRetries, 97 | func() (string, error) { 98 | pods, err := k8s.ListPodsE(t, options, filters) 99 | if err != nil { 100 | return "", err 101 | } 102 | if len(pods) != desiredCount { 103 | return "", k8s.DesiredNumberOfPodsNotCreated{Filter: filters, DesiredCount: desiredCount} 104 | } 105 | for _, pod := range pods { 106 | pod, err := k8s.GetPodE(t, options, pod.Name) 107 | if err != nil { 108 | return "", err 109 | } 110 | if !k8s.IsPodAvailable(pod) { 111 | return "", k8s.NewPodNotAvailableError(pod) 112 | } 113 | } 114 | return "Pods are now available", nil 115 | }, 116 | ) 117 | if err != nil { 118 | logger.Logf(t, "Timedout waiting for the desired number of Pods to be available: %s", err) 119 | return err 120 | } 121 | logger.Log(t, message) 122 | return nil 123 | } 124 | 125 | func WaitUntilPodsAvailable(t *testing.T, options *k8s.KubectlOptions, filters metav1.ListOptions, desiredCount, retries int, sleepBetweenRetries time.Duration) { 126 | require.NoError(t, WaitUntilPodsAvailableE(t, options, filters, desiredCount, retries, sleepBetweenRetries)) 127 | } 128 | func WaitUntilPodsSucceededE(t *testing.T, options *k8s.KubectlOptions, filters metav1.ListOptions, desiredCount, retries int, sleepBetweenRetries time.Duration) error { 129 | statusMsg := "Wait for pods to Succeed." 130 | message, err := retry.DoWithRetryE( 131 | t, 132 | statusMsg, 133 | retries, 134 | sleepBetweenRetries, 135 | func() (string, error) { 136 | pods, err := k8s.ListPodsE(t, options, filters) 137 | if err != nil { 138 | return "", err 139 | } 140 | if len(pods) != desiredCount { 141 | return "", k8s.DesiredNumberOfPodsNotCreated{Filter: filters, DesiredCount: desiredCount} 142 | } 143 | for _, pod := range pods { 144 | pod, err := k8s.GetPodE(t, options, pod.Name) 145 | if err != nil { 146 | return "", err 147 | } 148 | if pod.Status.Phase != corev1.PodSucceeded { 149 | return "", k8s.NewPodNotAvailableError(pod) 150 | } 151 | } 152 | return "Pods have now Succeeded", nil 153 | }, 154 | ) 155 | if err != nil { 156 | logger.Logf(t, "Timedout waiting for the desired number of Pods to Succeed: %s", err) 157 | return err 158 | } 159 | logger.Log(t, message) 160 | return nil 161 | } 162 | 163 | func WaitUntilPodsSucceeded(t *testing.T, options *k8s.KubectlOptions, filters metav1.ListOptions, desiredCount, retries int, sleepBetweenRetries time.Duration) { 164 | require.NoError(t, WaitUntilPodsSucceededE(t, options, filters, desiredCount, retries, sleepBetweenRetries)) 165 | } 166 | -------------------------------------------------------------------------------- /test/go.mod: -------------------------------------------------------------------------------- 1 | module github.com/cookpad/terraform-aws-eks 2 | 3 | go 1.24.1 4 | 5 | require ( 6 | github.com/gruntwork-io/terratest v0.46.11 7 | github.com/stretchr/testify v1.8.4 8 | k8s.io/api v0.29.2 9 | k8s.io/apimachinery v0.29.2 10 | ) 11 | 12 | require ( 13 | cloud.google.com/go v0.112.0 // indirect 14 | cloud.google.com/go/compute v1.24.0 // indirect 15 | cloud.google.com/go/compute/metadata v0.2.3 // indirect 16 | cloud.google.com/go/iam v1.1.6 // indirect 17 | cloud.google.com/go/storage v1.38.0 // indirect 18 | github.com/BurntSushi/toml v1.3.2 // indirect 19 | github.com/agext/levenshtein v1.2.3 // indirect 20 | github.com/apparentlymart/go-textseg/v15 v15.0.0 // indirect 21 | github.com/aws/aws-sdk-go v1.50.19 // indirect 22 | github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d // indirect 23 | github.com/boombuler/barcode v1.0.1 // indirect 24 | github.com/cpuguy83/go-md2man/v2 v2.0.3 // indirect 25 | github.com/davecgh/go-spew v1.1.1 // indirect 26 | github.com/emicklei/go-restful/v3 v3.11.2 // indirect 27 | github.com/felixge/httpsnoop v1.0.4 // indirect 28 | github.com/ghodss/yaml v1.0.0 // indirect 29 | github.com/go-errors/errors v1.5.1 // indirect 30 | github.com/go-logr/logr v1.4.1 // indirect 31 | github.com/go-logr/stdr v1.2.2 // indirect 32 | github.com/go-openapi/jsonpointer v0.20.2 // indirect 33 | github.com/go-openapi/jsonreference v0.20.4 // indirect 34 | github.com/go-openapi/swag v0.22.9 // indirect 35 | github.com/go-sql-driver/mysql v1.7.1 // indirect 36 | github.com/gogo/protobuf v1.3.2 // indirect 37 | github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect 38 | github.com/golang/protobuf v1.5.3 // indirect 39 | github.com/gonvenience/bunt v1.3.5 // indirect 40 | github.com/gonvenience/neat v1.3.12 // indirect 41 | github.com/gonvenience/term v1.0.2 // indirect 42 | github.com/gonvenience/text v1.0.7 // indirect 43 | github.com/gonvenience/wrap v1.1.2 // indirect 44 | github.com/gonvenience/ytbx v1.4.4 // indirect 45 | github.com/google/gnostic-models v0.6.8 // indirect 46 | github.com/google/gofuzz v1.2.0 // indirect 47 | github.com/google/s2a-go v0.1.7 // indirect 48 | github.com/google/uuid v1.6.0 // indirect 49 | github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect 50 | github.com/googleapis/gax-go/v2 v2.12.1 // indirect 51 | github.com/gruntwork-io/go-commons v0.17.1 // indirect 52 | github.com/hashicorp/errwrap v1.1.0 // indirect 53 | github.com/hashicorp/go-cleanhttp v0.5.2 // indirect 54 | github.com/hashicorp/go-getter v1.7.5 // indirect 55 | github.com/hashicorp/go-multierror v1.1.1 // indirect 56 | github.com/hashicorp/go-safetemp v1.0.0 // indirect 57 | github.com/hashicorp/go-version v1.6.0 // indirect 58 | github.com/hashicorp/hcl/v2 v2.19.1 // indirect 59 | github.com/hashicorp/terraform-json v0.21.0 // indirect 60 | github.com/homeport/dyff v1.6.0 // indirect 61 | github.com/imdario/mergo v0.3.16 // indirect 62 | github.com/jinzhu/copier v0.4.0 // indirect 63 | github.com/jmespath/go-jmespath v0.4.0 // indirect 64 | github.com/josharian/intern v1.0.0 // indirect 65 | github.com/json-iterator/go v1.1.12 // indirect 66 | github.com/klauspost/compress v1.17.6 // indirect 67 | github.com/lucasb-eyer/go-colorful v1.2.0 // indirect 68 | github.com/mailru/easyjson v0.7.7 // indirect 69 | github.com/mattn/go-ciede2000 v0.0.0-20170301095244-782e8c62fec3 // indirect 70 | github.com/mattn/go-isatty v0.0.19 // indirect 71 | github.com/mattn/go-zglob v0.0.4 // indirect 72 | github.com/mitchellh/go-homedir v1.1.0 // indirect 73 | github.com/mitchellh/go-ps v1.0.0 // indirect 74 | github.com/mitchellh/go-testing-interface v1.14.1 // indirect 75 | github.com/mitchellh/go-wordwrap v1.0.1 // indirect 76 | github.com/mitchellh/hashstructure v1.1.0 // indirect 77 | github.com/moby/spdystream v0.2.0 // indirect 78 | github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect 79 | github.com/modern-go/reflect2 v1.0.2 // indirect 80 | github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect 81 | github.com/mxk/go-flowrate v0.0.0-20140419014527-cca7078d478f // indirect 82 | github.com/pmezard/go-difflib v1.0.0 // indirect 83 | github.com/pquerna/otp v1.4.0 // indirect 84 | github.com/russross/blackfriday/v2 v2.1.0 // indirect 85 | github.com/sergi/go-diff v1.3.1 // indirect 86 | github.com/spf13/pflag v1.0.5 // indirect 87 | github.com/texttheater/golang-levenshtein v1.0.1 // indirect 88 | github.com/tmccombs/hcl2json v0.6.1 // indirect 89 | github.com/ulikunitz/xz v0.5.11 // indirect 90 | github.com/urfave/cli/v2 v2.27.1 // indirect 91 | github.com/virtuald/go-ordered-json v0.0.0-20170621173500-b18e6e673d74 // indirect 92 | github.com/xrash/smetrics v0.0.0-20231213231151-1d8dd44e695e // indirect 93 | github.com/zclconf/go-cty v1.14.2 // indirect 94 | go.opencensus.io v0.24.0 // indirect 95 | go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.48.0 // indirect 96 | go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.48.0 // indirect 97 | go.opentelemetry.io/otel v1.23.1 // indirect 98 | go.opentelemetry.io/otel/metric v1.23.1 // indirect 99 | go.opentelemetry.io/otel/trace v1.23.1 // indirect 100 | golang.org/x/crypto v0.36.0 // indirect 101 | golang.org/x/exp v0.0.0-20240213143201-ec583247a57a // indirect 102 | golang.org/x/net v0.38.0 // indirect 103 | golang.org/x/oauth2 v0.17.0 // indirect 104 | golang.org/x/sync v0.12.0 // indirect 105 | golang.org/x/sys v0.31.0 // indirect 106 | golang.org/x/term v0.30.0 // indirect 107 | golang.org/x/text v0.23.0 // indirect 108 | golang.org/x/time v0.5.0 // indirect 109 | google.golang.org/api v0.165.0 // indirect 110 | google.golang.org/appengine v1.6.8 // indirect 111 | google.golang.org/genproto v0.0.0-20240213162025-012b6fc9bca9 // indirect 112 | google.golang.org/genproto/googleapis/api v0.0.0-20240213162025-012b6fc9bca9 // indirect 113 | google.golang.org/genproto/googleapis/rpc v0.0.0-20240213162025-012b6fc9bca9 // indirect 114 | google.golang.org/grpc v1.61.1 // indirect 115 | google.golang.org/protobuf v1.33.0 // indirect 116 | gopkg.in/inf.v0 v0.9.1 // indirect 117 | gopkg.in/yaml.v2 v2.4.0 // indirect 118 | gopkg.in/yaml.v3 v3.0.1 // indirect 119 | k8s.io/client-go v0.29.2 // indirect 120 | k8s.io/klog/v2 v2.120.1 // indirect 121 | k8s.io/kube-openapi v0.0.0-20240209001042-7a0d5b415232 // indirect 122 | k8s.io/utils v0.0.0-20240102154912-e7106e64919e // indirect 123 | sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect 124 | sigs.k8s.io/structured-merge-diff/v4 v4.4.1 // indirect 125 | sigs.k8s.io/yaml v1.4.0 // indirect 126 | ) 127 | -------------------------------------------------------------------------------- /variables.tf: -------------------------------------------------------------------------------- 1 | variable "name" { 2 | type = string 3 | description = "A name for this eks cluster" 4 | } 5 | 6 | variable "endpoint_public_access" { 7 | type = bool 8 | description = "Indicates whether or not the Amazon EKS public API server endpoint is enabled." 9 | default = false 10 | } 11 | 12 | variable "endpoint_public_access_cidrs" { 13 | type = list(string) 14 | default = null 15 | } 16 | 17 | variable "cluster_log_types" { 18 | type = list(string) 19 | description = "A list of the desired control plane logging to enable." 20 | default = ["api", "audit", "authenticator", "controllerManager", "scheduler"] 21 | } 22 | 23 | variable "vpc_config" { 24 | type = object({ 25 | vpc_id = string 26 | public_subnet_ids = map(string) 27 | private_subnet_ids = map(string) 28 | }) 29 | 30 | description = "The network configuration used by the cluster, If you use the included VPC module you can provide it's config output variable" 31 | } 32 | 33 | variable "iam_role_name_prefix" { 34 | default = "" 35 | description = "An optional prefix to any IAM Roles created by this module" 36 | } 37 | 38 | variable "iam_policy_name_prefix" { 39 | default = "" 40 | description = "An optional prefix to any IAM Policies created by this module" 41 | } 42 | 43 | variable "cluster_role_arn" { 44 | type = string 45 | description = "The ARN of IAM role to be used by the cluster, if not specified a role will be created" 46 | default = "" 47 | } 48 | 49 | variable "oidc_root_ca_thumbprints" { 50 | type = list(string) 51 | default = ["9e99a48a9960b14926bb7f3b02e22da2b0ab7280"] 52 | description = "Thumbprint of Root CA for EKS OpenID Connect (OIDC) identity provider, Valid until 2037 🤞" 53 | } 54 | 55 | variable "aws_auth_role_map" { 56 | type = list(object({ 57 | rolearn = string 58 | username = string 59 | groups = list(string) 60 | })) 61 | default = [] 62 | description = "A list of mappings from aws role arns to kubernetes users, and their groups" 63 | } 64 | 65 | variable "aws_auth_user_map" { 66 | type = list(object({ 67 | userarn = string 68 | username = string 69 | groups = list(string) 70 | })) 71 | default = [] 72 | description = "A list of mappings from aws user arns to kubernetes users, and their groups" 73 | } 74 | 75 | variable "kms_cmk_arn" { 76 | type = string 77 | default = "" 78 | description = "The ARN of the KMS (CMK) customer master key, to be used for Envelope Encryption of Kubernetes secrets, if not set a key will be generated" 79 | } 80 | 81 | variable "legacy_security_groups" { 82 | type = bool 83 | default = false 84 | description = "Preserves existing security group setup from pre 1.15 clusters, to allow existing clusters to be upgraded without recreation" 85 | } 86 | 87 | variable "tags" { 88 | type = map(string) 89 | default = {} 90 | description = "A map of tags to assign to cluster AWS resources" 91 | } 92 | 93 | variable "security_group_ids" { 94 | type = list(string) 95 | default = [] 96 | description = "A list of security group IDs for the cross-account elastic network interfaces that Amazon EKS creates to use to allow communication with the Kubernetes control plane. *WARNING* changes to this list will cause the cluster to be recreated." 97 | } 98 | 99 | variable "fargate_namespaces" { 100 | type = set(string) 101 | default = ["kube-system", "flux-system"] 102 | description = "A list of namespaces to create fargate profiles for, should be set to a list of namespaces critical for flux / cluster bootstrapping" 103 | } 104 | 105 | variable "vpc_cni_configuration_values" { 106 | type = string 107 | default = null 108 | description = "Configuration values passed to the vpc-cni EKS addon." 109 | } 110 | 111 | variable "kube_proxy_configuration_values" { 112 | type = string 113 | default = null 114 | description = "Configuration values passed to the kube-proxy EKS addon." 115 | } 116 | 117 | variable "coredns_configuration_values" { 118 | type = string 119 | default = "{ \"computeType\": \"fargate\", \"autoScaling\":{ \"enabled\": true } }" 120 | description = "Configuration values passed to the coredns EKS addon." 121 | } 122 | 123 | variable "ebs_csi_configuration_values" { 124 | type = string 125 | default = null 126 | description = "Configuration values passed to the ebs-csi EKS addon." 127 | } 128 | -------------------------------------------------------------------------------- /versions.tf: -------------------------------------------------------------------------------- 1 | # Run hack/versions k8sVersionNumber > versions.tf 2 | # to generate the latest values for this 3 | locals { 4 | versions = { 5 | k8s = "1.32" 6 | vpc_cni = "v1.19.3-eksbuild.1" 7 | kube_proxy = "v1.32.0-eksbuild.2" 8 | coredns = "v1.11.4-eksbuild.2" 9 | aws_ebs_csi_driver = "v1.41.0-eksbuild.1" 10 | } 11 | } 12 | --------------------------------------------------------------------------------