Vagrantを使用してK 8 sクラスタ環境を構成する

25282 ワード

インストール環境の設定


1.Vagrantの概要


Vagrantとは?


Vagrantは、HashiCorp社が開発したIaCツールの1つで、ワークスペース内でスクリプト形式で仮想マシン環境を迅速に作成できるツールです.
ここで、IaCはインフラストラクチャasコードの略であり、IaCツールは大きく分けてプロビジョニングツールと構成ツールに分けられる.なお、資料によっては、下図のように4種類または5種類に分けて説明してもよい.

Vagrantのインストール


Vagrantをインストールするために、筆者は直接Webブラウザからダウンロードします.

💡 注:ダウンロードリンクはここです。にあります.
パッケージマネージャでインストールする場合は、次の内容を参照してください.

パッケージマネージャのインストール(選択)

  • Windows : https://chocolatey.org/install
  • Windows 7+/Windows Server 2003+
  • PowerShell v2+
  • .NET Framework 4+
  • Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
  • macOS : https://brew.sh/index_ko
  • /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"

    一時的なダウンロードとインストール(オプション)

  • Windows
  • choco install vagrant
  • macOS
  • brew cask install vagrant
    

    2.VirtualBoxの概要


    VirtualBoxとは?


    VirtualBoxはもともとInnoTekによって開発されていたが、現在はOracleによって開発された商用・プライベートソフトウェア(限られたGPLバージョン)であり、Linux、MacOS、Solaris、Windowsをゲストオペレーティングシステムのx 86仮想化ソフトウェアに仮想化している.数年の開発を経て、限られたオープンソースバージョンのOSEがGPLの下で2007年1月に公開された.出典:ウィキペディア
    VirtualBoxのインストールは公式サイトで行えます.

    💡 注:ダウンロードリンクはここです。にあります.
    VirtualBoxのダウンロードとインストール(オプション)
    前にインストールしたパッケージマネージャからダウンロードすることもできます.
  • Windows
  • choco install virtualbox virtualbox.extensionpack
  • macOS
  • brew cask install virtualbox virtualbox-extension-pack

    3.Vagrantを使用した仮想マシンの作成


    vaguntfileのダウンロード


    筆者はWindows環境でPowerShellを使用しています.
    Linuxシステムでは、外部からファイルを受信する際にcurlまたはwgetを使用することができる.
    ただしWindowsでは使い方が違うのでInvoke-WebRequestが使えることを確認.
    Windowsシステムでは、Invoke-WebRequestcurlコマンドにも別名が設定されているので使用可能です.
    (ガシダのフィードバックを反映しています.🙏)
    💡 注:Invoke-WebRequestの使用法はDownload a File with an Alternative PowerShell wget Command、PowerShell curl関連ここです。を参照してください.
    まずPowerShellを管理者権限で実行します.

    次に、目的のパスにディレクトリを作成します.筆者はC:\Users\hyungパス上にvagrantディレクトリを作成した.
    #경로 확인
    PS C:\Users\hyung> pwd
    
    Path
    ----
    C:\Users\hyung
    
    # vagrant 디렉토리 생성
    mkdir vagrant
    その後、Invoke-WebRequestコマンドおよび-Uri -OutFileオプションを使用してファイルをダウンロードします.
    PS C:\Users\hyung\vagrant> Invoke-WebRequest -Uri https://raw.githubusercontent.com/gasida/NDKS/main/3/Vagrantfile -
    OutFile Vagrantfile
    
    # curl 명령을 사용해도 동일하게 작업 가능
    curl -Uri https://raw.githubusercontent.com/gasida/NDKS/main/3/Vagrantfile -OutFile Vagrantfile
    💡 注意:このValgrantfileは、Gashidaによって作成されたファイルを使用しています.リンク

    🤦‍♂️事件が起こる

    vagrant upコマンドの実行後、次の問題が発生しました.なぜなら、WSLを使用するために仮想化(Hyper-V)が有効になっているからです.
    😨 エラー内容:Stederr:VboxManagement.exe: error: Call to NEMR0InitVMPart2 failed: VERR_NEM_INIT_FAILED (VERR_NEM_VM_CREATE_FAILED)
    VBoxManage.exe: error: Details: code E_FAIL (0x80004005), component ConsoleWrap, interface IConsole
    PS C:\Users\hyung\vagrant> vagrant up
    Bringing machine 'k8s-m' up with 'virtualbox' provider...
    Bringing machine 'k8s-w1' up with 'virtualbox' provider...
    Bringing machine 'k8s-w2' up with 'virtualbox' provider...
    ==> k8s-m: Box 'ubuntu/focal64' could not be found. Attempting to find and install...
        k8s-m: Box Provider: virtualbox
        k8s-m: Box Version: 20211026.0.0
    ==> k8s-m: Loading metadata for box 'ubuntu/focal64'
        k8s-m: URL: https://vagrantcloud.com/ubuntu/focal64
    ==> k8s-m: Adding box 'ubuntu/focal64' (v20211026.0.0) for provider: virtualbox
        k8s-m: Downloading: https://vagrantcloud.com/ubuntu/boxes/focal64/versions/20211026.0.0/providers/virtualbox.box
    Download redirected to host: cloud-images.ubuntu.com
        k8s-m:
    ==> k8s-m: Successfully added box 'ubuntu/focal64' (v20211026.0.0) for 'virtualbox'!
    ==> k8s-m: Preparing master VM for linked clones...
        k8s-m: This is a one time operation. Once the master VM is prepared,
        k8s-m: it will be used as a base for linked clones, making the creation
        k8s-m: of new VMs take milliseconds on a modern system.
    ==> k8s-m: Importing base box 'ubuntu/focal64'...
    ==> k8s-m: Cloning VM...
    ==> k8s-m: Matching MAC address for NAT networking...
    ==> k8s-m: Checking if box 'ubuntu/focal64' version '20211026.0.0' is up to date...
    ==> k8s-m: Setting the name of the VM: Flannel-k8s-m
    ==> k8s-m: Clearing any previously set network interfaces...
    ==> k8s-m: Preparing network interfaces based on configuration...
        k8s-m: Adapter 1: nat
        k8s-m: Adapter 2: hostonly
    ==> k8s-m: Forwarding ports...
        k8s-m: 22 (guest) => 50010 (host) (adapter 1)
    ==> k8s-m: Running 'pre-boot' VM customizations...
    ==> k8s-m: Booting VM...
    There was an error while executing `VBoxManage`, a CLI used by Vagrant
    for controlling VirtualBox. The command and stderr is shown below.
    
    Command: ["startvm", "45c19cdb-af92-494a-b012-249d7e771342", "--type", "headless"]
    
    Stderr: VBoxManage.exe: error: Call to NEMR0InitVMPart2 failed: VERR_NEM_INIT_FAILED (VERR_NEM_VM_CREATE_FAILED)
    VBoxManage.exe: error: Details: code E_FAIL (0x80004005), component ConsoleWrap, interface IConsole
    この問題を解決するために、hypervisorlaunchtypeを無効にし、タスクを実行した.
    💡 注意:https://forums.virtualbox.org/viewtopic.php?f=6&t=104175&start=15

    ぶらぶらdestroy(オプション)

    vagrant destroyを実行して、以前に作成した仮想マシンを削除します.
    PS C:\Users\hyung\vagrant> vagrant destroy
    ==> k8s-w2: VM not created. Moving on...
    ==> k8s-w1: VM not created. Moving on...
        k8s-m: Are you sure you want to destroy the 'k8s-m' VM? [y/N] y
    ==> k8s-m: Destroying VM and associated drives...
    WSLを無効にして使用できますが、万が一...破壊してまた仕事をした.😅

    hypervisorの無効化と再起動

    # hyper-v 비활성화
    PS C:\Users\hyung\vagrant> bcdedit /set hypervisorlaunchtype off
    작업을 완료했습니다.
    
    # 재부팅
    PS C:\Users\hyung\vagrant> Restart-Computer

    vagrant up

    PS C:\Users\hyung\vagrant> vagrant up
    Bringing machine 'k8s-m' up with 'virtualbox' provider...
    Bringing machine 'k8s-w1' up with 'virtualbox' provider...
    Bringing machine 'k8s-w2' up with 'virtualbox' provider...
    ==> k8s-m: Preparing master VM for linked clones...
        k8s-m: This is a one time operation. Once the master VM is prepared,
        k8s-m: it will be used as a base for linked clones, making the creation
        k8s-m: of new VMs take milliseconds on a modern system.
    ==> k8s-m: Importing base box 'ubuntu/focal64'...
    ==> k8s-m: Cloning VM...
    ==> k8s-m: Matching MAC address for NAT networking...
    ==> k8s-m: Checking if box 'ubuntu/focal64' version '20211026.0.0' is up to date...
    ==> k8s-m: Setting the name of the VM: Flannel-k8s-m
    ==> k8s-m: Clearing any previously set network interfaces...
    ==> k8s-m: Preparing network interfaces based on configuration...
        k8s-m: Adapter 1: nat
        k8s-m: Adapter 2: hostonly
    ==> k8s-m: Forwarding ports...
        k8s-m: 22 (guest) => 50010 (host) (adapter 1)
    ==> k8s-m: Running 'pre-boot' VM customizations...
    ==> k8s-m: Booting VM...
    ==> k8s-m: Waiting for machine to boot. This may take a few minutes...
        k8s-m: SSH address: 127.0.0.1:50010
        k8s-m: SSH username: vagrant
        k8s-m: SSH auth method: private key
        k8s-m: Warning: Connection reset. Retrying...
        k8s-m: Warning: Connection aborted. Retrying...
        k8s-m: Warning: Remote connection disconnect. Retrying...
        k8s-m:
        k8s-m: Vagrant insecure key detected. Vagrant will automatically replace
        k8s-m: this with a newly generated keypair for better security.
        k8s-m:
        k8s-m: Inserting generated public key within guest...
        k8s-m: Removing insecure key from the guest if it's present...
        k8s-m: Key inserted! Disconnecting and reconnecting using new SSH key...
    ==> k8s-m: Machine booted and ready!
    ==> k8s-m: Checking for guest additions in VM...
    ==> k8s-m: Setting hostname...
    ==> k8s-m: Configuring and enabling network interfaces...
    ==> k8s-m: Running provisioner: shell...
    ...(중략)
    ==> k8s-w2: Running provisioner: shell...
        k8s-w2: Running: C:/Users/hyung/AppData/Local/Temp/vagrant-shell20220106-4360-17anule.sh
        k8s-w2: [preflight] Running pre-flight checks
        k8s-w2: [preflight] Reading configuration from the cluster...
        k8s-w2: [preflight] FYI: You can look at this config file with 'kubectl -n kube-system get cm kubeadm-config -o yaml'
        k8s-w2: [kubelet-start] Writing kubelet configuration to file "/var/lib/kubelet/config.yaml"
        k8s-w2: [kubelet-start] Writing kubelet environment file with flags to file "/var/lib/kubelet/kubeadm-flags.env"
        k8s-w2: [kubelet-start] Starting the kubelet
        k8s-w2: [kubelet-start] Waiting for the kubelet to perform the TLS Bootstrap...
        k8s-w2:
        k8s-w2: This node has joined the cluster:
        k8s-w2: * Certificate signing request was sent to apiserver and a response was received.
        k8s-w2: * The Kubelet was informed of the new secure connection details.
        k8s-w2:
        k8s-w2: Run 'kubectl get nodes' on the control-plane to see this node join the cluster.
    タスクが完了したら、VirtualBoxで作成したMaster-1、Worker-1、およびWorker-2が正常であることを確認します.
    PS C:\Users\hyung\vagrant> vagrant status
    Current machine states:
    
    k8s-m                     running (virtualbox)
    k8s-w1                    running (virtualbox)
    k8s-w2                    running (virtualbox)
    
    This environment represents multiple VMs. The VMs are all listed
    above with their current state. For more information about a specific
    VM, run `vagrant status NAME`.
  • VirtualBoxで作成された仮想マシンのリスト
  • 生成されたMasterノードvagrant sshに接続される.
    PS C:\Users\hyung\vagrant> vagrant ssh k8s-m
    Welcome to Ubuntu 20.04.3 LTS (GNU/Linux 5.4.0-92-generic x86_64)
    
     * Documentation:  https://help.ubuntu.com
     * Management:     https://landscape.canonical.com
     * Support:        https://ubuntu.com/advantage
    
      System information as of Thu Jan  6 03:18:42 UTC 2022
    
      System load:  0.53              Users logged in:          0
      Usage of /:   8.2% of 38.71GB   IPv4 address for cni0:    172.16.0.1
      Memory usage: 22%               IPv4 address for docker0: 172.17.0.1
      Swap usage:   0%                IPv4 address for enp0s3:  10.0.2.15
      Processes:    159               IPv4 address for enp0s8:  192.168.100.10
    
    3 updates can be applied immediately.
    To see these additional updates run: apt list --upgradable
    
    (|admin-k8s:default) root@k8s-m:~#
    ホストノードが正常にSSH接続されていることを確認します.次に、各ノードのステータスを確認して、クラスタが正常に構成されているかどうかを確認します.
    (|admin-k8s:default) root@k8s-m:~# kubectl get nodes -o wide
    NAME     STATUS   ROLES                  AGE   VERSION   INTERNAL-IP       EXTERNAL-IP   OS-IMAGE             KERNEL-VERSION     CONTAINER-RUNTIME
    k8s-m    Ready    control-plane,master   42m   v1.21.8   192.168.100.10    <none>        Ubuntu 20.04.3 LTS   5.4.0-92-generic   docker://20.10.12
    k8s-w1   Ready    <none>                 37m   v1.21.8   192.168.100.101   <none>        Ubuntu 20.04.3 LTS   5.4.0-92-generic   docker://20.10.12
    k8s-w2   Ready    <none>                 33m   v1.21.8   192.168.100.102   <none>        Ubuntu 20.04.3 LTS   5.4.0-92-generic   docker://20.10.12
    VirtualBoxとVagrantを使用してK 8 sクラスタを構成する方法について簡単に説明します.
    次の記事では、簡単な実践とKubernets Advanced Network Studio(=KANS)研究について連載します.