Skip to content

Commit

Permalink
🎉 initial commit (first draft)
Browse files Browse the repository at this point in the history
  • Loading branch information
colinwilson committed Jul 20, 2022
0 parents commit b7736c4
Show file tree
Hide file tree
Showing 35 changed files with 1,974 additions and 0 deletions.
40 changes: 40 additions & 0 deletions .github/workflows/terraform.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
name: 'Terraform GitHub Actions'

on:
pull_request:

jobs:
terraform-fmt:
name: Terraform Format
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/[email protected]

- name: Setup Terraform
uses: hashicorp/setup-terraform@v1

- name: Terraform Format
id: fmt
run: terraform fmt -diff -check -no-color -recursive
continue-on-error: true

- uses: actions/github-script@v4
if: github.event_name == 'pull_request' && steps.fmt.outputs.exitcode != 0
env:
TF_FMT_STDOUT: "${{ steps.fmt.outputs.stdout }}"
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const output = `#### Terraform Format and Style 🖌 - \`${{ steps.fmt.outcome }}\`
\`\`\`diff
${process.env.TF_FMT_STDOUT}
\`\`\`
*Pusher: @${{ github.actor }}, Action: \`${{ github.event_name }}\`, Workflow: \`${{ github.workflow }}\`*`;
github.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: output
})
throw "failed to run `terraform fmt -check -recursive -diff`"
9 changes: 9 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
.terraform.*
.terraform/
terraform.tfstate*
terraform.tfvars
terraform.txt
.auto.tfvars
creds/
.vscode/
debug.log
7 changes: 7 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright © 2022 AIGIS (Lotus Labs Ltd), Colin Wilson

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
57 changes: 57 additions & 0 deletions agents.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Create initial K3s server node
resource "hcloud_server" "agent_node" {

for_each = local.agent_nodes

name = "k3s-agent-${each.value.nodepool_name}-${each.value.location}-${random_id.agent_node_id[each.value.index].hex}"
image = "ubuntu-22.04"
server_type = each.value.server_type
placement_group_id = element(hcloud_placement_group.k3s_agent_placement_group.*.id, ceil(each.value.index / 10))
firewall_ids = [hcloud_firewall.k3s.id]
location = each.value.location
ssh_keys = [var.ssh_public_key_name]
labels = {
provisioner = "terraform",
engine = "k3s"
type = "agent"
}
# Prevent destroying the whole cluster if the user changes any of the attributes
# that force to recreate the servers or network ip's/mac addresses.
lifecycle {
ignore_changes = [
location,
network,
ssh_keys,
user_data,
]
}
network {
network_id = hcloud_network.k3s_net.id
#ip = "10.1.0.3"
}
user_data = templatefile("${path.module}/user_data/agent/agent.yaml.tftpl", {
k3s_channel = each.value.channel
agent_config = base64gzip(yamlencode({
server = "https://${hcloud_load_balancer_network.k3s_network.ip}:6443"
token = random_password.k3s_agent_token.result
flannel-iface = "ens10"
kubelet-arg = ["cloud-provider=external"]
node-label = each.value.labels
}))
})
provisioner "remote-exec" {
inline = [
"cloud-init status --wait --long > /dev/null" # wait for cloud-init to complete
]

connection {
host = self.ipv4_address
type = "ssh"
user = "root"
private_key = var.ssh_private_key
}
}
depends_on = [
hcloud_server.server_node_init
]
}
134 changes: 134 additions & 0 deletions code_of_conduct.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@

# Contributor Covenant Code of Conduct

## Our Pledge

We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, caste, color, religion, or sexual
identity and orientation.

We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.

## Our Standards

Examples of behaviour that contributes to a positive environment for our
community include:

* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall
community

Examples of unacceptable behaviour include:

* The use of sexualized language or imagery, and sexual attention or advances of
any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address,
without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting

## Enforcement Responsibilities

Community leaders are responsible for clarifying and enforcing our standards of
acceptable behaviour and will take appropriate and fair corrective action in
response to any behaviour that they deem inappropriate, threatening, offensive,
or harmful.

Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.

## Scope

This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behaviour may be
reported to the community leaders responsible for enforcement at
[email protected].
All complaints will be reviewed and investigated promptly and fairly.

All community leaders are obligated to respect the privacy and security of the
reporter of any incident.

## Enforcement Guidelines

Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:

### 1. Correction

**Community Impact**: Use of inappropriate language or other behaviour deemed
unprofessional or unwelcome in the community.

**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behaviour was inappropriate. A public apology may be requested.

### 2. Warning

**Community Impact**: A violation through a single incident or series of
actions.

**Consequence**: A warning with consequences for continued behaviour. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or permanent
ban.

### 3. Temporary Ban

**Community Impact**: A serious violation of community standards, including
sustained inappropriate behaviour.

**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.

### 4. Permanent Ban

**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behaviour, harassment of an
individual, or aggression toward or disparagement of classes of individuals.

**Consequence**: A permanent ban from any sort of public interaction within the
community.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.1, available at
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].

Community Impact Guidelines were inspired by
[Mozilla's code of conduct enforcement ladder][Mozilla CoC].

For answers to common questions about this code of conduct, see the FAQ at
[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at
[https://www.contributor-covenant.org/translations][translations].

[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
[Mozilla CoC]: https://github.com/mozilla/diversity
[FAQ]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations

14 changes: 14 additions & 0 deletions firewall.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
resource "hcloud_firewall" "k3s" {
name = "k3s-cluster"

dynamic "rule" {
for_each = concat(local.base_firewall_rules)
content {
direction = rule.value.direction
protocol = rule.value.protocol
port = lookup(rule.value, "port", null)
destination_ips = lookup(rule.value, "destination_ips", [])
source_ips = lookup(rule.value, "source_ips", [])
}
}
}
11 changes: 11 additions & 0 deletions k3s_tokens.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
resource "random_password" "k3s_token" {
length = 48
upper = false
special = false
}

resource "random_password" "k3s_agent_token" {
length = 48
upper = false
special = false
}
19 changes: 19 additions & 0 deletions kubeconfig.yaml.tftpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
apiVersion: v1
clusters:
- cluster:
certificate-authority-data: ${certificate-authority-data}
server: https://${k3s_lb_ip}:6443
name: default
contexts:
- context:
cluster: default
user: default
name: default
current-context: default
kind: Config
preferences: {}
users:
- name: default
user:
client-certificate-data: ${client-certificate-data}
client-key-data: ${client-key-data}
58 changes: 58 additions & 0 deletions kubeconfig_certs.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Create Private Keys and Certificates required by k3s and the Default Kubeconfig

# Generate Server, Client & Request Header CA Keys + Default Client Admin Key
resource "tls_private_key" "keys" {
for_each = setunion(local.ca_names, local.client_names)
algorithm = "ECDSA" # ECDSA key
ecdsa_curve = "P256" # P256 elliptic curve
}

# Generate Server, Client & Request Header CA Certificates
resource "tls_self_signed_cert" "ca_certs" {

for_each = local.ca_names

private_key_pem = tls_private_key.keys[each.key].private_key_pem

subject {
common_name = "k3s-${each.key}-ca@${formatdate("YYYYMMDDhhmmss", timestamp())}"
}

is_ca_certificate = true

validity_period_hours = 87600 # 10 years

allowed_uses = [
"cert_signing",
"key_encipherment",
"digital_signature",
]

lifecycle {
ignore_changes = [subject]
}
}

# Default Client Admin User Certificate (Signed by Client CA)
resource "tls_cert_request" "client_admin_user" {
private_key_pem = tls_private_key.keys["client-admin"].private_key_pem

subject {
common_name = "system:admin"
organization = "system:masters"
}
}

resource "tls_locally_signed_cert" "client_admin_user" {
cert_request_pem = tls_cert_request.client_admin_user.cert_request_pem
ca_private_key_pem = tls_private_key.keys["client"].private_key_pem
ca_cert_pem = tls_self_signed_cert.ca_certs["client"].cert_pem

validity_period_hours = 8760 # 1 year

allowed_uses = [
"key_encipherment",
"digital_signature",
"client_auth",
]
}
4 changes: 4 additions & 0 deletions kubeconfig_file_output.tf
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
resource "local_file" "k3s_kubeconfig" {
content = local.kubeconfig
filename = "${path.root}/k3s.yaml"
}
Loading

0 comments on commit b7736c4

Please sign in to comment.