Container Apps como runners de GitHub Actions

Guía práctica para configurar runners autoescalables de GitHub Actions con Azure Container Apps: automatiza CI/CD en redes privadas, reduce costes y aumenta seguridad.

18 ago 2025 • 5 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Guía práctica para configurar runners de GitHub Actions con Azure Container Apps

Descripción general Azure Container Apps jobs permite arrancar runners de GitHub de forma dinámica cuando se ejecutan flujos de trabajo y detenerlos al finalizar, de modo que solo se paga por el uso real. Esta solución facilita ejecutar pipelines en redes privadas y evita el gasto en máquinas virtuales siempre activas. En Q2BSTUDIO, empresa especializada en desarrollo de software a medida, aplicaciones a medida, inteligencia artificial, ciberseguridad y servicios cloud aws y azure, implementamos este tipo de arquitecturas para ofrecer eficiencia, seguridad y ahorro de costes.

Requisitos previos Tener instalado y configurado Azure CLI; contar con una suscripción activa de Azure; disponer de un repositorio en GitHub con Actions habilitado; generar un GitHub Personal Access Token PAT con permisos adecuados.

Permisos necesarios para el PAT El token debe incluir los siguientes scopes: repo para control total de repositorios privados; workflow para actualizar workflows de Actions; admin:org si se usan runners a nivel de organización.

Paso 1 instalar la extensión de Container Apps Ejecutar el comando az extension add --name containerapp --upgrade para añadir la extensión necesaria de Container Apps a Azure CLI.

Paso 2 configurar variables de entorno Ejemplo de variables de configuración para adaptar a tu entorno: RESOURCE_GROUP=jobs-sample; LOCATION=northcentralus; ENVIRONMENT=env-jobs-sample; JOB_NAME=github-actions-runner-job; GITHUB_PAT=tu_github_personal_access_token; REPO_OWNER=tu_usuario_github; REPO_NAME=tu_repositorio; CONTAINER_IMAGE_NAME=github-actions-runner:1.0; CONTAINER_REGISTRY_NAME=nombre_unico_registro; IDENTITY=github-actions-runner-identity. Nota de seguridad nunca almacenar el PAT en control de versiones; en entornos de producción utilizar Azure Key Vault o identidades administradas.

Paso 3 crear registro de contenedores Crear un Azure Container Registry para almacenar la imagen del runner: az acr create --name CONTAINER_REGISTRY_NAME --resource-group RESOURCE_GROUP --location LOCATION --sku Basic.

Paso 4 configurar autenticación del registro Verificar la configuración de autenticación como ARM con: az acr config authentication-as-arm show --registry CONTAINER_REGISTRY_NAME.

Paso 5 construir la imagen del runner Construir la imagen con az acr build --registry CONTAINER_REGISTRY_NAME --image github-actions-runner:2.1 --file Dockerfile.github https://github.com/TuanLikeminds/container-apps-ci-cd-runner-tutorial.git. El Dockerfile puede partir de la imagen oficial de actions runner y añadir herramientas necesarias como Azure CLI, kubectl y Helm. Ejemplo de base del Dockerfile FROM ghcr.io/actions/actions-runner:2.304.0; instalar curl jq git y herramientas de Azure; instalar Azure CLI y Helm; instalar kubectl; copiar un entrypoint que registre y desregistre el runner contra GitHub.

Paso 6 crear el Container App Job con autoescalado Crear el job que escalará en función de la cola de workflows: az containerapp job create --name JOB_NAME --resource-group RESOURCE_GROUP --environment ENVIRONMENT --trigger-type Event --replica-timeout 1800 --replica-retry-limit 0 --replica-completion-count 1 --parallelism 1 --image CONTAINER_REGISTRY_NAME.azurecr.io/CONTAINER_IMAGE_NAME --min-executions 0 --max-executions 10 --polling-interval 30 --scale-rule-name github-runner --scale-rule-type github-runner --scale-rule-metadata githubAPIURL=https://api.github.com owner=REPO_OWNER runnerScope=repo repos=REPO_NAME targetWorkflowQueueLength=1 --scale-rule-auth personalAccessToken=personal-access-token --cpu 2.0 --memory 4Gi --secrets personal-access-token=GITHUB_PAT --env-vars GITHUB_PAT=secretref:personal-access-token GH_URL=https://github.com/REPO_OWNER/REPO_NAME --registry-server CONTAINER_REGISTRY_NAME.azurecr.io --mi-user-assigned IDENTITY_ID --registry-identity IDENTITY_ID. Explicación de parámetros clave replica-timeout tiempo máximo de ejecución en segundos; min-executions y max-executions límites de escalado; polling-interval intervalo de comprobación de cola; targetWorkflowQueueLength umbral de activación; cpu y memory recursos por instancia.

Paso 7 asignaciones de rol Conceder permisos para que la identidad administrada pueda acceder al registro y a otros recursos. Ejemplos: az role assignment create --assignee IDENTITY_ID --role AcrPull --scope /subscriptions/SUBSCRIPTION_ID/resourceGroups/RESOURCE_GROUP/providers/Microsoft.ContainerRegistry/registries/CONTAINER_REGISTRY_NAME; si se necesita push para construir imágenes az role assignment create --assignee IDENTITY_ID --role AcrPush --scope /subscriptions/SUBSCRIPTION_ID/resourceGroups/RESOURCE_GROUP/providers/Microsoft.ContainerRegistry/registries/CONTAINER_REGISTRY_NAME; para acceso a AKS az role assignment create --assignee IDENTITY_ID --role Azure Kubernetes Service RBAC Admin --scope /subscriptions/SUBSCRIPTION_ID/resourceGroups/AKS_RESOURCE_GROUP/providers/Microsoft.ContainerService/managedClusters/AKS_CLUSTER_NAME.

Paso 8 verificar la configuración Comprobar el estado del job con az containerapp job show --name JOB_NAME --resource-group RESOURCE_GROUP; revisar logs con az containerapp job logs show --name JOB_NAME --resource-group RESOURCE_GROUP --follow; y confirmar en la pestaña Actions del repositorio GitHub que aparece el runner autogestionado.

Cómo funciona Disparador cuando un workflow queda en cola; escalado Azure Container Apps detecta la cola y arranca una instancia de runner; ejecución el runner ejecuta el workflow dentro del contenedor; limpieza la instancia termina y se elimina al completar la ejecución; escalado a cero cuando no hay trabajos pendientes.

Resolución de problemas comunes Si el runner no aparece en GitHub verificar permisos del PAT y valores REPO_OWNER y REPO_NAME; revisar logs del contenedor para errores de autenticación. Si hay problemas de escalado comprobar polling-interval y metadatos de la regla de escalado, y ajustar targetWorkflowQueueLength. Para problemas de acceso al registro revisar las asignaciones de rol de la identidad administrada y confirmar que la imagen existe en el registro.

Comandos útiles Ver ejecuciones del job az containerapp job execution list --name JOB_NAME --resource-group RESOURCE_GROUP; ver logs detallados az containerapp job logs show --name JOB_NAME --resource-group RESOURCE_GROUP --follow; actualizar imagen del job az containerapp job update --name JOB_NAME --resource-group RESOURCE_GROUP --image nueva_imagen:tag.

Buenas prácticas de seguridad Usar identidades administradas en lugar de credenciales en variables de entorno; aplicar principio de menor privilegio a roles; rotación periódica de PATs; considerar endpoints privados en producción; definir límites de recursos adecuados para cada runner. En Q2BSTUDIO combinamos estas prácticas con servicios de ciberseguridad e inteligencia artificial para ofrecer soluciones robustas y seguras.

Optimización de costes Aprovechar el escalado a cero para minimizar facturación; ajustar CPU y memoria según las necesidades de los workflows; desplegar en regiones cercanas al equipo de desarrollo; usar Azure Monitor para supervisar uso y optimizar costes. Q2BSTUDIO ofrece consultoría para optimizar despliegues en servicios cloud aws y azure y reducir gastos operativos.

Siguientes pasos recomendados Implementar monitorización y alertas; configurar políticas de red para mayor seguridad; adoptar GitOps para gestionar configuraciones; crear varios pools de runners según tipos de carga; integrar análisis con power bi para visualizar métricas de uso y rendimiento.

Sobre Q2BSTUDIO Q2BSTUDIO es una empresa de desarrollo de software y aplicaciones a medida especializada en soluciones de software a medida, inteligencia artificial y servicios inteligencia de negocio. Ofrecemos servicios de ciberseguridad, consultoría cloud en aws y azure, desarrollo de agentes IA e ia para empresas y soluciones de visualización con power bi. Si necesitas arquitecturas eficientes para CI CD, runners autoescalables o integración de IA en tus procesos, contacta con Q2BSTUDIO para un diseño a medida que busque rendimiento, seguridad y ahorro de costes.

Palabras clave aplicaciones a medida; software a medida; inteligencia artificial; ciberseguridad; servicios cloud aws y azure; servicios inteligencia de negocio; ia para empresas; agentes IA; power bi.

Nota final Antes de ejecutar los comandos sustituir todos los marcadores de posición SUBSCRIPTION_ID RESOURCE_GROUP CONTAINER_REGISTRY_NAME REPO_OWNER REPO_NAME GITHUB_PAT IDENTITY_ID por los valores reales de tu entorno.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat