Como instalar um Application Gateway Ingress Controller (AGIC) usando um novo gateway de aplicativo

As instruções abaixo pressupõem que o Application Gateway Ingress Controller (AGIC) será instalado em um ambiente sem componentes pré-existentes.

Ferramentas de linha de comando necessárias

Recomendamos o uso do Azure Cloud Shell para todas as operações de linha de comando abaixo. Inicie seu shell a partir do shell.azure.com ou clicando no link:

Como alternativa, inicie o Cloud Shell no portal do Azure usando o seguinte ícone:

Portal launch

Seu Azure Cloud Shell já tem todas as ferramentas necessárias. Se você optar por usar outro ambiente, verifique se as seguintes ferramentas de linha de comando estão instaladas:

Criar uma identidade

Siga as etapas abaixo para criar um objeto principal de serviço do Microsoft Entra. Registre os appIdvalores , password, e objectId - esses valores serão usados nas etapas a seguir.

  1. Criar entidade de serviço do AD (Leia mais sobre o Azure RBAC):

    az ad sp create-for-rbac --role Contributor --scopes /subscriptions/mySubscriptionID -o json > auth.json
    appId=$(jq -r ".appId" auth.json)
    password=$(jq -r ".password" auth.json)
    

    Os appId valores e password da saída JSON serão usados nas seguintes etapas

  2. Use a appId saída do comando anterior para obter a id da nova entidade de serviço:

    objectId=$(az ad sp show --id $appId --query "id" -o tsv)
    

    A saída deste comando é objectId, que será usada no modelo do Azure Resource Manager abaixo

  3. Crie o arquivo de parâmetro que será usado na implantação do modelo do Azure Resource Manager posteriormente.

    cat <<EOF > parameters.json
    {
      "aksServicePrincipalAppId": { "value": "$appId" },
      "aksServicePrincipalClientSecret": { "value": "$password" },
      "aksServicePrincipalObjectId": { "value": "$objectId" },
      "aksEnableRBAC": { "value": false }
    }
    EOF
    

    Para implantar um cluster habilitado para RBAC do Kubernetes, defina o aksEnableRBAC campo como true

Implantar componentes

Esta etapa adicionará os seguintes componentes à sua assinatura:

  1. Baixe o modelo do Azure Resource Manager e modifique-o conforme necessário.

    wget https://raw.githubusercontent.com/Azure/application-gateway-kubernetes-ingress/master/deploy/azuredeploy.json -O template.json
    
  2. Implante o modelo do Azure Resource Manager usando a CLI do Azure. A implantação pode levar até 5 minutos.

    resourceGroupName="MyResourceGroup"
    location="westus2"
    deploymentName="ingress-appgw"
    
    # create a resource group
    az group create -n $resourceGroupName -l $location
    
    # modify the template as needed
    az deployment group create \
            -g $resourceGroupName \
            -n $deploymentName \
            --template-file template.json \
            --parameters parameters.json
    
  3. Quando a implantação for concluída, baixe a saída da implantação em um arquivo chamado deployment-outputs.json.

    az deployment group show -g $resourceGroupName -n $deploymentName --query "properties.outputs" -o json > deployment-outputs.json
    

Configurar o Application Gateway Ingress Controller

Com as instruções na seção anterior, criamos e configuramos um novo cluster AKS e um Application Gateway. Agora estamos prontos para implantar um aplicativo de exemplo e um controlador de entrada em nossa nova infraestrutura do Kubernetes.

Configurar credenciais do Kubernetes

Para as etapas a seguir, precisamos do comando setup kubectl , que usaremos para nos conectar ao nosso novo cluster Kubernetes. O Cloud Shell já foi kubectl instalado. Usaremos az a CLI para obter credenciais para o Kubernetes.

Obtenha credenciais para o seu AKS recém-implantado (leia mais):

# use the deployment-outputs.json created after deployment to get the cluster name and resource group name
aksClusterName=$(jq -r ".aksClusterName.value" deployment-outputs.json)
resourceGroupName=$(jq -r ".resourceGroupName.value" deployment-outputs.json)

az aks get-credentials --resource-group $resourceGroupName --name $aksClusterName

Instalar o Microsoft Entra Pod Identity

O Microsoft Entra Pod Identity fornece acesso baseado em token ao Azure Resource Manager (ARM).

O Microsoft Entra Pod Identity adicionará os seguintes componentes ao seu cluster Kubernetes:

Para instalar o Microsoft Entra Pod Identity no seu cluster:

  • Cluster AKS habilitado para RBAC do Kubernetes

    kubectl create -f https://raw.githubusercontent.com/Azure/aad-pod-identity/master/deploy/infra/deployment-rbac.yaml
    
  • Cluster AKS desativado do RBAC do Kubernetes

    kubectl create -f https://raw.githubusercontent.com/Azure/aad-pod-identity/master/deploy/infra/deployment.yaml
    

Instalar o Helm

Helm é um gerenciador de pacotes para o Kubernetes. Vamos usá-lo para instalar o application-gateway-kubernetes-ingress pacote.

Nota

Se você usa o Cloud Shell, não precisa instalar o Helm. O Azure Cloud Shell vem com o Helm versão 3. Pule a primeira etapa e adicione o repositório AGIC Helm.

  1. Instale o Helm e execute o seguinte para adicionar application-gateway-kubernetes-ingress o pacote helm:

    • Cluster AKS habilitado para RBAC do Kubernetes

      kubectl create serviceaccount --namespace kube-system tiller-sa
      kubectl create clusterrolebinding tiller-cluster-rule --clusterrole=cluster-admin --serviceaccount=kube-system:tiller-sa
      helm init --tiller-namespace kube-system --service-account tiller-sa
      
    • Cluster AKS desativado do RBAC do Kubernetes

      helm init
      
  2. Adicione o repositório AGIC Helm:

    helm repo add application-gateway-kubernetes-ingress https://appgwingress.blob.core.windows.net/ingress-azure-helm-package/
    helm repo update
    

Instalar o Ingress Controller Helm Chart

  1. Use o deployment-outputs.json arquivo criado acima e crie as seguintes variáveis.

    applicationGatewayName=$(jq -r ".applicationGatewayName.value" deployment-outputs.json)
    resourceGroupName=$(jq -r ".resourceGroupName.value" deployment-outputs.json)
    subscriptionId=$(jq -r ".subscriptionId.value" deployment-outputs.json)
    identityClientId=$(jq -r ".identityClientId.value" deployment-outputs.json)
    identityResourceId=$(jq -r ".identityResourceId.value" deployment-outputs.json)
    
  2. Faça o download do helm-config.yaml, que configurará o AGIC:

    wget https://raw.githubusercontent.com/Azure/application-gateway-kubernetes-ingress/master/docs/examples/sample-helm-config.yaml -O helm-config.yaml
    

    Ou copie o arquivo YAML abaixo:

    # This file contains the essential configs for the ingress controller helm chart
    
    # Verbosity level of the App Gateway Ingress Controller
    verbosityLevel: 3
    
    ################################################################################
    # Specify which application gateway the ingress controller will manage
    #
    appgw:
        subscriptionId: <subscriptionId>
        resourceGroup: <resourceGroupName>
        name: <applicationGatewayName>
    
        # Setting appgw.shared to "true" will create an AzureIngressProhibitedTarget CRD.
        # This prohibits AGIC from applying config for any host/path.
        # Use "kubectl get AzureIngressProhibitedTargets" to view and change this.
        shared: false
    
    ################################################################################
    # Specify which kubernetes namespace the ingress controller will watch
    # Default value is "default"
    # Leaving this variable out or setting it to blank or empty string would
    # result in Ingress Controller observing all acessible namespaces.
    #
    # kubernetes:
    #   watchNamespace: <namespace>
    
    ################################################################################
    # Specify the authentication with Azure Resource Manager
    #
    # Two authentication methods are available:
    # - Option 1: AAD-Pod-Identity (https://github.com/Azure/aad-pod-identity)
    armAuth:
        type: aadPodIdentity
        identityResourceID: <identityResourceId>
        identityClientID:  <identityClientId>
    
    ## Alternatively you can use Service Principal credentials
    # armAuth:
    #    type: servicePrincipal
    #    secretJSON: <<Generate this value with: "az ad sp create-for-rbac --subscription <subscription-uuid> --role Contributor --sdk-auth | base64 -w0" >>
    
    ################################################################################
    # Specify if the cluster is Kubernetes RBAC enabled or not
    rbac:
        enabled: false # true/false
    
    # Specify aks cluster related information. THIS IS BEING DEPRECATED.
    aksClusterConfiguration:
        apiServerAddress: <aks-api-server-address>
    
  3. Edite o helm-config.yaml recém-baixado e preencha as seções appgw e armAuth.

    sed -i "s|<subscriptionId>|${subscriptionId}|g" helm-config.yaml
    sed -i "s|<resourceGroupName>|${resourceGroupName}|g" helm-config.yaml
    sed -i "s|<applicationGatewayName>|${applicationGatewayName}|g" helm-config.yaml
    sed -i "s|<identityResourceId>|${identityResourceId}|g" helm-config.yaml
    sed -i "s|<identityClientId>|${identityClientId}|g" helm-config.yaml
    

    Nota

    Para implantar em Nuvens Soberanas (por exemplo, Azure Government), o appgw.environment parâmetro de configuração deve ser adicionado e definido com o valor apropriado, conforme documentado abaixo.

    Valores:

    • verbosityLevel: Define o nível de detalhamento da infraestrutura de log AGIC. Consulte Níveis de log para obter os valores possíveis.
    • appgw.environment: Define o ambiente de nuvem. Valores possíveis: AZURECHINACLOUD, AZUREGERMANCLOUD, AZUREPUBLICCLOUD, AZUREUSGOVERNMENTCLOUD
    • appgw.subscriptionId: A ID de Assinatura do Azure na qual o Gateway de Aplicativo reside. Exemplo: a123b234-a3b4-557d-b2df-a0bc12de1234
    • appgw.resourceGroup: Nome do Grupo de Recursos do Azure no qual o Gateway de Aplicativo foi criado. Exemplo: app-gw-resource-group
    • appgw.name: Nome do gateway de aplicativo. Exemplo: applicationgatewayd0f0
    • appgw.shared: Este sinalizador booleano deve ser padronizado para false. Defina como true caso você precise de um Shared Application Gateway.
    • kubernetes.watchNamespace: Especifique o namespace que a AGIC deve observar. O valor do namespace pode ser um único valor de cadeia de caracteres ou uma lista de namespaces separada por vírgula.
    • armAuth.type: pode ser aadPodIdentity ou servicePrincipal
    • armAuth.identityResourceID: ID de recurso da Identidade Gerenciada do Azure
    • armAuth.identityClientID: A ID do Cliente da Identidade. Mais informações sobre identityClientID são fornecidas abaixo.
    • armAuth.secretJSON: Necessário apenas quando o tipo de Segredo Principal de Serviço é escolhido (quando armAuth.type foi definido como servicePrincipal)

    Nota

    Os identityResourceID valores e identityClientID são que foram criados durante as etapas Implantar componentes e podem ser obtidos novamente usando o seguinte comando:

    az identity show -g <resource-group> -n <identity-name>
    

    <resource-group> no comando acima é o grupo de recursos do seu Application Gateway. <identity-name> é o nome da identidade criada. Todas as identidades de uma determinada assinatura podem ser listadas usando: az identity list

  4. Instale o pacote do controlador de entrada do Application Gateway:

    helm install -f helm-config.yaml --generate-name application-gateway-kubernetes-ingress/ingress-azure
    

Instalar um aplicativo de exemplo

Agora que temos o Application Gateway, AKS e AGIC instalados, podemos instalar um aplicativo de exemplo por meio do Azure Cloud Shell:

cat <<EOF | kubectl apply -f -
apiVersion: v1
kind: Pod
metadata:
  name: aspnetapp
  labels:
    app: aspnetapp
spec:
  containers:
  - image: "mcr.microsoft.com/dotnet/samples:aspnetapp"
    name: aspnetapp-image
    ports:
    - containerPort: 8080
      protocol: TCP

---

apiVersion: v1
kind: Service
metadata:
  name: aspnetapp
spec:
  selector:
    app: aspnetapp
  ports:
  - protocol: TCP
    port: 80
    targetPort: 8080

---

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: aspnetapp
  annotations:
    kubernetes.io/ingress.class: azure/application-gateway
spec:
  rules:
  - http:
      paths:
      - path: /
        pathType: Exact
        backend:
          service:
            name: aspnetapp
            port:
              number: 80
        pathType: Exact
EOF

Em alternativa, pode:

  • Baixe o arquivo YAML acima:

    curl https://raw.githubusercontent.com/Azure/application-gateway-kubernetes-ingress/master/docs/examples/aspnetapp.yaml -o aspnetapp.yaml
    
  • Aplique o arquivo YAML:

    kubectl apply -f aspnetapp.yaml
    

Outros exemplos

Este guia de instruções contém mais exemplos sobre como expor um serviço AKS via HTTP ou HTTPS à Internet com o Application Gateway.