Windows部署K8S


在这里插入图片描述

参考链接

官网链接

安装Chocolatey

安装启动minikube参考链接

启动minikube失败参考链接

官网部署文档

在 Windows 上安装和设置 kubectl

在你开始之前

您必须使用与集群的一个次要版本差异内的 kubectl 版本。例如,v1.23 客户端可以与 v1.22、v1.23 和 v1.24 控制平面通信。使用 kubectl 的最新兼容版本有助于避免不可预见的问题。
事先安装docker,可以参考官方文档

在 Windows 上安装 kubectl

在 Windows 上安装 kubectl 有以下方法:

  • 在 Windows 上使用 curl 安装 kubectl 二进制文件
  • 使用 Chocolatey 或 Scoop 在 Windows 上安装
在 Windows 上使用 curl 安装 kubectl 二进制文件
  1. 下载最新版本 v1.23.0。

    或者,如果您已curl安装,请使用以下命令:

curl -LO "https://dl.k8s.io/release/v1.23.0/bin/windows/amd64/kubectl.exe"

注意:要查找最新的稳定版本(例如,用于脚本),请查看https://dl.k8s.io/release/stable.txt

  1. 验证二进制文件(可选)

    下载 kubectl 校验和文件:

curl -LO "https://dl.k8s.io/v1.23.0/bin/windows/amd64/kubectl.exe.sha256"
根据校验和文件验证 kubectl 二进制文件:
  • 使用命令提示符手动将CertUtil的输出与下载的校验和文件进行比较:
CertUtil -hashfile kubectl.exe SHA256
type kubectl.exe.sha256
  • 使用 PowerShell 使用-eq运算符自动验证以获取TrueFalse结果:
$($(CertUtil -hashfile .\kubectl.exe SHA256)[1] -replace " ", "") -eq $(type .\kubectl.exe.sha256)
  1. 将 kubectl 二进制文件夹附加或添加到您的PATH环境变量中。

  2. 测试以确保版本kubectl与下载的相同:

kubectl version --client

注意: Docker Desktop for Windows添加了自己的kubectlto版本PATH。如果您之前安装过 Docker Desktop,您可能需要将您的PATH条目放在 Docker Desktop 安装程序添加的条目之前,或者删除 Docker Desktop 的kubectl.

使用 Chocolatey 或 Scoop 在 Windows 上安装
  1. 要在 Windows 上安装 kubectl,您可以使用Chocolatey包管理器或Scoop命令行安装程序。

    Chocolatey:

choco install kubernetes-cli
Scoop:
scoop install kubectl
  1. 测试以确保您安装的版本是最新的:
kubectl version --client
  1. 导航到您的主目录:
# If you're using cmd.exe, run: cd %USERPROFILE%
cd ~
  1. 创建.kube目录:
mkdir .kube
  1. 切换到.kube刚刚创建的目录:
cd .kube
  1. 配置 kubectl 以使用远程 Kubernetes 集群:
New-Item config -type file

注意:使用您选择的文本编辑器(例如记事本)编辑配置文件。

验证 kubectl 配置

为了让 kubectl 找到和访问 Kubernetes 集群,它需要一个 kubeconfig 文件,该文件在您使用kube-up.sh创建集群 或成功部署 Minikube 集群时自动创建。默认情况下,kubectl 配置位于~/.kube/config.

通过获取集群状态检查 kubectl 是否正确配置:

kubectl cluster-info

如果您看到 URL 响应,则 kubectl 已正确配置为访问您的集群。

如果您看到类似以下的消息,则 kubectl 配置不正确或无法连接到 Kubernetes 集群。

The connection to the server <server-name:port> was refused - did you specify the right host or port?

例如,如果您打算在笔记本电脑上(本地)运行 Kubernetes 集群,则需要先安装 Minikube 之类的工具,然后重新运行上述命令。

如果 kubectl cluster-info 返回 url 响应但您无法访问您的集群,请检查它是否配置正确,请使用:

kubectl cluster-info dump

可选的 kubectl 配置和插件

启用 shell 自动完成

kubectl 为 Bash、Zsh、Fish 和 PowerShell 提供了自动补全支持,可以为您节省大量输入。

以下是为 PowerShell 设置自动完成的过程。

可以使用命令生成 PowerShell 的 kubectl 完成脚本kubectl completion powershell

要在所有 shell 会话中执行此操作,请将以下行添加到$PROFILE文件中:

kubectl completion powershell | Out-String | Invoke-Expression

此命令将在每次 PowerShell 启动时重新生成自动完成脚本。您还可以将生成的脚本直接添加到您的$PROFILE文件中。

要将生成的脚本添加到您的$PROFILE文件中,请在您的 powershell 提示符下运行以下行:

kubectl completion powershell >> $PROFILE

重新加载 shell 后,kubectl 自动完成功能应该可以工作了。

安装kubectl convert插件

Kubernetes 命令行工具的插件kubectl,允许您在不同 API 版本之间转换清单。这对于将清单迁移到具有较新 Kubernetes 版本的非弃用 api 版本特别有用。有关更多信息,请访问迁移到非弃用 api

  1. 使用以下命令下载最新版本:
curl -LO "https://dl.k8s.io/release/v1.23.0/bin/windows/amd64/kubectl-convert.exe"
  1. 验证二进制文件(可选)

    下载 kubectl-convert 校验和文件:

curl -LO "https://dl.k8s.io/v1.23.0/bin/windows/amd64/kubectl-convert.exe.sha256"
根据校验和文件验证 kubectl-convert 二进制文件:
  • 使用命令提示符手动将CertUtil的输出与下载的校验和文件进行比较:
CertUtil -hashfile kubectl-convert.exe SHA256
type kubectl-convert.exe.sha256
  • 使用 PowerShell 使用-eq运算符自动验证以获取 aTrue或False结果:
$($(CertUtil -hashfile .\kubectl-convert.exe SHA256)[1] -replace " ", "") -eq $(type .\kubectl-convert.exe.sha256)
  1. 将 kubectl 二进制文件夹附加或添加到您的PATH环境变量中。

  2. 验证插件是否安装成功

kubectl convert --help

如果您没有看到错误,则表示插件已成功安装。

问题处理(相关组件安装)

安装chocolatey工具

安装Chocolatey

安装choco
要求:Windows 7+ / Windows Server 2003+
以管理员权限运行cmd.exc或powershell.exe
cmd运行
@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"
powershell运行
Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
安装完成,运行choco 或 choco -?检查一下是否安装正确。

 PS C:\Windows\system32> Set-ExecutionPolicy Bypass -Scope Process -Force; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
Forcing web requests to allow TLS v1.2 (Required for requests to Chocolatey.org)
Getting latest version of the Chocolatey package for download.
Not using proxy.
Getting Chocolatey from https://community.chocolatey.org/api/v2/package/chocolatey/0.12.1.
Downloading https://community.chocolatey.org/api/v2/package/chocolatey/0.12.1 to C:\Users\****-2~1\AppData\Local\Temp\chocolatey\chocoInstall\chocolatey.zip
Not using proxy.
Extracting C:\Users\****-2~1\AppData\Local\Temp\chocolatey\chocoInstall\chocolatey.zip to C:\Users\****-2~1\AppData\Local\Temp\chocolatey\chocoInstall
Installing Chocolatey on the local machine
Creating ChocolateyInstall as an environment variable (targeting 'Machine')
  Setting ChocolateyInstall to 'C:\ProgramData\chocolatey'
WARNING: It's very likely you will need to close and reopen your shell
  before you can use choco.'
Restricting write permissions to Administrators
We are setting up the Chocolatey package repository.
The packages themselves go to 'C:\ProgramData\chocolatey\lib'
  (i.e. C:\ProgramData\chocolatey\lib\yourPackageName).
A shim file for the command line goes to 'C:\ProgramData\chocolatey\bin'
  and points to an executable in 'C:\ProgramData\chocolatey\lib\yourPackageName'.

Creating Chocolatey folders if they do not already exist.

WARNING: You can safely ignore errors related to missing log files when
  upgrading from a version of Chocolatey less than 0.9.9.
  'Batch file could not be found' is also safe to ignore.
  'The system cannot find the file specified' - also safe.
chocolatey.nupkg file not installed in lib.
 Attempting to locate it from bootstrapper.
PATH environment variable does not have C:\ProgramData\chocolatey\bin in it. Adding...
警告: Not setting tab completion: Profile file does not exist at
'C:\Users\****-2020-NB019\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1'.
Chocolatey (choco.exe) is now ready.
You can call choco from anywhere, command line or powershell by typing choco.
Run choco /? for a list of functions.
You may need to shut down and restart powershell and/or consoles
 first prior to using choco.
Ensuring Chocolatey commands are on the path
Ensuring chocolatey.nupkg is in the lib folder
PS C:\Windows\system32>
PS C:\Windows\system32> choco
Chocolatey v0.12.1
Please run 'choco -?' or 'choco <command> -?' for help menu.
PS C:\Windows\system32> choco -?
This is a listing of all of the different things you can pass to choco.

Options and Switches

 -v, --version
     Version - Prints out the Chocolatey version. Available in 0.9.9+.

Commands

 * find - searches remote or local packages (alias for search)
 * list - lists remote or local packages
 * search - searches remote or local packages (alias for list)
 * help - displays top level help information for choco
 * info - retrieves package information. Shorthand for choco search pkgname --exact --verbose
 * install - installs packages using configured sources
 * pin - suppress upgrades for a package
 * outdated - retrieves information about packages that are outdated. Similar to upgrade all --noop
 * upgrade - upgrades packages from various sources
 * uninstall - uninstalls a package
 * pack - packages nuspec, scripts, and other Chocolatey package resources into a nupkg file
 * push - pushes a compiled nupkg to a source
 * new - creates template files for creating a new Chocolatey package
 * source - view and configure default sources
 * sources - view and configure default sources (alias for source)
 * config - Retrieve and configure config file settings
 * features - view and configure choco features (alias for feature)
 * feature - view and configure choco features
 * apikey - retrieves, saves or deletes an apikey for a particular source
 * setapikey - retrieves, saves or deletes an apikey for a particular source (alias for apikey)
 * unpackself - re-installs Chocolatey base files
 * version - [DEPRECATED] will be removed in v1 - use `choco outdated` or `cup <pkg|all> -whatif` instead
 * update - [DEPRECATED] RESERVED for future use (you are looking for upgrade, these are not the droids you are looking for)
 * export - exports list of currently installed packages
 * template - get information about installed templates
 * templates - get information about installed templates (alias for template)

......此处省略N行......
     --proxy-bypass-on-local
     Proxy Bypass On Local - Bypass proxy for local connections. Requires
       explicit proxy (`--proxy` or config setting). Overrides the default
       proxy bypass on local setting of 'True'. Available in 0.10.4+.

     --log-file=VALUE
     Log File to output to in addition to regular loggers. Available in 0.1-
       0.8+.
Chocolatey v0.12.1
PS C:\Windows\system32>

安装minikube工具

安装启动minikube参考链接
以管理员身份运行一个cmd.exe,启动minikube:minikube start
起动时间会比较长。
启动minikube在这里插入图片描述

详细步骤参考官方文档

k8s安装实操步骤

PS D:\opt\work> curl -LO "https://dl.k8s.io/release/v1.23.0/bin/windows/amd64/kubectl.exe"
Invoke-WebRequest : 找不到与参数名称“LO”匹配的参数。
所在位置 行:1 字符: 6
+ curl -LO "https://dl.k8s.io/release/v1.23.0/bin/windows/amd64/kubectl.exe"
+      ~~~
    + CategoryInfo          : InvalidArgument: (:) [Invoke-WebRequest],ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

PS D:\opt\work> curl

位于命令管道位置 1 的 cmdlet Invoke-WebRequest
请为以下参数提供值:
Uri:
curl : 无效的 URI: 未能分析主机名。
所在位置 行:1 字符: 1
+ curl
+ ~~~~
    + CategoryInfo          : NotSpecified: (:) [Invoke-WebRequest], UriFormatException
    + FullyQualifiedErrorId : System.UriFormatException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

PS D:\opt\work> certutil.exe
CertUtil: -dump 命令成功完成。
PS D:\opt\work> ls


    目录: D:\opt\work


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----          2022/2/7     17:58                kubernetes
d-----        2021/12/29     17:58                mysql8
d-----          2022/1/4     18:23                tomcat8
d-----          2022/1/4     18:00                tomcat9
-a----        2021/12/24     14:50            226 Dockerfile
-a----        2021/12/27     17:34             70 Dockerfile2
-a----        2021/12/28      9:44             77 Dockerfile3


PS D:\opt\work> cd .\kubernetes\
PS D:\opt\work\kubernetes> ls


    目录: D:\opt\work\kubernetes


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----          2022/2/7     17:57       47827456 kubectl.exe


PS D:\opt\work\kubernetes> certutil -hashfile .\kubectl.exe SHA256
SHA256 的 .\kubectl.exe 哈希:
5e504bb9c553e66983f2e59d0c3e2ab19e3a4961ecea998dc617aa80a8c193f3
CertUtil: -hashfile 命令成功完成。
PS D:\opt\work\kubernetes> type .\kubectl.exe.sha256
5e504bb9c553e66983f2e59d0c3e2ab19e3a4961ecea998dc617aa80a8c193f3
PS D:\opt\work\kubernetes> $($(CertUtil -hashfile .\kubectl.exe SHA256)[1] -replace " ", "") -eq $(type .\kubectl.exe.sha256)
True
PS D:\opt\work\kubernetes> kubectl version --client
Client Version: version.Info{Major:"1", Minor:"21", GitVersion:"v1.21.5", GitCommit:"aea7bbadd2fc0cd689de94a54e5b7b758869d691", GitTreeState:"clean", BuildDate:"2021-09-15T21:10:45Z", GoVersion:"go1.16.8", Compiler:"gc", Platform:"windows/amd64"}
PS D:\opt\work\kubernetes>
--------------以管理员身份运行----------------
PS C:\Windows\system32> choco
Chocolatey v0.12.1
Please run 'choco -?' or 'choco <command> -?' for help menu.
PS C:\Windows\system32> choco install kubernetes-cli
Chocolatey v0.12.1
Installing the following packages:
kubernetes-cli
By installing, you accept licenses for the packages.
Progress: Downloading kubernetes-cli 1.23.3... 100%

kubernetes-cli v1.23.3 [Approved]
kubernetes-cli package files install completed. Performing other installation steps.
The package kubernetes-cli wants to run 'chocolateyInstall.ps1'.
Note: If you don't run this script, the installation will fail.'
Note: To confirm automatically next time, use '-y' or consider:
choco feature enable -n allowGlobalConfirmation
Do you want to run the script?([Y]es/[A]ll - yes to all/[N]o/[P]rint): Y

Extracting 64-bit C:\ProgramData\chocolatey\lib\kubernetes-cli\tools\kubernetes-client-windows-amd64.tar.gz to C:\ProgramData\chocolatey\lib\kubernetes-cli\tools...
C:\ProgramData\chocolatey\lib\kubernetes-cli\tools
Extracting 64-bit C:\ProgramData\chocolatey\lib\kubernetes-cli\tools\kubernetes-client-windows-amd64.tar to C:\ProgramData\chocolatey\lib\kubernetes-cli\tools...
C:\ProgramData\chocolatey\lib\kubernetes-cli\tools
 ShimGen has successfully created a shim for kubectl-convert.exe
 ShimGen has successfully created a shim for kubectl.exe
 The install of kubernetes-cli was successful.
  Software installed to 'C:\ProgramData\chocolatey\lib\kubernetes-cli\tools'

Chocolatey installed 1/1 packages.
 See the log for details (C:\ProgramData\chocolatey\logs\chocolatey.log).
PS C:\Windows\system32> kubectl version --client
Client Version: version.Info{Major:"1", Minor:"23", GitVersion:"v1.23.0", GitCommit:"ab69524f795c42094a6630298ff53f3c3ebab7f4", GitTreeState:"clean", BuildDate:"2021-12-07T18:16:20Z", GoVersion:"go1.17.3", Compiler:"gc", Platform:"windows/amd64"}
PS C:\Windows\system32>
PS C:\Windows\system32> cd ~
PS C:\Users\****-2020-NB019> ls


    目录: C:\Users\****-2020-NB019


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----        2021/11/18     16:33                .android
d-----        2021/12/10     14:47                .aws
d-----        2021/12/10     14:47                .azure
d-----        2021/12/22     10:51                .docker
d-----         2021/8/23     14:26                .eclipse
d-----          2021/6/9     10:26                .InstallAnywhere
d-----         2021/6/17     16:06                .kettle
d-----         2021/6/17     16:06                .kingbase
d-----          2022/2/8      9:42                .kube
d-----        2021/11/26     10:50                .m2
d-----         2021/4/19     14:49                .minio
d-----         2021/4/14     16:57                .oracle_jre_usage
d-----        2021/11/19     20:30                .oss-browser
d-----        2021/12/30     13:56                .p2
d-----         2022/1/20     10:58                .ssh
d-----         2021/4/14     16:34                .swt
d-----         2021/7/12     11:48                .tooling
d-----        2021/10/22     14:07                .vscode
d-r---        2020/12/21      4:00                3D Objects
d-r---        2020/12/21      4:00                Contacts
d-----          2022/2/7     16:01                Desktop
d-r---         2022/1/26     15:59                Documents
d-----          2022/2/7     18:12                Downloads
d-----         2021/8/25     14:00                eclipse-workspace
d-r---        2020/12/21      4:00                Favorites
d-----         2021/11/8     11:03                getting-started
d-----        2020/12/22     15:59                HBuilder
d-----        2020/12/22     15:59                HBuilder settings
d-----        2020/12/22     15:59                HBuilderProjects
d-----        2021/10/18     18:04                IdeaProjects
d-r---        2020/12/21      4:00                Links
d-r---        2020/12/21      4:00                Music
d-r---         2021/4/23     15:16                OneDrive
d-r---         2021/4/20     17:41                Pictures
d-r---        2020/12/21      4:00                Saved Games
d-r---        2020/12/21      4:01                Searches
d-r---          2021/4/6     13:57                Videos
-a----         2022/1/20     11:45           8407 .bash_history
-ar---        2020/12/22      0:00             20 .erlang.cookie
-a----         2021/11/8     17:58             24 .gitconfig
-a----          2022/1/4     16:56             20 .lesshst
-a----         2021/12/8     11:44            828 .viminfo

PS C:\Users\****-2020-NB019> cd .\.kube\
PS C:\Users\****-2020-NB019\.kube> ls


    目录: C:\Users\****-2020-NB019\.kube


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----          2022/2/8      9:42              0 config

----------------------验证 kubectl 配置------------------------------
PS C:\Users\****-2020-NB019\.kube> kubectl cluster-info
Kubernetes control plane is running at https://127.0.0.1:53439
CoreDNS is running at https://127.0.0.1:53439/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy

To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
PS C:\Users\****-2020-NB019\.kube> kubectl cluster-info dump
******此处忽略---检查它是否配置正确日志**********
----------------------------------------
PS C:\Users\****-2020-NB019\.kube> kubectl completion powershell

# Copyright 2016 The Kubernetes Authors.
#
# 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.
# powershell completion for kubectl                              -*- shell-script -*-

function __kubectl_debug {
    if ($env:BASH_COMP_DEBUG_FILE) {
        "$args" | Out-File -Append -FilePath "$env:BASH_COMP_DEBUG_FILE"
    }
}

filter __kubectl_escapeStringWithSpecialChars {
    $_ -replace '\s|#|@|\$|;|,|''|\{|\}|\(|\)|"|`|\||<|>|&','`$&'
}

Register-ArgumentCompleter -CommandName 'kubectl' -ScriptBlock {
    param(
            $WordToComplete,
            $CommandAst,
            $CursorPosition
        )

    # Get the current command line and convert into a string
    $Command = $CommandAst.CommandElements
    $Command = "$Command"

    __kubectl_debug ""
    __kubectl_debug "========= starting completion logic =========="
    __kubectl_debug "WordToComplete: $WordToComplete Command: $Command CursorPosition: $CursorPosition"

    # The user could have moved the cursor backwards on the command-line.
    # We need to trigger completion from the $CursorPosition location, so we need
    # to truncate the command-line ($Command) up to the $CursorPosition location.
    # Make sure the $Command is longer then the $CursorPosition before we truncate.
    # This happens because the $Command does not include the last space.
    if ($Command.Length -gt $CursorPosition) {
        $Command=$Command.Substring(0,$CursorPosition)
    }
        __kubectl_debug "Truncated command: $Command"

    $ShellCompDirectiveError=1
    $ShellCompDirectiveNoSpace=2
    $ShellCompDirectiveNoFileComp=4
    $ShellCompDirectiveFilterFileExt=8
    $ShellCompDirectiveFilterDirs=16

        # Prepare the command to request completions for the program.
    # Split the command at the first space to separate the program and arguments.
    $Program,$Arguments = $Command.Split(" ",2)
    $RequestComp="$Program __complete $Arguments"
    __kubectl_debug "RequestComp: $RequestComp"

    # we cannot use $WordToComplete because it
    # has the wrong values if the cursor was moved
    # so use the last argument
    if ($WordToComplete -ne "" ) {
        $WordToComplete = $Arguments.Split(" ")[-1]
    }
    __kubectl_debug "New WordToComplete: $WordToComplete"


    # Check for flag with equal sign
    $IsEqualFlag = ($WordToComplete -Like "--*=*" )
    if ( $IsEqualFlag ) {
        __kubectl_debug "Completing equal sign flag"
        # Remove the flag part
        $Flag,$WordToComplete = $WordToComplete.Split("=",2)
    }

    if ( $WordToComplete -eq "" -And ( -Not $IsEqualFlag )) {
        # If the last parameter is complete (there is a space following it)
        # We add an extra empty parameter so we can indicate this to the go method.
        __kubectl_debug "Adding extra empty parameter"
        # We need to use `"`" to pass an empty argument a "" or '' does not work!!!
        $RequestComp="$RequestComp" + ' `"`"'
    }

    __kubectl_debug "Calling $RequestComp"
    #call the command store the output in $out and redirect stderr and stdout to null
    # $Out is an array contains each line per element
    Invoke-Expression -OutVariable out "$RequestComp" 2>&1 | Out-Null


    # get directive from last line
    [int]$Directive = $Out[-1].TrimStart(':')
    if ($Directive -eq "") {
        # There is no directive specified
        $Directive = 0
    }
    __kubectl_debug "The completion directive is: $Directive"

    # remove directive (last element) from out
    $Out = $Out | Where-Object { $_ -ne $Out[-1] }
    __kubectl_debug "The completions are: $Out"

    if (($Directive -band $ShellCompDirectiveError) -ne 0 ) {
        # Error code.  No completion.
        __kubectl_debug "Received error from custom completion go code"
        return
    }

    $Longest = 0
    $Values = $Out | ForEach-Object {
        #Split the output in name and description
        $Name, $Description = $_.Split("`t",2)
        __kubectl_debug "Name: $Name Description: $Description"

        # Look for the longest completion so that we can format things nicely
        if ($Longest -lt $Name.Length) {
            $Longest = $Name.Length
        }

        # Set the description to a one space string if there is none set.
        # This is needed because the CompletionResult does not accept an empty string as argument
        if (-Not $Description) {
            $Description = " "
        }
        @{Name="$Name";Description="$Description"}
    }


    $Space = " "
    if (($Directive -band $ShellCompDirectiveNoSpace) -ne 0 ) {
        # remove the space here
        __kubectl_debug "ShellCompDirectiveNoSpace is called"
        $Space = ""
    }

    if ((($Directive -band $ShellCompDirectiveFilterFileExt) -ne 0 ) -or
       (($Directive -band $ShellCompDirectiveFilterDirs) -ne 0 ))  {
        __kubectl_debug "ShellCompDirectiveFilterFileExt ShellCompDirectiveFilterDirs are not supported"

        # return here to prevent the completion of the extensions
        return
    }

    $Values = $Values | Where-Object {
        # filter the result
        $_.Name -like "$WordToComplete*"

        # Join the flag back if we have an equal sign flag
        if ( $IsEqualFlag ) {
            __kubectl_debug "Join the equal sign flag back to the completion value"
            $_.Name = $Flag + "=" + $_.Name
        }
    }

    if (($Directive -band $ShellCompDirectiveNoFileComp) -ne 0 ) {
        __kubectl_debug "ShellCompDirectiveNoFileComp is called"

        if ($Values.Length -eq 0) {
            # Just print an empty string here so the
            # shell does not start to complete paths.
            # We cannot use CompletionResult here because
            # it does not accept an empty string as argument.
            ""
            return
        }
    }

    # Get the current mode
    $Mode = (Get-PSReadLineKeyHandler | Where-Object {$_.Key -eq "Tab" }).Function
    __kubectl_debug "Mode: $Mode"

    $Values | ForEach-Object {

        # store temporary because switch will overwrite $_
        $comp = $_

        # PowerShell supports three different completion modes
        # - TabCompleteNext (default windows style - on each key press the next option is displayed)
        # - Complete (works like bash)
        # - MenuComplete (works like zsh)
        # You set the mode with Set-PSReadLineKeyHandler -Key Tab -Function <mode>

        # CompletionResult Arguments:
        # 1) CompletionText text to be used as the auto completion result
        # 2) ListItemText   text to be displayed in the suggestion list
        # 3) ResultType     type of completion result
        # 4) ToolTip        text for the tooltip with details about the object

        switch ($Mode) {

            # bash like
            "Complete" {

                if ($Values.Length -eq 1) {
                    __kubectl_debug "Only one completion left"

                    # insert space after value
                    [System.Management.Automation.CompletionResult]::new($($comp.Name | __kubectl_escapeStringWithSpecialChars) + $Space, "$($comp.Name)", 'ParameterValue', "$($comp.Description)")

                } else {
                    # Add the proper number of spaces to align the descriptions
                    while($comp.Name.Length -lt $Longest) {
                        $comp.Name = $comp.Name + " "
                    }

                    # Check for empty description and only add parentheses if needed
                    if ($($comp.Description) -eq " " ) {
                        $Description = ""
                    } else {
                        $Description = "  ($($comp.Description))"
                    }
                    [System.Management.Automation.CompletionResult]::new("$($comp.Name)$Description", "$($comp.Name)$Description", 'ParameterValue', "$($comp.Description)")
                }
             }

            # zsh like
            "MenuComplete" {
                # insert space after value
                # MenuComplete will automatically show the ToolTip of
                # the highlighted value at the bottom of the suggestions.
                [System.Management.Automation.CompletionResult]::new($($comp.Name | __kubectl_escapeStringWi            }

            # TabCompleteNext and in case we get something unknown
            Default {
                # Like MenuComplete but we don't want to add a space here because
                # the user need to press space anyway to get the completion.
                # Description will not be shown because thats not possible with TabCompleteNext
                [System.Management.Automation.CompletionResult]::new($($comp.Name | __kubectl_escapeStringWithSpecialChars), "$($comp.Name)", 'ParameterValue', "$($comp.Description)")

    }
}
PS C:\Users\****-2020-NB019\.kube> ls


    目录: C:\Users\****-2020-NB019\.kube


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----

PS C:\Users\****-2020-NB019\.kube\cache> ls



Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----          2022/2/8     14:23                discovery
d-----          2022/2/8     14:23                http


PS C:\Users\****-2020-NB019\.kube\cache> cd .\discovery\

    目录: C:\Users\****-2020-NB019\.kube\cache\discovery


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d-----          2022/2/8     14:23                127.0.0.1_53439

PS C:\Users\****-2020-NB019\.kube> $PROFILE
C:\Users\****-2020-NB019\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
PS C:\Users\****-2020-NB019\.kube> kubectl completion powershell | Out-String | Invoke-Expression

-----------------------安装kubectl convert插件-------------------------
PS D:\opt\work\kubernetes>
PS D:\opt\work\kubernetes> ls


    目录: D:\opt\work\kubernetes


Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
-a----          2022/2/8     14:29       43828224 kubectl-convert.exe
-a----          2022/2/8     14:33             64 kubectl-convert.exe.sha256
-a----          2022/2/7     17:57       47827456 kubectl.exe
-a----          2022/2/7     18:03             64 kubectl.exe.sha256
-a----          2022/2/8     10:03       29645555 minikube-installer.exe


PS D:\opt\work\kubernetes> $($(CertUtil -hashfile .\kubectl-convert.exe SHA256)[1] -replace " ", "") -eq $(type .\kubectl-convert.exe.sha256)
True
PS D:\opt\work\kubernetes> CertUtil -hashfile kubectl-convert.exe SHA256
SHA256 的 kubectl-convert.exe 哈希:
e54da455fed15ec2e50cdddcea1ae18df31d18ad240077eaa28dd239db60122f
CertUtil: -hashfile 命令成功完成。
PS D:\opt\work\kubernetes> type kubectl-convert.exe.sha256
e54da455fed15ec2e50cdddcea1ae18df31d18ad240077eaa28dd239db60122f
PS D:\opt\work\kubernetes> $($(CertUtil -hashfile .\kubectl-convert.exe SHA256)[1] -replace " ", "") -eq $(type .\kubectl-convert.exe.sha256)
True
PS D:\opt\work\kubernetes> kubectl convert --help
Convert config files between different API versions. Both YAML and JSON formats are accepted.

 The command takes filename, directory, or URL as input, and convert it into format of version specified by --output-version flag. If target version is not specified or not supported, convert to latest version.

 The default output will be printed to stdout in YAML format. One can use -o option to change to output destination.

Usage:
  convert -f FILENAME

Examples:
  # Convert 'pod.yaml' to latest version and print to stdout.
  kubectl convert -f pod.yaml

  # Convert the live state of the resource specified by 'pod.yaml' to the latest version
  # and print to stdout in JSON format.
  kubectl convert -f pod.yaml --local -o json

  # Convert all files under current directory to latest version and create them all.
  kubectl convert -f . | kubectl create -f -

Flags:
      --add-dir-header                   If true, adds the file directory to the header of the log messages (DEPRECATED: will be removed in a future release, see https://github.com/kubernetes/enhancements/tree/master/keps/sig-instrumentation/2845-deprecate-klog-specific-flags-in-k8s-components)
      --allow-missing-template-keys      If true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats. (default true)
      --alsologtostderr                  log to standard error as well as files (DEPRECATED: will be removed in a future release, see https://github.com/kubernetes/enhancements/tree/master/keps/sig-instrumentation/2845-deprecate-klog-specific-flags-in-k8s-components)
      --as string                        Username to impersonate for the operation. User could be a regular user or a service account in a namespace.
      --as-group stringArray             Group to impersonate for the operation, this flag can be repeated to specify multiple groups.
      --as-uid string                    UID to impersonate for the operation.
      --cache-dir string                 Default cache directory (default "C:\\Users\\****-2020-NB019\\.kube\\cache")
      --certificate-authority string     Path to a cert file for the certificate authority
      --client-certificate string        Path to a client certificate file for TLS
      --client-key string                Path to a client key file for TLS
      --cluster string                   The name of the kubeconfig cluster to use
      --context string                   The name of the kubeconfig context to use
  -f, --filename strings                 Filename, directory, or URL to files to need to get converted.
  -h, --help                             help for convert
      --insecure-skip-tls-verify         If true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure
      --kubeconfig string                Path to the kubeconfig file to use for CLI requests.
  -k, --kustomize string                 Process the kustomization directory. This flag can't be used together with -f or -R.
      --local                            If true, convert will NOT try to contact api-server but run locally. (default true)
      --log-backtrace-at traceLocation   when logging hits line file:N, emit a stack trace (default :0) (DEPRECATED: will be removed in a future release, see https://github.com/kubernetes/enhancements/tree/master/keps/sig-instrumentation/2845-deprecate-klog-specific-flags-in-k8s-components)
      --log-dir string                   If non-empty, write log files in this directory (DEPRECATED: will be removed in a future release, see https://github.com/kubernetes/enhancements/tree/master/keps/sig-instrumentation/2845-deprecate-klog-specific-flags-in-k8s-components)
      --log-file string                  If non-empty, use this log file (DEPRECATED: will be removed in a future release, see https://github.com/kubernetes/enhancements/tree/master/keps/sig-instrumentation/2845-deprecate-klog-specific-flags-in-k8s-components)
      --log-file-max-size uint           Defines the maximum size a log file can grow to. Unit is megabytes. If the value is 0, the maximum file size is unlimited. (default 1800) (DEPRECATED: will be removed in a future release, see https://github.com/kubernetes/enhancements/tree/master/keps/sig-instrumentation/2845-deprecate-klog-specific-flags-in-k8s-components)
      --log-flush-frequency duration     Maximum number of seconds between log flushes (default 5s)
      --logtostderr                      log to standard error instead of files (default true) (DEPRECATED: will be removed in a future release, see https://github.com/kubernetes/enhancements/tree/master/keps/sig-instrumentation/2845-deprecate-klog-specific-flags-in-k8s-components)
      --match-server-version             Require server version to match client version
  -n, --namespace string                 If present, the namespace scope for this CLI request
      --one-output                       If true, only write logs to their native severity level (vs also writing to each lower severity level) (DEPRECATED: will be removed in a future release, see https://github.com/kubernetes/enhancements/tree/master/keps/sig-instrumentation/2845-deprecate-klog-specific-flags-in-k8s-components)
  -o, --output string                    Output format. One of: json|yaml|name|go-template|go-template-file|template|templatefile|jsonpath|jsonpath-as-json|jsonpath-file. (default "yaml")
      --output-version string            Output the formatted object with the given group version (for ex: 'extensions/v1beta1').
      --password string                  Password for basic authentication to the API server
  -R, --recursive                        Process the directory used in -f, --filename recursively. Useful when you want to manage related manifests organized within the same directory.
      --request-timeout string           The length of time to wait before giving up on a single server requ timeout requests. (default "0")
  -s, --server string                    The address and port of the Kubernetes API server
      --show-managed-fields              If true, keep the managedFields when printing objects in JSON or YA      --skip-headers                     If true, avoid header prefixes in the log messages (DEPRECATED: will be removed in a future release, see https://github.com/kubernetes/enhancements/tree/master/keps/sig-instrumentation/2845-deprecate-klog-specific-flags-in-k8s-components)
      --skip-log-headers                 If true, avoid headers when opening log files (DEPRECATED: will be removed in a future release, see https://github.com/kubernetes/enhancements/tree/master/keps/sig-instrumentation/2845-deprecate-klog-specific-flags-in-k8s-components)
      --stderrthreshold severity         logs at or above this threshold go to stderr (default 2) (DEPRECATED: will be removed in a future release, see https://github.com/kubernetes/enhancements/tree/master/keps/sig-      --template string                  Template string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-ove      --tls-server-name string           Server name to use for server certificate validation. If it is not provided, the hostname used to contact the server is used
      --token string                     Bearer token for authentication to the API server
      --user string                      The name of the kubeconfig user to use
      --username string                  Username for basic authentication to the API server
  -v, --v Level                          number for the log level verbosity
      --validate                         If true, use a schema to validate the input before sending it (default true)
      --vmodule moduleSpec               comma-separated list of pattern=N settings for file-filtered logging

PS D:\opt\work\kubernetes>

K8S部署完成!

在这里插入图片描述
可以在官网在线教程试试哦!

预知后事如何,且看下集分晓~!祝大家开工大吉!工作顺利!学习进步!

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Windows上使用Kubernetesk8s)进行管理,可以按照以下步骤进行操作: 1. 首先,需要安装Windows版的Docker,因为k8s需要依赖Docker来运行容器。你可以从Docker官网下载并安装Windows版的Docker。 2. 接下来,需要安装kubectl命令行工具,它是与k8s集群进行交互的主要工具。你可以使用以下方法之一来安装kubectl: - 使用curl命令在Windows上安装kubectl二进制文件。 - 使用Chocolatey或Scoop包管理器在Windows上安装kubectl。 3. 安装完成kubectl后,你可以根据需要配置kubectl的环境变量,以便在任何位置都可以直接使用kubectl命令。 4. 接下来,你可以使用kubectl命令来管理k8s集群。例如,你可以使用kubectl get命令来获取集群中的资源信息,使用kubectl create命令来创建新的资源,使用kubectl delete命令来删除资源等等。你可以参考k8s官方文档或其他相关教程来学习更多kubectl的使用方法。 总结起来,你需要先安装Docker,然后安装kubectl,并配置好环境变量,最后使用kubectl命令来管理k8s集群。希望这些信息对你有帮助!\[1\]\[2\]\[3\] #### 引用[.reference_title] - *1* [windows10下如何安装 k8s,避坑指南](https://blog.csdn.net/w286554018/article/details/130770758)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [Windows部署K8S](https://blog.csdn.net/weixin_45364386/article/details/122812751)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值