Lensを使ってみる

はじめに

前回でおうちKubernetes環境ができたので、モチベがあるうちに色々試したいと思い
とりあえず監視周りもついでにできるIDE環境、Lensを導入した。

Lensとは

Lens | The Kubernetes IDE

Lens is the only IDE you’ll ever need to take control of your Kubernetes clusters. It's open source and free. Download it today!

KubernetesIDEで、開発/監視/DevOp etcと色々できるらしい。

クラスタ追加

Lensを起動したあと、とりあえずクラスタ追加を行う。
$HOME/.kube/configあたりにある人はファイルを選べば行けそう。
筆者はwindows環境にkubectl周りの導入をしてなかったので、前回構築したマスターノードから.kube/configを持ってきて、Paste as textに転記した。

f:id:tm3log:20210102210148p:plain
Lens kubeconfig追加

初期設定

クラスタ追加された後は、各resourceが見れるようになる。

f:id:tm3log:20210102210804p:plain
kubeconfig追加後
f:id:tm3log:20210102211031p:plain
Podの一覧

今の状態だとCPUやメモリの状態が見れない。
Lensはボタン1つでkube-metric-stateやPrometheusの導入ができる。
メニューバーから「file」→「Cluster Settings」を選んでFeaturesからInstallを押下する。

f:id:tm3log:20210102211435p:plain
Cluster Settings

これで完了かと思いきや、kube-state-metericsが動いてないように見える。

f:id:tm3log:20210102211701p:plain
kube-state-metricsのEvents

0/3 nodes are available: 3 node(s) didn't match node selector.

NodeSelectorにarm64の記載がないので追加してやる。
Lensは選択したリソースのYAMLを直接編集してそのままapplyできる。
Deploymentsのkueb-state-metricsを選択し鉛筆マークを選択する。
before

      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
              - matchExpressions:
                  - key: kubernetes.io/os
                    operator: In
                    values:
                      - linux
                  - key: kubernetes.io/arch
                    operator: In
                    values:
                      - amd64
              - matchExpressions:
                  - key: beta.kubernetes.io/os
                    operator: In
                    values:
                      - linux
                  - key: beta.kubernetes.io/arch
                    operator: In
                    values:
                      - amd64

after

      affinity:
        nodeAffinity:
          requiredDuringSchedulingIgnoredDuringExecution:
            nodeSelectorTerms:
              - matchExpressions:
                  - key: kubernetes.io/os
                    operator: In
                    values:
                      - linux
                  - key: kubernetes.io/arch
                    operator: In
                    values:
                      - arm64
              - matchExpressions:
                  - key: beta.kubernetes.io/os
                    operator: In
                    values:
                      - linux
                  - key: beta.kubernetes.io/arch
                    operator: In
                    values:
                      - arm64

今回は全台RaspberryPi4なのでamd64をarm64に修正してみる。

f:id:tm3log:20210102212929p:plain
amd64 -> arm64に変更後

修正したけど、CrashLoopBackOffになるのでそもそものイメージがARMに対応してなさそう。
とりあえずgithubのissueを漁ると、やはり対応して無さそうなので対応しているalpha版のイメージを使う。

github.com

- - image: 'quay.io/coreos/kube-state-metrics:v1.9.7'
+ - image: 'k8s.gcr.io/kube-state-metrics/kube-state-metrics-arm64:2.0.0-alpha.1'

<figure class="figure-image figure-image-fotolife" title="修正後のClusterの状態">[f:id:tm3log:20210102213629p:plain]<figcaption>修正後のClusterの状態</figcaption></figure>

無事見れるようになった!

## 最後に
とりあえずLensの導入とmetrics周りの導入ができた。  
prometheusもデプロイされたので勉強がてら触って行こうと思う。  

K3s on Raspberry Pi4を構築してみる

はじめに

前回から半年以上経ってしまった...
それはそうとして冬休みなので、段ボールに眠っていたRaspberry Pi4を使っておうちKubernetesをした。
その時のログをとりあえず備忘録的に書き残しておく。
k8s自体はたくさんクラウドで作ったので、k3sでさくっと作っていく。

機材

機材はCyberAgnetのDeveloprBlog「おうちKubernetesインターン」を実施しましたを参考

機材名 個数 URL 備考
Raspberry Pi4 3 https://raspberry-pi.ksyic.com/main/index/pdp.id/549/pdp.open/549
micro SDカード 32GB 3 https://www.amazon.co.jp/dp/B07MTCJHP6
積載ケース 1 www.amazon.co.jp/dp/B07TJZ2HDG
PoE スイッチ 1 https://www.amazon.co.jp/dp/B0763TGBTS
PoE HAT 3 https://www.amazon.co.jp/dp/B07JPXR9ZN サードパーティ製PoE HAT
六角スペーサー 1 https://www.amazon.co.jp/dp/B0166GCHD4 PoE HAT装着すると積載ケースに付属のスペーサーだと入らないので購入
LANケーブル 0.15m 3 https://www.amazon.co.jp/dp/B00FZTNJQI/
Raspberry Pi3 1 お家に転がってたもの k8sクラスタへの踏み台(不要だったかも)

構成

ざっくりと。

f:id:tm3log:20210101232809p:plain
物理構成
NASはPVあたりに使おうかなぁという気持ちがあり、図として組み込んだ

実物はこちら

f:id:tm3log:20210101233314j:plain
Raspberry Pi4+Pi3
JumpもPoE化 or 追加Pi4購入&交換するかなぁ
それとスペーサーが60mmもあるので、高い...公式PoEに変える検討しよ

SDカードにOSイメージを焼く

今回焼くイメージはRaspberry Pi OSとした /etc/os-release

$ cat /etc/os-release
PRETTY_NAME="Raspbian GNU/Linux 10 (buster)"
NAME="Raspbian GNU/Linux"
VERSION_ID="10"
VERSION="10 (buster)"
VERSION_CODENAME=buster
ID=raspbian
ID_LIKE=debian
HOME_URL="http://www.raspbian.org/"
SUPPORT_URL="http://www.raspbian.org/RaspbianForums"
BUG_REPORT_URL="http://www.raspbian.org/RaspbianBugs"

手順
www.youtube.com

SSH有効化

デフォルメでSSHが無効になっているので、SSHを有効化しておく。
SDカードをイメージを焼くに使ったMacBookマウントした状態で以下を実行

$ touch /Volumes/boot/ssh

これを3回

構成情報

アドレスは以下の通り

ホスト名 eth0 wlan0
k3s-jump 192.168.110.50 192.168.11.50
k3s-master 192.168.110.51 192.168.11.51
k3s-worker01 192.168.110.52 192.168.11.52
k3s-worker02 192.168.110.53 192.168.11.53

初期設定

お家ルーターに一度繋ぎ、Wifi&IPの設定してから無線LAN経由でsshで作業。 参考にさせていただいたページ
blog.nownabe.com blog.nownabe.com

# change root
$ sudo su -

# 64bitモードに変更
$ echo "arm_64bit=1" >> /boot/config.txt
$ cat /boot/config.txt | grep arm?_64
arm_64bit=1

# hosts追加
$ vim /etc/hosts
$ grep k3s /etc/hosts
192.168.110.50 k3s-jump
192.168.110.51 k3s-master
192.168.110.52 k3s-worker01
192.168.110.53 k3s-worker02

# ipv6の停止
$ echo net.ipv6.conf.all.disable_ipv6 = 1 >> /etc/sysctl.conf
$ tail -1 /etc/sysctl.conf
net.ipv6.conf.all.disable_ipv6 = 1
$ sysctl -p

# cgroupsのMemory Subsystem を有効化
$ vim ./boot/cmdline.txt
(末尾に追記)
cgroup_memory=1 cgroup_enable=memory cgroup_enable=cpuset

# vimをインストール
$ apt install -y vim

# ホスト名の設定
$ hostnamectl set-hostname <hostname>

# IPアドレスの設定
$ vim /etc/dhcpcd.conf
(追記内奥).
interface eth0
static ip_address=<eth0.ip>/24
interface wlan0
static ip_address=<wlan0.ip>/24
static routers=<wlan0.gateway>
static domain_name_servers=<wlan0.gateway> 8.8.8.8 4.4.4.4

# SSID/Wifiのパスワード設定 
$ raspi-config
System Options -> S1 Wireless LANを選択して、情報を入力し再起動される

これを3台分実施
再起動後、さらにsshdの変更と作業ユーザー作成を行う

$ ssh pi@<wlan0.ip>
$ sudo su- 

# sshdの設定変更
$ vim /etc/ssh/sshd_config
(編集内容)
PermitRootLogin no
PasswordAuthentication no
$ systemctl restart sshd

# 作業ユーザー作成
$ useradd -m tm3exe
$ usermod -aG sudo tm3exe
$ passwd tm3exe

# 作業ユーザーに変更して、sshの設定
$ su - tm3exe
$ mkdir .ssh
$ cat <your_authpubkey> >> ~/.ssh/authorized_keys
$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/authorized_keys

# デフォルトユーザーpiのパスワード削除
$ sudo passwd -d pi

# swapの停止
$ sudo swapoff --all
$ sudo apt-get purge -y --auto-remove dphys-swapfile
$ sudo rm -fr /var/swap
$ free -h
              total        used        free      shared  buff/cache   available
Mem:          912Mi       169Mi       401Mi        13Mi       341Mi       666Mi
Swap:            0B          0B          0B <- 0BになっていればOK

K3sのインストール(共通)

やることは前記事と変わらず、Nodeを追加する部分だけが追加で必要。

# Master/Worker両方に実施
$ sudo su -
$ curl -sfL https://get.k3s.io | INSTALL_K3S_EXEC="--disable servicelb" sh -
(~snip~)
Created symlink /etc/systemd/system/multi-user.target.wants/k3s.service ¨ /etc/systemd/system/k3s.service.
[INFO]  systemd: Starting k3s

# Node取得
$ kubectl beget nodes
NAME         STATUS   ROLES    AGE     VERSION
k3s-master   Ready    master   3m16s   v1.19.5+k3s2

Workerの追加

参考にさせていただいたページ
qiita.com

# Masterのみ
# TOKENの取得
$ cat /var/lib/rancher/k3s/server/node-token
K10560f5b4981b71a2c7886935ea74b52540b698b0bb0c22a6232d3884e10f18333::server:7a988ded50e84665f0cb547d45f75f52

# Workerのみ
# k3sの停止
$ sh /usr/local/bin/k3s-killall.sh
$ systemctl stop k3s

# k3s-agentのservice設定
cat <<EOF > /etc/systemd/system/k3s-agent.service
[Unit]
Description=Lightweight Kubernetes Agent
Documentation=https://k3s.io
After=network-online.target

[Service]
Type=simple
EnvironmentFile=/etc/sysconfig/k3s-agent
ExecStartPre=-/sbin/modprobe br_netfilter
ExecStartPre=-/sbin/modprobe nf_conntrack
ExecStartPre=-/sbin/modprobe overlay
ExecStartPre=-/sbin/modprobe vxlan
ExecStart=/usr/local/bin/k3s agent --server \$SERVER --token \$TOKEN
Delegate=yes
LimitNOFILE=infinity
LimitNPROC=infinity
LimitCORE=infinity
TasksMax=infinity
TimeoutStartSec=0

[Install]
WantedBy=multi-user.target
EOF

# デーモン設定
$ mkdir /etc/sysconfig/
$ cat <<EOF > /etc/sysconfig/k3s-agent
SERVER=https://k3s-master:6443
TOKEN=K10560f5b4981b71a2c7886935ea74b52540b698b0bb0c22a6232d3884e10f18333::server:7a988ded50e84665f0cb547d45f75f52 
EOF

$ systemctl daemon-reload
$ systemctl start k3s-agent
$ systemctl status k3s-agent
$ systemctl enable k3s-agent

しばらくすると

$ kubectl get nodes
NAME           STATUS   ROLES    AGE     VERSION
k3s-master     Ready    master   6m40s   v1.19.5+k3s2
k3s-worker02   Ready    <none>   14s     v1.19.5+k3s2
k3s-worker01   Ready    <none>   14s     v1.19.5+k3s2

無事追加!

最後に

今回眠りに眠らせていたRaspbeyPi4をおうちKubernetesすることができた。
ちょっとした検証とかbotとか捗る環境にはなったと思う。
あとやり方は前記事と同じなので掲載しないが、MetalLBも導入した。
次はGitOps環境作りをやりたいな~(armイメージあるかなぁ..)

K3s+MetalLBを使ってみる

はじめに

今回は軽量なKubernetesと言われるK3sを使ってみたかったので、導入時のメモとMetalLBを導入したログを残す

VagrantVMを作成

ホストを汚したくないので、VMを作ることにする

Vagrantfile

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|

  config.vm.box = "bento/ubuntu-18.04"
  config.vm.network "private_network", ip: "192.168.33.10"
  config.vm.provider "virtualbox" do |vb|
    vb.memory = "4096"
  end
end

  あとはVagrantfileがあるディレクトリでvagrant upを実行してSSHログインする

$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'bento/ubuntu-18.04'...
==> default: Matching MAC address for NAT networking...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
$ vagrant ssh
Welcome to Ubuntu 18.04.1 LTS (GNU/Linux 4.15.0-29-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Thu Jun  4 13:28:17 UTC 2020

  System load:  0.0               Processes:           89
  Usage of /:   2.4% of 61.80GB   Users logged in:     0
  Memory usage: 3%                IP address for eth0: 10.0.2.15
  Swap usage:   0%                IP address for eth1: 192.168.33.10


0 packages can be updated.
0 updates are security updates.


vagrant@vagrant:~$ 

  k3sをインストールする前に、rootになってパッケージのアップデートを行っておく

vagrant@vagrant:~$ sudo su -
root@vagrant:~# apt update

k3sをインストール

k3sを公式ドキュメントにあるコマンドでインストールしていくが、MetalLBを使いたいのでk3sのデフォルトのservice podをデプロイしないようにオプションを追加する
k3sのデフォルトのLoadBlancerを無効にするのは公式ドキュメントを参照した

root@vagrant:~# curl -sfL https://get.k3s.io | INSTALL_K3S_EXEC="--disable servicelb" sh -
[INFO]  Finding release for channel stable
[INFO]  Using v1.18.3+k3s1 as release
[INFO]  Downloading hash https://github.com/rancher/k3s/releases/download/v1.18.3+k3s1/sha256sum-amd64.txt
[INFO]  Downloading binary https://github.com/rancher/k3s/releases/download/v1.18.3+k3s1/k3s
[INFO]  Verifying binary download
[INFO]  Installing k3s to /usr/local/bin/k3s
[INFO]  Creating /usr/local/bin/kubectl symlink to k3s
[INFO]  Creating /usr/local/bin/crictl symlink to k3s
[INFO]  Creating /usr/local/bin/ctr symlink to k3s
[INFO]  Creating killall script /usr/local/bin/k3s-killall.sh
[INFO]  Creating uninstall script /usr/local/bin/k3s-uninstall.sh
[INFO]  env: Creating environment file /etc/systemd/system/k3s.service.env
[INFO]  systemd: Creating service file /etc/systemd/system/k3s.service
[INFO]  systemd: Enabling k3s unit
Created symlink /etc/systemd/system/multi-user.target.wants/k3s.service → /etc/systemd/system/k3s.service.
[INFO]  systemd: Starting k3s
root@vagrant:~# kubectl get nodes
NAME      STATUS   ROLES    AGE   VERSION     
vagrant   Ready    master   80s   v1.18.3+k3s1
root@vagrant:~#

何事もなくインストールできた

MetalLBを導入

MetalLB, bare metal load-balancer for Kubernetes 公式ドキュメントのinstallation通りに進めていく

root@vagrant:~# kubectl apply -f https://raw.githubusercontent.com/metallb/metallb/v0.9.3/manifests/namespace.yaml
namespace/metallb-system created
root@vagrant:~# kubectl apply -f https://raw.githubusercontent.com/metallb/metallb/v0.9.3/manifests/metallb.yaml
podsecuritypolicy.policy/controller created
podsecuritypolicy.policy/speaker created
serviceaccount/controller created
serviceaccount/speaker created
clusterrole.rbac.authorization.k8s.io/metallb-system:controller created
clusterrole.rbac.authorization.k8s.io/metallb-system:speaker created
role.rbac.authorization.k8s.io/config-watcher created
role.rbac.authorization.k8s.io/pod-lister created
clusterrolebinding.rbac.authorization.k8s.io/metallb-system:controller created
clusterrolebinding.rbac.authorization.k8s.io/metallb-system:speaker created
rolebinding.rbac.authorization.k8s.io/config-watcher created
rolebinding.rbac.authorization.k8s.io/pod-lister created
daemonset.apps/speaker created
deployment.apps/controller created
root@vagrant:~# kubectl create secret generic -n metallb-system memberlist --from-literal=secretkey="$(openssl rand -base64 128)"
secret/memberlist created
root@vagrant:~#
root@vagrant:~# kubectl get pods,svc -n metallb-system
NAME                              READY   STATUS    RESTARTS   AGE
pod/controller-57f648cb96-s7kj7   1/1     Running   0          2m30s
pod/speaker-m7w9n                 1/1     Running   0          2m30s
root@vagrant:~#

L2modeで利用したいので、configmapも追加でapplyしておく Vagrantで作成したVMのprivate networkのアドレス帯が192.168.33.0/24なのでそのアドレス帯からLBのIPと使用できるように記載した
metallb-configmap.yaml

apiVersion: v1
kind: ConfigMap
metadata:
  namespace: metallb-system
  name: config
data:
  config: |
    address-pools:
    - name: default
      protocol: layer2
      addresses:
      - 192.168.33.50-192.168.33.100

ConfigMapの適用

root@vagrant:~# kubectl apply -f metallb-configmap.yaml 
configmap/config created
root@vagrant:~#

Pod + Serviceを作成してみる

導入が全て済んだので、実際にk8sのPodとServiceが動作するか試してみる お馴染み(?)のnginxを作成してみる

nginx.yaml

---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  replicas: 2
  selector:
    matchLabels:
      app: web-app
  template:
    metadata:
      labels:
        app: web-app
    spec:
      containers:
        - name: nginx-container
          image: nginx:1.12
          ports:
            - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: nginx-service
  annotations:
    cloud.google.com/load-balancer-type: "Internal"
spec:
  type: LoadBalancer
  ports:
    - name: "http-port"
      protocol: "TCP"
      port: 80
      targetPort: 80
  selector:
    app: web-app

デプロイ

root@vagrant:~# kubectl get pods,svc
NAME                                   READY   STATUS    RESTARTS   AGE
pod/nginx-deployment-964cb4cfd-bnmlc   1/1     Running   0          23s
pod/nginx-deployment-964cb4cfd-fm6g5   1/1     Running   0          23s

NAME                    TYPE           CLUSTER-IP    EXTERNAL-IP     PORT(S)        AGE
service/kubernetes      ClusterIP      10.43.0.1     <none>          443/TCP        16m
service/nginx-service   LoadBalancer   10.43.36.24   192.168.33.51   80:30456/TCP   23s

PodおよびServiceがデプロイできた EXTERNAL-IPに対してcurlしてみる

root@vagrant:~# curl 192.168.33.51
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
    body {
        width: 35em;
        margin: 0 auto;
        font-family: Tahoma, Verdana, Arial, sans-serif;
    }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>

<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>

<p><em>Thank you for using nginx.</em></p>
</body>
</html>
root@vagrant:~#

無事アクセスできた

ちなみにlogsも見てみる

root@vagrant:~# kubectl logs pod/nginx-deployment-964cb4cfd-bnmlc
10.42.0.1 - - [04/Jun/2020:14:03:01 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.58.0" "-"
root@vagrant:~#

最後に

試したかったk3sとMetalLBの導入ができた
今回は1台でMaster/Nodeの兼用だったが、Nodeの追加もできるとのことなので機会があれば試してみたいところ とても導入が楽だったので、軽いアプリの運用や手軽なデモ・習熟環境としてはすぐ使えそう