Commit a88437f2 by chenxx

add

1 parent 13a04ace
.idea
.terraform
*.tfstate
*.tfstate.backup
*.tfstate.lock.info
\ No newline at end of file
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Terraform module for Kubernetes Deployment
==========================================
Terraform module used to easily create a deployment with singe container. With simple syntax.
## Usage
```terraform
module "deploy" {
source = "../"
name = "jenkins"
namespace = "ci-cd"
image = "jenkins/jenkins:latest"
internal_port = [
{
name = "web-access"
internal_port = "8080"
host_port = "80"
},
{
name = "another"
internal_port = "8090"
}
]
readiness_probe = {
http_get = {
path = "/health"
port = 8080
scheme = "HTTP"
}
success_threshold = 1
failure_threshold = 3
initial_delay_seconds = 10
period_seconds = 30
timeout_seconds = 3
}
}
```
## Terraform Requirements
| Name | Version |
|------|---------|
| terraform | >= 0.14.8 |
| kubernetes | >= 2.1.0 |
## Inputs
| Name | Description | Type | Default | Example | Required |
|------|-------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|---------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:--------:|
| name | Name of the deployment | `string` | n/a | `application` | yes |
| namespace | Namespace in which create the deployment | `string` | `default` | `default` | no |
| custom\_labels | Add custom label to pods | `object` | `{ app = var.name }` | `{ mylabel = "apps" }` | no |
| image | Docker image name | `string` | n/a | `ubuntu:18.04` | yes |
| image\_pull_policy | One of Always, Never, IfNotPresent | `string` | `IfNotPresent` | `Always` | no |
| args | Arguments to the entrypoint | `list(string)` | n/a | `["--dev", "--nodaemon"]` | no |
| command | Change entrypoint array | `list(string)` | n/a | `["/bin/bash", "-c", "pwd"]` | no |
| min\_ready\_seconds | Field that specifies the minimum number of seconds for which a newly created Pod should be ready without any of its containers crashing, for it to be considered available | `number` | `null` | `2` | no |
| replicas | Count of pods | `number` | `1` | `5` | no |
| strategy\_update | Type of deployment. Can be 'Recreate' or 'RollingUpdate' | `string` | `RollingUpdate` | `Recreate` | no |
| rolling\_update | Rolling update config params. Present only if strategy_update = RollingUpdate | `object({ max_surge = string, max_unavailable = string })` | n/a | <pre>{<br> max_surge = "25%"<br> max_unavailable = "25%"<br>}</pre> | no |
| service_account\_name | Is the name of the ServiceAccount to use to run this pod | `string` | `null` | `application-sa` | no |
| service_accoun_token | Indicates whether a service account token should be automatically mounted | `bool` | `null` | `true` | no |
| restart\_policy | Restart policy for all containers within the pod. One of Always, OnFailure, Never | `string` | `Always` | `OnFailure` | no |
| image\_pull\_secrets | Specify image pull secrets | `map(string)` | `null` | `{ "some-key" = "my-secret" }` | no |
| node\_selector | Specify node selector for pod | `map(string)` | `null` | `{ "some-key" = "true" }` | no |
| env | Name and value pairs to set in the container's environment | `map(string)` | n/a | <pre>\{<br> PORT = "80"<br> ADDRESS = "0.0.0.0"<br>}</pre> | no |
| env\_field | Get field from k8s and add as environment variables to pods | `map(string)` | n/a | <pre>\{<br> NodeName = "spec.nodeName"<br>}</pre> | no |
| env\_secret | Get secret keys from k8s and add as environment variables to pods | `map(string)` | n/a | <pre>\{<br> # Match env name, with the same key in secret.<br> admin_pass = kubernetes.secret.my.id<br> <br> # Specify secret name & secret key for env name<br> DbPass = {<br> name = "kubernetes-secret-name"<br> key = "secret-key"<br> }<br>}<br></pre> | no |
| resources | Compute Resources required by this container. CPU/RAM requests/limits | <pre>object({<br> request_cpu = string - (Optional)<br> request_memory = string - (Optional)<br> limit_cpu = string - (Optional)<br> limit_memory = string - (Optional)<br> })</pre> | n/a | <pre> {<br> request_cpu = "100m"<br> request_memory = "800Mi"<br> limit_cpu = "120m"<br> limit_memory = "900Mi"<br> }<br></pre> | no || internal\_port | List of ports to expose from the container | <pre>list(object({<br> internal_port = number<br> name = string<br> host_port = number - (Optional)<br> }))</pre> | n/a | <pre>\[<br> {<br> internal_port = 8080<br> name = web<br> host_port = 80 - (Optional)<br> }<br>]</pre> | no |
| toleration | Pod node tolerations | <pre>list(object({<br> effect = string // (Optional)<br> key = string // (Optional)<br> operator = string // (Optional)<br> toleration_seconds = number // (Optional)<br> value = string // (Optional)<br> }))</pre> | n/a | <pre>[<br> {<br> effect = "NoSchedule"<br> key = "gpu"<br> operator = "Equal"<br> value = "true"<br> }<br>]</pre> | no |
| hosts | Add /etc/hosts records to pods | <pre>list(object({<br> hostname = string<br> ip = string<br> }))</pre> | n/a | <pre>\[<br> {<br> hostname = "mysite.com"<br> ip = "10.10.1.20"<br> }<br>]</pre> | no |
| volume\_mount | Mount path from pods to volume | <pre>list(object({<br> mount_path = string<br> volume_name = string<br> sub_path = string - (Optional)<br> read_only = bool - (Optional)<br> }))</pre> | n/a | <pre>\[<br> {<br> mount_path = "/mnt"<br> volume_name = "node"<br> sub_path = "app"<br> read_only = false<br> }<br>]</pre> | no |
| volume\_nfs | Represents an NFS mounts on the host | <pre>list(object({<br> path_on_nfs = string<br> nfs_endpoint = string<br> volume_name = string<br> }))</pre> | n/a | <pre>\[<br> {<br> path_on_nfs = "/"<br> nfs_endpoint = "10.10.0.100"<br> volume_name = "share"<br> }<br>]</pre> | no |
| volume\_host\_path | Represents a directory from node on the host | <pre>list(object({<br> path_on_node = string<br> type = string - (Optional)<br> volume_name = string<br> }))</pre> | n/a | <pre>\[<br> {<br> path_on_node = "/home/ubuntu"<br> type = "Directory"<br> volume_name = "node"<br> }<br>]</pre> | no |
| volume\_config\_map | The data stored in a ConfigMap object can be referenced in a volume of type configMap and then consumed by containerized applications running in a Pod | <pre>list(object({<br> mode = string<br> name = string<br> volume_name = string<br> }))</pre> | n/a | <pre>\[<br> {<br> mode = "0777"<br> name = "config-map"<br> volume_name = "config-volume"<br> }<br>]</pre> | no |
| volume\_aws\_disk | Represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod | <pre>list(object({<br> volume_id = string<br> fs_type = string - (Optional)<br> partition = string - (Optional)<br> read_only = string - (Optional)<br> volume_name = string<br> }))</pre> | n/a | <pre>\[<br> {<br> volume_id = "vol-123124123"<br> volume_name = "disk"<br> }<br>]</pre> | no |
| volume\_gce\_disk | Represents an GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod | <pre>list(object({<br> volume_name = string<br> fs_type = string - (Optional)<br> partition = string - (Optional)<br> read_only = string - (Optional)<br> gce_disk = string<br> }))</pre> | n/a | <pre>\[<br> {<br> volume_name = "google-disk-my"<br> gce_disk = "disk"<br> }<br>]</pre> | no |
| volume\_empty\_dir | EmptyDir represents a temporary directory that shares a pod's lifetime | <pre>list(object({<br> volume_name = string<br> medium = string (Optional)<br> size_limit = string (Optional)<br> }))</pre> | n/a | <pre>\[<br> {<br> volume_name = "empty-dir"<br> medium = "Memory"<br> size_limit = "128Mi"<br> }<br>]</pre> | no |
| volume\_claim | Represents an Persistent volume Claim resource that is attached to a kubelet's host machine and then exposed to the pod | <pre>list(object({<br> volume_name = string<br> claim_name = string - (Optional)<br> read_only = string - (Optional)<br>}))</pre> | n/a | <pre>\[<br> {<br> volume_name = "data-disk"<br> claim_name = "claim-name-disk"<br> }<br>]</pre> | no |
| readiness\_probe | Periodic probe of container service readiness. Container will be removed from service endpoints if the probe fails. | <pre>object({<br> success_threshold = number<br> failure_threshold = number<br> initial_delay_seconds = number <br> period_seconds = number <br> timeout_seconds = number <br><br> http_get = {<br> http_header = list(object( // (Optional)<br> {<br> name = string<br> value = string<br> }<br> )<br> path = string<br> port = number<br> scheme = string<br> } <br> exec = { // (Optional)<br> command =list(string)<br> }<br> tcp_socket = { // (Optional)<br> port = number<br> }<br> })</pre> | n/a | <pre>{<br> success_threshold = 1<br> failure_threshold = 3<br> initial_delay_seconds = 10 <br> period_seconds = 30 <br> timeout_seconds = 10 <br><br> http_get = {<br> http_header = [<br> {<br> name = "some-header"<br> value = "some-value"<br> }<br> ]<br> path = "/"<br> port = 80<br> scheme = "HTTP"<br> } <br> exec = {<br> command = ["/bin/bash", "command"]<br> }<br> tcp_socket = {<br> port = 5433<br> }<br> })</pre> | no |
| liveness\_probe | Periodic probe of container liveness. Container will be restarted if the probe fails | same as on readiness_probe | n/a | same as on readiness_probe | no |
| lifecycle\_events | Actions that the management system should take in response to container lifecycle events | <pre>object({<br> pre_stop = { // (Optional) <br> same as on readiness_probe<br> } <br><br> post_start = { // (Optional) <br> same as on readiness_probe<br> }<br>})</pre> | n/a | <pre>{<br> pre_stop = { // (Optional) <br> same as on readiness_probe<br> } <br><br> post_start = { // (Optional) <br> same as on readiness_probe<br> }<br>}</pre> | no |
## Outputs
| Name | Description |
|------|:-----------:|
| name | Name of the deployment |
| namespace | Namespace in which created the deployment |
module "deploy" {
source = "../"
name = var.app_name
namespace = var.app_namespace
image = var.image
internal_port = var.ports
volume_nfs = [
{
path_on_nfs = "/"
nfs_endpoint = "10.10.0.100"
volume_name = var.volume_data
}
]
volume_host_path = [
{
volume_name = var.volume_logs
path_on_node = "/var/log"
},
{
volume_name = var.volume_tmp
path_on_node = "/tmp"
}
]
volume_mount = [
{
mount_path = "/var/jenkins_home"
sub_path = "jenkins"
volume_name = var.volume_data
},
{
mount_path = "/logs"
volume_name = var.volume_logs
},
{
mount_path = "/tmps"
volume_name = var.volume_tmp
},
{
mount_path = "/var/jenkins_home/config.conf"
volume_name = var.volume_config
sub_path = "key1" // Key from configmap
}
]
volume_config_map = [
{
mode = "0777" // Must be a value between 0 and 0777. Defaults to 0644
name = "config-jenkins" // Config map name
volume_name = var.volume_config
}
]
readiness_probe = {
http_get = {
path = "/healthcheck"
port = 80
scheme = "HTTP"
http_header = [
{
name = "test"
value = "test"
},
{
name = "tes"
value = "asd"
}
]
}
success_threshold = 1
failure_threshold = 3
initial_delay_seconds = 10
period_seconds = 30
timeout_seconds = 3
}
}
\ No newline at end of file
variable "app_name" {
default = "jenkins"
}
variable "app_namespace" {
default = "jenkins-ci"
}
variable "image" {
default = "jenkins/jenkins:latest"
}
variable "ports" {
default = [
{
name = "web-access"
internal_port = "8080"
}
]
}
variable "volume_data" {
default = "data"
}
variable "volume_logs" {
default = "logs-from-node"
}
variable "volume_tmp" {
default = "tmp-from-node"
}
variable "volume_config" {
default = "jenkins-configmap"
}
\ No newline at end of file
locals {
labels = var.custom_labels == null ? { app = var.name } : var.custom_labels
env = flatten([
for name, value in var.env : {
name = tostring(name)
value = tostring(value)
}
])
env_field = flatten([
for name, field_path in var.env_field : {
name = tostring(name)
field_path = tostring(field_path)
}
])
env_secret = flatten([
for name, secret in var.env_secret : {
name = tostring(name)
secret_key = try(tostring(secret["key"]), name)
secret_name = try(tostring(secret["name"]), secret)
}
])
}
\ No newline at end of file
resource "kubernetes_deployment" "deploy_app" {
wait_for_rollout = var.wait_for_rollout
metadata {
name = var.name
namespace = var.namespace
labels = local.labels
annotations = var.deployment_annotations
}
spec {
min_ready_seconds = var.min_ready_seconds
replicas = var.replicas
strategy {
type = var.strategy_update
dynamic "rolling_update" {
for_each = flatten([var.rolling_update])
content {
max_surge = lookup(rolling_update.value, "max_surge", "25%")
max_unavailable = lookup(rolling_update.value, "max_unavailable", "25%")
}
}
}
selector {
match_labels = local.labels
}
template {
metadata {
labels = local.labels
annotations = var.template_annotations
}
spec {
termination_grace_period_seconds = var.termination_grace_period_seconds
service_account_name = var.service_account_name
automount_service_account_token = var.service_account_token
restart_policy = var.restart_policy
dynamic "image_pull_secrets" {
for_each = var.image_pull_secrets
content {
name = image_pull_secrets.value
}
}
node_selector = var.node_selector
dynamic "affinity" {
for_each = var.prevent_deploy_on_the_same_node ? [{}] : []
content {
pod_anti_affinity {
required_during_scheduling_ignored_during_execution {
label_selector {
match_labels = local.labels
}
topology_key = "kubernetes.io/hostname"
}
}
}
}
dynamic "toleration" {
for_each = var.toleration
content {
effect = lookup(toleration.value, "effect", null)
key = lookup(toleration.value, "key", null)
operator = lookup(toleration.value, "operator", null)
toleration_seconds = lookup(toleration.value, "toleration_seconds", null)
value = lookup(toleration.value, "value", null)
}
}
dynamic "host_aliases" {
iterator = hosts
for_each = var.hosts
content {
hostnames = hosts.value.hostname
ip = hosts.value.ip
}
}
dynamic "volume" {
for_each = var.volume_empty_dir
content {
empty_dir {
medium = lookup(volume.value, "medium", null)
size_limit = lookup(volume.value, "size_limit", null)
}
name = volume.value.volume_name
}
}
dynamic "volume" {
for_each = var.volume_nfs
content {
nfs {
path = volume.value.path_on_nfs
server = volume.value.nfs_endpoint
}
name = volume.value.volume_name
}
}
dynamic "volume" {
for_each = var.volume_host_path
content {
host_path {
path = volume.value.path_on_node
type = lookup(volume.value, "type", null)
}
name = volume.value.volume_name
}
}
dynamic "volume" {
for_each = var.volume_config_map
content {
config_map {
default_mode = volume.value.mode
name = volume.value.name
optional = lookup(volume.value, "optional", null)
dynamic "items" {
for_each = lookup(volume.value, "items", [])
content {
key = items.value.key
path = items.value.path
mode = lookup(items.value, "mode", null)
}
}
}
name = volume.value.volume_name
}
}
dynamic "volume" {
for_each = var.volume_gce_disk
content {
gce_persistent_disk {
pd_name = volume.value.gce_disk
fs_type = lookup(volume.value, "fs_type", null)
partition = lookup(volume.value, "partition", null)
read_only = lookup(volume.value, "read_only", null)
}
name = volume.value.volume_name
}
}
dynamic "volume" {
for_each = var.volume_secret
content {
secret {
secret_name = volume.value.secret_name
default_mode = lookup(volume.value, "default_mode", null)
optional = lookup(volume.value, "optional", null)
dynamic "items" {
for_each = lookup(volume.value, "items", [])
content {
key = items.value.key
path = items.value.path
mode = lookup(items.value, "mode", null)
}
}
}
name = volume.value.volume_name
}
}
dynamic "volume" {
for_each = var.volume_aws_disk
content {
aws_elastic_block_store {
fs_type = lookup(volume.value, "fs_type", null)
partition = lookup(volume.value, "partition", null)
read_only = lookup(volume.value, "read_only", null)
volume_id = volume.value.volume_id
}
name = volume.value.volume_name
}
}
dynamic "volume" {
for_each = var.volume_claim
content {
persistent_volume_claim {
claim_name = lookup(volume.value, "claim_name", null)
read_only = lookup(volume.value, "read_only", null)
}
name = volume.value.volume_name
}
}
dynamic "security_context" {
for_each = flatten([var.security_context])
content {
fs_group = lookup(security_context.value, "fs_group", null)
run_as_group = lookup(security_context.value, "run_as_group", null)
run_as_user = lookup(security_context.value, "run_as_user", null)
run_as_non_root = lookup(security_context.value, "run_as_non_root", null)
}
}
container {
name = var.name
image = var.image
image_pull_policy = var.image_pull_policy
args = var.args
command = var.command
dynamic "security_context" {
for_each = flatten([var.security_context_container])
content {
allow_privilege_escalation = lookup(security_context.value, "allow_privilege_escalation", null)
privileged = lookup(security_context.value, "privileged", null)
read_only_root_filesystem = lookup(security_context.value, "read_only_root_filesystem", null)
dynamic "capabilities" {
for_each = length(security_context.value.capabilities) != 0 ? [security_context.value.capabilities] : []
content {
add = lookup(capabilities.value, "add", [])
drop = lookup(capabilities.value, "drop", [])
}
}
}
}
dynamic "env" {
for_each = local.env
content {
name = env.value.name
value = env.value.value
}
}
dynamic "env" {
for_each = local.env_field
content {
name = env.value.name
value_from {
field_ref {
field_path = env.value.field_path
}
}
}
}
dynamic "env" {
for_each = local.env_secret
content {
name = env.value.name
value_from {
secret_key_ref {
name = env.value.secret_name
key = env.value.secret_key
}
}
}
}
dynamic "resources" {
for_each = length(var.resources) == 0 ? [] : [{}]
content {
requests = {
cpu = lookup(var.resources, "request_cpu", null)
memory = lookup(var.resources, "request_memory", null)
}
limits = {
cpu = lookup(var.resources, "limit_cpu", null)
memory = lookup(var.resources, "limit_memory", null)
}
}
}
dynamic "port" {
for_each = var.internal_port
content {
container_port = port.value.internal_port
name = substr(port.value.name, 0, 14)
host_port = lookup(port.value, "host_port", null)
}
}
dynamic "volume_mount" {
for_each = var.volume_mount
content {
mount_path = volume_mount.value.mount_path
sub_path = lookup(volume_mount.value, "sub_path", null)
name = volume_mount.value.volume_name
read_only = lookup(volume_mount.value, "read_only", false)
}
}
dynamic "liveness_probe" {
for_each = flatten([var.liveness_probe])
content {
initial_delay_seconds = lookup(liveness_probe.value, "initial_delay_seconds", null)
period_seconds = lookup(liveness_probe.value, "period_seconds", null)
timeout_seconds = lookup(liveness_probe.value, "timeout_seconds", null)
success_threshold = lookup(liveness_probe.value, "success_threshold", null)
failure_threshold = lookup(liveness_probe.value, "failure_threshold", null)
dynamic "http_get" {
for_each = contains(keys(liveness_probe.value), "http_get") ? [liveness_probe.value.http_get] : []
content {
path = lookup(http_get.value, "path", null)
port = lookup(http_get.value, "port", null)
scheme = lookup(http_get.value, "scheme", null)
host = lookup(http_get.value, "host", null)
dynamic "http_header" {
for_each = contains(keys(http_get.value), "http_header") ? http_get.value.http_header : []
content {
name = http_header.value.name
value = http_header.value.value
}
}
}
}
dynamic "exec" {
for_each = contains(keys(liveness_probe.value), "exec") ? [liveness_probe.value.exec] : []
content {
command = exec.value.command
}
}
dynamic "tcp_socket" {
for_each = contains(keys(liveness_probe.value), "tcp_socket") ? [liveness_probe.value.tcp_socket] : []
content {
port = tcp_socket.value.port
}
}
}
}
dynamic "readiness_probe" {
for_each = flatten([var.readiness_probe])
content {
initial_delay_seconds = lookup(readiness_probe.value, "initial_delay_seconds", null)
period_seconds = lookup(readiness_probe.value, "period_seconds", null)
timeout_seconds = lookup(readiness_probe.value, "timeout_seconds", null)
success_threshold = lookup(readiness_probe.value, "success_threshold", null)
failure_threshold = lookup(readiness_probe.value, "failure_threshold", null)
dynamic "http_get" {
for_each = contains(keys(readiness_probe.value), "http_get") ? [readiness_probe.value.http_get] : []
content {
path = lookup(http_get.value, "path", null)
port = lookup(http_get.value, "port", null)
scheme = lookup(http_get.value, "scheme", null)
host = lookup(http_get.value, "host", null)
dynamic "http_header" {
for_each = contains(keys(http_get.value), "http_header") ? http_get.value.http_header : []
content {
name = http_header.value.name
value = http_header.value.value
}
}
}
}
dynamic "exec" {
for_each = contains(keys(readiness_probe.value), "exec") ? [readiness_probe.value.exec] : []
content {
command = exec.value.command
}
}
dynamic "tcp_socket" {
for_each = contains(keys(readiness_probe.value), "tcp_socket") ? [readiness_probe.value.tcp_socket] : []
content {
port = tcp_socket.value.port
}
}
}
}
dynamic "lifecycle" {
for_each = flatten([var.lifecycle_events])
content {
dynamic "pre_stop" {
for_each = contains(keys(lifecycle.value), "pre_stop") ? [lifecycle.value.pre_stop] : []
content {
dynamic "http_get" {
for_each = contains(keys(pre_stop.value), "http_get") ? [pre_stop.value.http_get] : []
content {
path = lookup(http_get.value, "path", null)
port = lookup(http_get.value, "port", null)
scheme = lookup(http_get.value, "scheme", null)
host = lookup(http_get.value, "host", null)
dynamic "http_header" {
for_each = contains(keys(http_get.value), "http_header") ? http_get.value.http_header : []
content {
name = http_header.value.name
value = http_header.value.value
}
}
}
}
dynamic "exec" {
for_each = contains(keys(pre_stop.value), "exec") ? [pre_stop.value.exec] : []
content {
command = exec.value.command
}
}
dynamic "tcp_socket" {
for_each = contains(keys(pre_stop.value), "tcp_socket") ? [pre_stop.value.tcp_socket] : []
content {
port = tcp_socket.value.port
}
}
}
}
dynamic "post_start" {
for_each = contains(keys(lifecycle.value), "post_start") ? [lifecycle.value.post_start] : []
content {
dynamic "http_get" {
for_each = contains(keys(post_start.value), "http_get") ? [post_start.value.http_get] : []
content {
path = lookup(http_get.value, "path", null)
port = lookup(http_get.value, "port", null)
scheme = lookup(http_get.value, "scheme", null)
host = lookup(http_get.value, "host", null)
dynamic "http_header" {
for_each = contains(keys(http_get.value), "http_header") ? http_get.value.http_header : []
content {
name = http_header.value.name
value = http_header.value.value
}
}
}
}
dynamic "exec" {
for_each = contains(keys(post_start.value), "exec") ? [post_start.value.exec] : []
content {
command = exec.value.command
}
}
dynamic "tcp_socket" {
for_each = contains(keys(post_start.value), "tcp_socket") ? [post_start.value.tcp_socket] : []
content {
port = tcp_socket.value.port
}
}
}
}
}
}
tty = var.tty
}
}
}
}
}
\ No newline at end of file
output "name" {
value = var.name
}
output "namespace" {
value = var.namespace
}
\ No newline at end of file
variable "name" {
type = string
description = "(Required) Name of the deployment"
}
variable "namespace" {
type = string
description = "(Optional) Namespace in which to create the deployment"
default = "default"
}
variable "deployment_annotations" {
description = "Annotations for deployment"
type = map(string)
default = null
}
variable "template_annotations" {
description = "Annotations for pod (template)"
type = map(string)
default = null
}
variable "image" {
type = string
description = "(Required) Docker image name"
}
variable "image_pull_policy" {
type = string
default = "IfNotPresent"
description = "One of Always, Never, IfNotPresent"
}
variable "args" {
type = list(string)
description = "(Optional) Arguments to the entrypoint"
default = []
}
variable "command" {
type = list(string)
description = "(Optional) Entrypoint array. Not executed within a shell"
default = []
}
variable "env" {
type = map(string)
description = "(Optional) Name and value pairs to set in the container's environment"
default = {}
}
variable "env_field" {
type = map(string)
description = "(Optional) Get field from k8s and add as environment variables to pods"
default = {}
}
variable "env_secret" {
description = "(Optional) Get secret keys from k8s and add as environment variables to pods"
default = {}
}
variable "resources" {
/* type = object({
request_cpu = optional(string)
request_memory = optional(string)
limit_cpu = optional(string)
limit_memory = optional(string)
})*/
description = "(Optional) Compute Resources required by this container. CPU/RAM requests/limits"
default = {}
}
variable "internal_port" {
type = list(object({
name = string
internal_port = number
host_port = optional(string)
}))
description = "(Optional) List of ports to expose from the container"
default = []
}
variable "volume_mount" {
type = list(object({
volume_name = string
mount_path = string
sub_path = optional(string)
read_only = optional(string)
}))
description = "(Optional) Mount path from pods to volume"
default = []
}
variable "volume_nfs" {
type = list(object({
path_on_nfs = string
nfs_endpoint = string
volume_name = string
}))
description = "(Optional) Represents an NFS mounts on the host"
default = []
}
variable "volume_host_path" {
type = list(object({
volume_name = string
path_on_node = string
type = optional(string)
}))
description = "(Optional) Represents a directory from node on the host"
default = []
}
variable "volume_config_map" {
type = list(object({
volume_name = string
name = string
mode = optional(string)
optional = optional(string)
items = optional(list(object({
key = string
path = string
mode = optional(string)
})),[])
}))
description = "(Optional) The data stored in a ConfigMap object can be referenced in a volume of type configMap and then consumed by containerized applications running in a Pod"
default = []
}
variable "volume_empty_dir" {
type = list(object({
volume_name = string
medium = optional(string)
size_limit = optional(string)
}))
description = "(Optional) EmptyDir represents a temporary directory that shares a pod's lifetime"
default = []
}
variable "volume_gce_disk" {
type = list(object({
volume_name = string
gce_disk = optional(string)
fs_type = optional(string)
partition = optional(string)
read_only = optional(string)
}))
description = "(Optional) Represents an GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod"
default = []
}
variable "volume_secret" {
type = list(object({
volume_name = string
secret_name = string
default_mode = optional(string)
optional = optional(string)
items = optional(list(object({
key = string
path = string
mode = optional(string)
})),[])
}))
description = "(Optional) Create volume from secret"
default = []
}
variable "volume_aws_disk" {
type = list(object({
volume_name = string
volume_id = string
fs_type = optional(string)
partition = optional(string)
read_only = optional(string)
}))
description = "(Optional) Represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod"
default = []
}
variable "volume_claim" {
type = list(object({
volume_name = string
claim_name = optional(string)
read_only = optional(string)
}))
description = "(Optional) Represents an Persistent volume Claim resource that is attached to a kubelet's host machine and then exposed to the pod"
default = []
}
variable "toleration" {
type = list(object({
effect = optional(string)
key = optional(string)
operator = optional(string)
toleration_seconds = optional(string)
value = optional(string)
}))
description = "(Optional) Pod node tolerations"
default = []
}
variable "hosts" {
type = list(object({
hostname = list(string)
ip = string
}))
description = "(Optional) Add /etc/hosts records to pods"
default = []
}
variable "security_context" {
/* type = object({
fs_group = optional(string)
run_as_group = optional(string)
run_as_user = optional(string)
run_as_non_root = optional(string)
})*/
description = "(Optional) SecurityContext holds pod-level security attributes and common container settings"
default = []
}
variable "security_context_container" {
/* type = object({
allow_privilege_escalation = optional(string)
privileged = optional(string)
read_only_root_filesystem = optional(string)
run_as_non_root = optional(string)
capabilities = optional(object({
add = optional(list(string))
drop = optional(list(string))
}),{})
})*/
description = "(Optional) Security context in pod."
default = []
}
variable "custom_labels" {
description = "(Optional) Add custom label to pods"
default = null
type = map(string)
}
variable "tty" {
description = "Whether this container should allocate a TTY for itself"
type = bool
default = true
}
variable "termination_grace_period_seconds" {
type = number
description = "Duration in seconds the pod needs to terminate gracefully"
default = null
}
variable "service_account_token" {
type = bool
description = "Indicates whether a service account token should be automatically mounted"
default = null
}
variable "service_account_name" {
type = string
description = "(Optional) Is the name of the ServiceAccount to use to run this pod"
default = null
}
variable "restart_policy" {
type = string
description = "Restart policy for all containers within the pod. One of Always, OnFailure, Never"
default = "Always"
}
variable "replicas" {
type = number
description = "(Optional) Count of pods"
default = 1
}
variable "min_ready_seconds" {
type = number
description = "(Optional) Field that specifies the minimum number of seconds for which a newly created Pod should be ready without any of its containers crashing, for it to be considered available"
default = null
}
variable "liveness_probe" {
/* type = object({
initial_delay_seconds = optional(string)
period_seconds = optional(string)
timeout_seconds = optional(string)
success_threshold = optional(string)
failure_threshold = optional(string)
http_get = optional(object({
path = optional(string)
port = optional(string)
scheme = optional(string)
host = optional(string)
http_header = optional(list(object({
name = string
value = string
})))
}))
exec = optional(object({
command = list(string)
}))
tcp_socket = optional(object({
port = number
}))
})*/
description = "(Optional) Periodic probe of container liveness. Container will be restarted if the probe fails. Cannot be updated. "
default = []
}
variable "readiness_probe" {
/* type = object({
initial_delay_seconds = optional(string)
period_seconds = optional(string)
timeout_seconds = optional(string)
success_threshold = optional(string)
failure_threshold = optional(string)
http_get = optional(object({
path = optional(string)
port = optional(string)
scheme = optional(string)
host = optional(string)
http_header = optional(list(object({
name = string
value = string
})))
}))
exec = optional(object({
command = list(string)
}))
tcp_socket = optional(object({
port = number
}))
})*/
description = "(Optional) Periodic probe of container service readiness. Container will be removed from service endpoints if the probe fails. Cannot be updated. "
default = []
}
variable "lifecycle_events" {
/* type = object({
pre_stop = optional(object({
initial_delay_seconds = optional(string)
period_seconds = optional(string)
timeout_seconds = optional(string)
success_threshold = optional(string)
failure_threshold = optional(string)
http_get = optional(object({
path = optional(string)
port = optional(string)
scheme = optional(string)
host = optional(string)
http_header = optional(list(object({
name = string
value = string
})))
}))
exec = object({
command = list(string)
})
tcp_socket = object({
port = number
})
}))
post_start = optional(object({
initial_delay_seconds = optional(string)
period_seconds = optional(string)
timeout_seconds = optional(string)
success_threshold = optional(string)
failure_threshold = optional(string)
http_get = optional(object({
path = optional(string)
port = optional(string)
scheme = optional(string)
host = optional(string)
http_header = optional(list(object({
name = string
value = string
})))
}))
exec = optional(object({
command = list(string)
}))
tcp_socket = optional(object({
port = number
}))
}))
})*/
description = "(Optional) Actions that the management system should take in response to container lifecycle events"
default = []
}
variable "image_pull_secrets" {
description = "(Optional) Specify list of pull secrets"
type = map(string)
default = {}
}
variable "node_selector" {
description = "(Optional) Specify node selector for pod"
type = map(string)
default = null
}
variable "strategy_update" {
type = string
description = "(Optional) Type of deployment. Can be 'Recreate' or 'RollingUpdate'"
default = "RollingUpdate"
}
variable "rolling_update" {
/* type = object({
max_surge = optional(string)
max_unavailable = optional(string)
})*/
description = "Rolling update config params. Present only if strategy_update = RollingUpdate"
default = []
}
variable "wait_for_rollout" {
type = bool
description = "Wait for the deployment to successfully roll out."
default = true
}
variable "prevent_deploy_on_the_same_node" {
description = "Pod pod_anti_affinity rule, which prevents deploy same pod on one node."
type = bool
default = false
}
\ No newline at end of file
terraform {
required_version = ">= 0.14.8"
required_providers {
kubernetes = ">= 2.1.0"
}
}
\ No newline at end of file
# Add any directories, files, or patterns you don't want to be tracked by version control
**/credentials
.idea
.terraform
*.tfstate
*.tfstate.backup
*.tfstate.lock.info
\ No newline at end of file
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Terraform module for Kubernetes Service
==========================================
## Usage (more in example direcotry)
With default labels, selector finds pods with `app` label which equal to `app_name`
### Example with ClusterIP
```
module "service_jenkins_ClusterIP" {
source = "../"
app_name = "jenkins1"
app_namespace = "jenkins1"
port_mapping = var.port_mapping_CI
}
```
### Example with Load Balancer
```
module "service_jenkins_LB" {
source = "../"
app_name = "jenkins2"
app_namespace = "jenkins2"
port_mapping = var.port_mapping_LB
type = "LoadBalancer"
load_balancer_ip = "134.13.13.24" // This field will be ignored if the cloud-provider does not support the feature
load_balancer_ips_whitelist = [
"10.10.10.0/24",
"34.23.145.91/32"
]
}
```
### Example with Node Port
```
module "service_jenkins_NP" {
source = "../"
app_name = "jenkins3"
app_namespace = "jenkins3"
port_mapping = var.port_mapping_NP
type = "NodePort"
}
```
## Terraform Requirements
| Name | Version |
|------|---------|
| terraform | >= 0.12.26 |
| kubernetes | >= 2.0.0 |
## Inputs
See in example directory & variables.tf
## Outputs
| Name | Description |
|------------|:--------------------------------------:|
| name | Name of the service |
| namespace | Namespace in which created the service |
| id | Kubernetes resource id |
| node_ports | All Node Ports generated & entered |
\ No newline at end of file
# Example with ClusterIP
module "service_jenkins_ClusterIP" {
source = "../"
app_name = "jenkins1"
app_namespace = "jenkins1"
port_mapping = var.port_mapping_CI
}
# Example with Load Balancer
module "service_jenkins_LB" {
source = "../"
app_name = "jenkins2"
app_namespace = "jenkins2"
port_mapping = var.port_mapping_LB
type = "LoadBalancer"
load_balancer_ip = "134.13.13.24" // Also you can get from google_compute_address.static_external_ip.address
load_balancer_ips_whitelist = [
"10.10.10.0/24",
"34.23.145.91/32"
]
}
# Example with Node Port
module "service_jenkins_NP" {
source = "../"
app_name = "jenkins3"
app_namespace = "jenkins3"
port_mapping = var.port_mapping_NP
type = "NodePort"
}
\ No newline at end of file
variable "port_mapping_CI" {
default = [
{
name = "web-access" // (Required) Port name
internal_port = "8080" // (Required) Pod port
external_port = "80" // (Required) Port for others container's
},
{
name = "service-port" // (Required) Port name
internal_port = "3000" //(Required) Pod port
external_port = "90" //(Required) Port for others container's
portocol = "UDP" // (Optional) The IP protocol for this port. Supports TCP and UDP. Default is TCP.
}
]
}
variable "port_mapping_LB" {
default = [
{
name = "web-access" // (Required) Port name
internal_port = "8080" // (Required) Pod port
external_port = "80" // (Required) Port for others container's
node_port = "30000" // (Optional) set Node Port. By default K8S automatically set free Node Port
},
{
name = "service-port" // (Required) Port name
internal_port = "3000" // (Required) Pod port
external_port = "90" // (Required) Port for others container's
portocol = "UDP" // (Optional) The IP protocol for this port. Supports TCP and UDP. Default is TCP.
}
]
}
variable "port_mapping_NP" {
default = [
{
name = "web-access" // (Required) Port name
internal_port = "8080" // (Required) Pod port
external_port = "80" // (Required) Port for others container's
node_port = "30000" // (Optional) set Node Port. By default K8S automatically set free Node Port
},
{
name = "service-port" // (Required) Port name
internal_port = "3000" // (Required) Pod port
external_port = "90" // (Required) Port for others container's
portocol = "UDP" // (Optional) The IP protocol for this port. Supports TCP and UDP. Default is TCP.
}
]
}
\ No newline at end of file
resource "kubernetes_service" "service" {
metadata {
name = var.app_name
namespace = var.app_namespace
annotations = var.annotations
labels = local.labels
}
spec {
selector = local.labels
type = var.type
load_balancer_ip = var.type == "LoadBalancer" ? var.load_balancer_ip : null
load_balancer_source_ranges = var.type == "LoadBalancer" ? var.load_balancer_ips_whitelist : null
dynamic "port" {
iterator = port
for_each = var.port_mapping
content {
name = port.value.name
port = port.value.external_port
protocol = lookup(port.value, "protocol", "TCP")
node_port = lookup(port.value, "node_port", null)
target_port = port.value.internal_port
}
}
}
}
\ No newline at end of file
# K8S Resource id
output "id" {
value = kubernetes_service.service.id
}
# K8S Service Name
output "name" {
value = kubernetes_service.service.metadata[0].name
}
output "namespace" {
value = kubernetes_service.service.metadata[0].namespace
}
# Ports
output "node_ports" {
value = kubernetes_service.service.spec[0].port[*].node_port
}
\ No newline at end of file
variable "app_name" {
type = string
description = "(Required) Application name for attach to service"
}
variable "app_namespace" {
type = string
description = "(Required) Namespace where located application"
}
variable "port_mapping" {
description = "(Required) Mapping ports from container to expose port"
}
variable "type" {
type = string
default = null
description = "(Optional) Default is ClusterIP. Can accept: NodePort , LoadBalancer ."
}
variable "load_balancer_ip" {
type = string
description = "(Optional) !!!Only applies with type = LoadBalancer!!! Define External Static IP address."
default = null
}
variable "load_balancer_ips_whitelist" {
type = list(string)
default = null
description = "(Optional) !!!Only applies with type = LoadBalancer!!! Define IPs cidr range for whitelist in Load Balancer. By default accept all IPs."
}
variable "annotations" {
description = "(Optional) Add annotations"
default = {}
}
locals {
labels = var.custom_labels == null ? { app = var.app_name } : var.custom_labels
}
variable "custom_labels" {
description = "(Optional) Custom labels & selector"
default = null
}
\ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!