Creación de un clúster de Kubernetes con Azure Kubernetes Service mediante TerraformCreate a Kubernetes cluster with Azure Kubernetes Service using Terraform
Azure Kubernetes Service (AKS) administra el entorno hospedado de Kubernetes.Azure Kubernetes Service (AKS) manages your hosted Kubernetes environment. Azure Kubernetes Service permite implementar y administrar aplicaciones en contenedores sin necesidad de tener conocimientos de orquestación de contenedores.AKS allows you to deploy and manage containerized applications without container orchestration expertise. También permite realizar muchas operaciones de mantenimiento comunes sin desconectar la aplicación.AKS also enables you to do many common maintenance operations without taking your app offline. Entre estas operaciones se incluyen el aprovisionamiento, la actualización y el escalado de recursos a petición.These operations include provisioning, upgrading, and scaling resources on demand.
En este artículo, aprenderá a realizar las siguientes tareas:In this article, you learn how to do the following tasks:
- Uso de HCL (HashiCorp Language) para definir un clúster de KubernetesUse HCL (HashiCorp Language) to define a Kubernetes cluster
- Uso de Terraform y AKS para crear un clúster de KubernetesUse Terraform and AKS to create a Kubernetes cluster
- Utilice la herramienta kubectl para probar la disponibilidad de un clúster de KubernetesUse the kubectl tool to test the availability of a Kubernetes cluster
PrerrequisitosPrerequisites
- Suscripción de Azure: si no tiene una suscripción a Azure, cree una cuenta gratuita de Azure antes de empezar.Azure subscription: If you don't have an Azure subscription, create a free account before you begin.
Configuración de Terraform: siga las instrucciones del artículo Instalación y configuración de Terraform para aprovisionar máquinas virtuales y otras infraestructuras en Azure.Configure Terraform: Follow the directions in the article, Terraform and configure access to Azure
Entidad de servicio de Azure: siga las instrucciones de Creación de la entidad de servicio, en el artículo Creación de una entidad de servicio de Azure con la CLI de Azure.Azure service principal: Follow the directions in the Create the service principal section in the article, Create an Azure service principal with Azure CLI. Anote los valores de
appId
,displayName
,password
ytenant
.Take note of the values for theappId
,displayName
,password
, andtenant
.
Creación de la estructura de directoriosCreate the directory structure
El primer paso es crear el directorio que contenga los archivos de configuración de Terraform para el ejercicio.The first step is to create the directory that holds your Terraform configuration files for the exercise.
Vaya a Azure Portal.Browse to the Azure portal.
Abra Azure Cloud Shell.Open Azure Cloud Shell. Si no seleccionó un entorno previamente, seleccione Bash como entorno.If you didn't select an environment previously, select Bash as your environment.
Cambie al directorio
clouddrive
.Change directories to theclouddrive
directory.cd clouddrive
Cree un directorio llamado
terraform-aks-k8s
.Create a directory namedterraform-aks-k8s
.mkdir terraform-aks-k8s
Cambie los directorios al nuevo directorio:Change directories to the new directory:
cd terraform-aks-k8s
Declaración del proveedor de AzureDeclare the Azure provider
Cree el archivo de configuración de Terraform que declara el proveedor de Azure.Create the Terraform configuration file that declares the Azure provider.
En Cloud Shell, cree un archivo denominado
main.tf
.In Cloud Shell, create a file namedmain.tf
.code main.tf
Pegue el siguiente código en el editor:Paste the following code into the editor:
provider "azurerm" { # The "feature" block is required for AzureRM provider 2.x. # If you are using version 1.x, the "features" block is not allowed. version = "~>2.0" features {} } terraform { backend "azurerm" {} }
Guarde el archivo ( <Ctrl > S) y salga del editor ( <Ctrl > Q).Save the file (<Ctrl>S) and exit the editor (<Ctrl>Q).
Definición de un clúster de KubernetesDefine a Kubernetes cluster
Cree el archivo de configuración de Terraform que declara los recursos para el clúster de Kubernetes.Create the Terraform configuration file that declares the resources for the Kubernetes cluster.
En Cloud Shell, cree un archivo denominado
k8s.tf
.In Cloud Shell, create a file namedk8s.tf
.code k8s.tf
Pegue el siguiente código en el editor:Paste the following code into the editor:
resource "azurerm_resource_group" "k8s" { name = var.resource_group_name location = var.location } resource "random_id" "log_analytics_workspace_name_suffix" { byte_length = 8 } resource "azurerm_log_analytics_workspace" "test" { # The WorkSpace name has to be unique across the whole of azure, not just the current subscription/tenant. name = "${var.log_analytics_workspace_name}-${random_id.log_analytics_workspace_name_suffix.dec}" location = var.log_analytics_workspace_location resource_group_name = azurerm_resource_group.k8s.name sku = var.log_analytics_workspace_sku } resource "azurerm_log_analytics_solution" "test" { solution_name = "ContainerInsights" location = azurerm_log_analytics_workspace.test.location resource_group_name = azurerm_resource_group.k8s.name workspace_resource_id = azurerm_log_analytics_workspace.test.id workspace_name = azurerm_log_analytics_workspace.test.name plan { publisher = "Microsoft" product = "OMSGallery/ContainerInsights" } } resource "azurerm_kubernetes_cluster" "k8s" { name = var.cluster_name location = azurerm_resource_group.k8s.location resource_group_name = azurerm_resource_group.k8s.name dns_prefix = var.dns_prefix linux_profile { admin_username = "ubuntu" ssh_key { key_data = file(var.ssh_public_key) } } default_node_pool { name = "agentpool" node_count = var.agent_count vm_size = "Standard_D2_v2" } service_principal { client_id = var.client_id client_secret = var.client_secret } addon_profile { oms_agent { enabled = true log_analytics_workspace_id = azurerm_log_analytics_workspace.test.id } } network_profile { load_balancer_sku = "Standard" network_plugin = "kubenet" } tags = { Environment = "Development" } }
El código anterior establece el nombre del clúster, la ubicación y el nombre del grupo de recursos.The preceding code sets the name of the cluster, location, and the resource group name. También se establece el prefijo del nombre de dominio completo (FQDN).The prefix for the fully qualified domain name (FQDN) is also set. El nombre de dominio completo se usa para acceder al clúster.The FQDN is used to access the cluster.
El registro
linux_profile
permite configurar las opciones que permiten iniciar sesión en los nodos de trabajo mediante SSH.Thelinux_profile
record allows you to configure the settings that enable signing into the worker nodes using SSH.Con AKS, solo se paga por los nodos de trabajo.With AKS, you pay only for the worker nodes. El registro
default_node_pool
configura los detalles de estos nodos de trabajo.Thedefault_node_pool
record configures the details for these worker nodes. El registrodefault_node_pool record
incluye el número de nodos de trabajo que se van a crear y el tipo de estos.Thedefault_node_pool record
includes the number of worker nodes to create and the type of worker nodes. Si necesita escalar o reducir verticalmente el clúster en el futuro, modifique el valor decount
en este registro.If you need to scale up or scale down the cluster in the future, you modify thecount
value in this record.Guarde el archivo ( <Ctrl > S) y salga del editor ( <Ctrl > Q).Save the file (<Ctrl>S) and exit the editor (<Ctrl>Q).
Declaración de las variablesDeclare the variables
En Cloud Shell, cree un archivo denominado
variables.tf
.In Cloud Shell, create a file namedvariables.tf
.code variables.tf
Pegue el siguiente código en el editor:Paste the following code into the editor:
variable "client_id" {} variable "client_secret" {} variable "agent_count" { default = 3 } variable "ssh_public_key" { default = "~/.ssh/id_rsa.pub" } variable "dns_prefix" { default = "k8stest" } variable cluster_name { default = "k8stest" } variable resource_group_name { default = "azure-k8stest" } variable location { default = "Central US" } variable log_analytics_workspace_name { default = "testLogAnalyticsWorkspaceName" } # refer https://azure.microsoft.com/global-infrastructure/services/?products=monitor for log analytics available regions variable log_analytics_workspace_location { default = "eastus" } # refer https://azure.microsoft.com/pricing/details/monitor/ for log analytics pricing variable log_analytics_workspace_sku { default = "PerGB2018" }
Guarde el archivo ( <Ctrl > S) y salga del editor ( <Ctrl > Q).Save the file (<Ctrl>S) and exit the editor (<Ctrl>Q).
Creación de un archivo de salida de TerraformCreate a Terraform output file
Las salidas de Terraform permiten definir valores que se resaltarán al usuario cuando Terraform aplique un plan, y pueden consultarse con el comando terraform output
.Terraform outputs allow you to define values that will be highlighted to the user when Terraform applies a plan, and can be queried using the terraform output
command. En esta sección, va a crear un archivo de salida que permita el acceso al clúster con kubectl.In this section, you create an output file that allows access to the cluster with kubectl.
En Cloud Shell, cree un archivo denominado
output.tf
.In Cloud Shell, create a file namedoutput.tf
.code output.tf
Pegue el siguiente código en el editor:Paste the following code into the editor:
output "client_key" { value = azurerm_kubernetes_cluster.k8s.kube_config.0.client_key } output "client_certificate" { value = azurerm_kubernetes_cluster.k8s.kube_config.0.client_certificate } output "cluster_ca_certificate" { value = azurerm_kubernetes_cluster.k8s.kube_config.0.cluster_ca_certificate } output "cluster_username" { value = azurerm_kubernetes_cluster.k8s.kube_config.0.username } output "cluster_password" { value = azurerm_kubernetes_cluster.k8s.kube_config.0.password } output "kube_config" { value = azurerm_kubernetes_cluster.k8s.kube_config_raw } output "host" { value = azurerm_kubernetes_cluster.k8s.kube_config.0.host }
Guarde el archivo ( <Ctrl > S) y salga del editor ( <Ctrl > Q).Save the file (<Ctrl>S) and exit the editor (<Ctrl>Q).
Configuración del almacenamiento de Azure para almacenar el estado de TerraformSet up Azure storage to store Terraform state
Terraform realiza un seguimiento del estado de manera local a través del archivo terraform.tfstate
.Terraform tracks state locally via the terraform.tfstate
file. Este patrón funciona bien en un entorno de persona único.This pattern works well in a single-person environment. En un entorno de varias personas, Azure Storage se usa para realizar un seguimiento del estado.In a multi-person environment, Azure storage is used to track state.
En esta sección, verá cómo se realizan las siguientes tareas:In this section, you see how to do the following tasks:
- Recuperar la información de la cuenta de almacenamiento (nombre y clave de la cuenta).Retrieve storage account information (account name and account key)
- Cree un contenedor de almacenamiento en el que se almacenará la información de estado de Terraform.Create a storage container into which Terraform state information will be stored.
En Azure Portal, seleccione Todos los servicios en el menú de la izquierda.In the Azure portal, select All services in the left menu.
Seleccione Cuentas de almacenamiento.Select Storage accounts.
En la pestaña Cuentas de almacenamiento, seleccione el nombre de la cuenta de almacenamiento en la que Terraform va a almacenar el estado.On the Storage accounts tab, select the name of the storage account into which Terraform is to store state. Por ejemplo, puede utilizar la cuenta de almacenamiento creada cuando abrió Cloud Shell por primera vez.For example, you can use the storage account created when you opened Cloud Shell the first time. El nombre de cuenta de almacenamiento creada por Cloud Shell normalmente comienza por
cs
seguido de una cadena aleatoria de números y letras.The storage account name created by Cloud Shell typically starts withcs
followed by a random string of numbers and letters. Anote la cuenta de almacenamiento que seleccione.Take note of the storage account you select. Este valor lo necesitará más adelante.This value is needed later.En la pestaña Cuenta de almacenamiento, seleccione Claves de acceso.On the storage account tab, select Access keys.
Anote el valor de la clave1 clave.Make note of the key1 key value. (Al seleccionar el icono a la derecha de la clave, se copia el valor al portapapeles).(Selecting the icon to the right of the key copies the value to the clipboard.)
En Cloud Shell, cree un contenedor en su cuenta de Azure Storage.In Cloud Shell, create a container in your Azure storage account. Reemplace los marcadores de posición por valores adecuados para su entorno.Replace the placeholders with appropriate values for your environment.
az storage container create -n tfstate --account-name <YourAzureStorageAccountName> --account-key <YourAzureStorageAccountKey>
Crear el clúster de KubernetesCreate the Kubernetes cluster
En esta sección, puede ver cómo usar el comando terraform init
para crear los recursos definidos en los archivos de configuración que creó en las secciones anteriores.In this section, you see how to use the terraform init
command to create the resources defined in the configuration files you created in the previous sections.
En Cloud Shell, inicialice Terraform.In Cloud Shell, initialize Terraform. Reemplace los marcadores de posición por valores adecuados para su entorno.Replace the placeholders with appropriate values for your environment.
terraform init -backend-config="storage_account_name=<YourAzureStorageAccountName>" -backend-config="container_name=tfstate" -backend-config="access_key=<YourStorageAccountAccessKey>" -backend-config="key=codelab.microsoft.tfstate"
El comando
terraform init
muestra el éxito de inicializar el back-end y el complemento del proveedor:Theterraform init
command displays the success of initializing the backend and provider plug-in:Exporte las credenciales de la entidad de servicio.Export your service principal credentials. Reemplace los marcadores de posición por valores adecuados de su entidad de servicio.Replace the placeholders with appropriate values from your service principal.
export TF_VAR_client_id=<service-principal-appid> export TF_VAR_client_secret=<service-principal-password>
Ejecute el comando
terraform plan
para crear el plan de Terraform que define los elementos de infraestructura.Run theterraform plan
command to create the Terraform plan that defines the infrastructure elements.terraform plan -out out.plan
El comando
terraform plan
muestra los recursos que se crearán cuando ejecute el comandoterraform apply
:Theterraform plan
command displays the resources that will be created when you run theterraform apply
command:Ejecute el comando
terraform apply
para aplicar el plan para crear el clúster de Kubernetes.Run theterraform apply
command to apply the plan to create the Kubernetes cluster. El proceso para crear un clúster de Kubernetes puede tardar varios minutos, dado como resultado el agotamiento del tiempo de espera de la sesión de Cloud Shell. Si la sesión de Cloud Shell agota su tiempo de espera, puede seguir los pasos de la sección "Recuperación de un tiempo de espera de Cloud Shell" para poder completar el proceso.The process to create a Kubernetes cluster can take several minutes, resulting in the Cloud Shell session timing out. If the Cloud Shell session times out, you can follow the steps in the section "Recover from a Cloud Shell timeout" to enable you to complete the process.terraform apply out.plan
El comando
terraform apply
muestra los resultados de la creación de los recursos definidos en sus archivos de configuración:Theterraform apply
command displays the results of creating the resources defined in your configuration files:En Azure Portal, seleccione Todos los recursos en el menú de la izquierda para ver los recursos que se han creado para su nuevo clúster de Kubernetes.In the Azure portal, select All resources in the left menu to see the resources created for your new Kubernetes cluster.
Recuperación de un tiempo de espera de Cloud ShellRecover from a Cloud Shell timeout
Si se agota el tiempo de espera de Cloud Shell, puede seguir estos pasos para recuperarla:If the Cloud Shell session times out, you can do the following steps to recover:
Inicie una sesión de Cloud Shell.Start a Cloud Shell session.
Cambie al directorio que contiene los archivos de configuración de Terraform.Change to the directory containing your Terraform configuration files.
cd /clouddrive/terraform-aks-k8s
Ejecute el siguiente comando:Run the following command:
export KUBECONFIG=./azurek8s
Prueba del clúster de KubernetesTest the Kubernetes cluster
Las herramientas de Kubernetes se pueden usar para comprobar el clúster recién creado.The Kubernetes tools can be used to verify the newly created cluster.
Obtenga la configuración de Kubernetes desde el estado de Terraform y almacénela en un archivo que kubectl puede leer.Get the Kubernetes configuration from the Terraform state and store it in a file that kubectl can read.
echo "$(terraform output kube_config)" > ./azurek8s
Establezca una variable de entorno para que kubectl seleccione la configuración correcta.Set an environment variable so that kubectl picks up the correct config.
export KUBECONFIG=./azurek8s
Compruebe el mantenimiento del clúster.Verify the health of the cluster.
kubectl get nodes
Debería ver los detalles de sus nodos de trabajo, y todos deberían tener el estado Listo, como se muestra en la siguiente imagen:You should see the details of your worker nodes, and they should all have a status Ready, as shown in the following image:
Supervisión de estado y registrosMonitor health and logs
Cuando se creó el clúster de AKS, se habilitó la supervisión para capturar métricas de mantenimiento para los nodos de clúster y los pods.When the AKS cluster was created, monitoring was enabled to capture health metrics for both the cluster nodes and pods. Estas métricas de mantenimiento están disponibles en Azure Portal.These health metrics are available in the Azure portal. Para obtener más información sobre la supervisión del estado de los contenedores, consulte Monitor Azure Kubernetes Service health (Supervisión del estado de Azure Kubernetes Service).For more information on container health monitoring, see Monitor Azure Kubernetes Service health.
Solución de problemasTroubleshooting
Para obtener soporte técnico específico de Terraform, use uno de los canales de soporte técnico de la comunidad de HashiCorp para Terraform:For Terraform-specific support, use one of HashiCorp's community support channels to Terraform:
- Preguntas, casos de uso y patrones útiles: sección Terraform del portal de la comunidad de HashiCorp.Questions, use-cases, and useful patterns: Terraform section of the HashiCorp community portal
- Preguntas relacionadas con proveedores: sección Proveedores de Terraform del portal de la comunidad de HashiCorp.Provider-related questions: Terraform Providers section of the HashiCorp community portal