<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[OpsUniverse - Medium]]></title>
        <description><![CDATA[Everything about DevOps — from tools to best practices. - Medium]]></description>
        <link>https://medium.com/opsuniverse?source=rss----c13c3d080b5d---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>OpsUniverse - Medium</title>
            <link>https://medium.com/opsuniverse?source=rss----c13c3d080b5d---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 05:53:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/opsuniverse" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[GitOps-Driven Control for Automated SSL Renewals]]></title>
            <link>https://medium.com/opsuniverse/automating-ssl-renewals-a-gitops-approach-eb519c024aac?source=rss----c13c3d080b5d---4</link>
            <guid isPermaLink="false">https://medium.com/p/eb519c024aac</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[ansible]]></category>
            <dc:creator><![CDATA[Samir Nabadov]]></dc:creator>
            <pubDate>Thu, 05 Feb 2026 12:23:23 GMT</pubDate>
            <atom:updated>2026-02-05T12:28:21.497Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*g0UK2VA2TyctAKbpMP66ew.avif" /></figure><p>This article describes how we added observability and control to an existing SSL automation pipeline without redesigning or replacing it.</p><h3>Context: Automation Was in Place, Visibility Was Not</h3><p>The goal of this solution was not to build SSL renewal from scratch.<br>The process had already been automated for a long time and was running in a stable way.</p><p>The existing system was built on the following components:</p><ul><li>SSL certificates were managed centrally</li><li>cert-manager handled certificate issuance and automatic renewal</li><li>Vault PKI acted as the main trust layer</li><li>consul-template running on VMs pulled certificates from Vault and applied them to services</li></ul><p>From a technical perspective, the system was stable and did not cause issues in day-to-day operations.</p><h3>The Gap: Renewal Without Visibility</h3><p>The core problem was not the lack of automation, but the lack of visibility.</p><p>The renewal process happened in the background, but there was no clear answer to several key questions.</p><ul><li>Which certificate was renewed</li><li>When the renewal happened</li><li>Which services were affected</li><li>Where the reload was executed</li></ul><p>consul-template could automatically reload services when changes occurred. However, this process was not controlled through a pipeline.</p><ul><li>It did not generate alerts or notifications</li><li>It was not measured by monitoring</li><li>It left little to no audit trail</li></ul><p>As a result, the SSL lifecycle was automated, but not observable.</p><h3>Design Direction</h3><p>The design decision was based on preserving the existing architecture.</p><ul><li>Do not change the current automation</li><li>Keep the renewal process as it is</li><li>Add control and observability to the reload stage</li></ul><p>This approach keeps renewal fully automatic, while making the application phase controlled and auditable.</p><h3>Architecture Overview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xItBlo2eAgr4bodUkM9Vew.png" /></figure><h3>High-Level Flow</h3><p>This architecture manages the creation, renewal, and application of SSL certificates in a centralized way using a GitOps approach.</p><pre>┌──────────────────────────────────────────────────────────────┐<br>│                    CERTIFICATE LIFECYCLE                      │<br>└──────────────────────────────────────────────────────────────┘<br><br>📁 Git Repo (Cert YAMLs)<br>    │<br>    │ GitOps<br>    ▼<br>🔄 cert-manager ──▶ 🔐 TLS Secrets (K8s)<br>                        │<br>                        │ Nightly Sync<br>                        ▼<br>                    🏛️ Vault PKI<br>                    (Source of Truth)<br>                        │<br>            ┌───────────┼───────────┐<br>            │           │           │<br>            ▼           ▼           ▼<br>        🖥️ VM-1    🖥️ VM-2    🖥️ VM-N<br>        consul-template pulls certs<br>            │           │           │<br>            └───────────┴───────────┘<br>                        │<br>                        ▼<br>            ⚙️ HAProxy/Nginx Configs<br>                        │<br>                        │ Webhook/Script<br>                        ▼<br>            🔔 Trigger Reload Pipeline<br>                        │<br>                        ▼<br>            📊 Metrics → Prometheus → Alert → 📱 Telegram<br>                                                    │<br>                                                    ▼<br>                                        👨‍💻 DevOps (Manual Approve)<br>                                                    │<br>                                                    ▼<br>                                        ✅ Service Reload (HAProxy/Nginx)</pre><p>At a high level, the process works as follows:</p><ol><li>Certificates are stored declaratively in a Git repository</li><li>cert-manager handles issuance and renewal automatically</li><li>Kubernetes secrets are synchronized to Vault</li><li>VMs read certificates from Vault</li><li>Service reloads are executed manually through a pipeline</li></ol><h3>Implementation Overview</h3><p>The implementation is divided into four independent parts:</p><ol><li>Certificate management (Kubernetes)</li><li>Secret synchronization (Kubernetes → Vault)</li><li>Certificate consumption (Vault → VMs)</li><li>Reload orchestration and monitoring</li></ol><p>The following sections describe the key implementation details of each component.</p><h3>Certificate Definitions (cert-manager)</h3><p>Certificates are stored in the Git repository as Certificate resources.<br>The example below shows the common pattern used across all environments.</p><pre>---<br>apiVersion: cert-manager.io/v1<br>kind: Certificate<br>metadata:<br>  name: dev.nginx.local.az<br>  namespace: cert-manager-pki<br>spec:<br>  secretName: dev.nginx.local.az<br>  duration: 8760h<br>  renewBefore: 2160h<br>  commonName: dev.nginx.local.az<br>  dnsNames:<br>    - dev.nginx.local.az<br>  issuerRef:<br>    name: vault-cluster-issuer<br>    kind: ClusterIssuer</pre><h3>Kubernetes → Vault Synchronization</h3><p>A nightly CronJob reads all TLS secrets from the cert-manager namespace<br>and writes them to Vault KV.<br>At this stage, Vault acts as the central source for certificate distribution.</p><pre>---<br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: Role<br>metadata:<br>  namespace: cert-manager-pki<br>  name: secrets-reader<br>rules:<br>- apiGroups: [&quot;&quot;]<br>  resources: [&quot;secrets&quot;]<br>  verbs: [&quot;get&quot;, &quot;list&quot;]<br>---<br>apiVersion: rbac.authorization.k8s.io/v1<br>kind: RoleBinding<br>metadata:<br>  name: read-secrets-binding<br>  namespace: cert-manager-pki<br>subjects:<br>- kind: ServiceAccount<br>  name: default<br>  namespace: cert-manager-pki<br>roleRef:<br>  kind: Role<br>  name: secrets-reader<br>  apiGroup: rbac.authorization.k8s.io<br>---<br>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: sync-secrets-to-vault-script<br>  namespace: cert-manager-pki<br>data:<br>  sync-secrets-to-vault.sh: |<br>    #!/bin/bash<br>    # Define variables<br>    NAMESPACE=&quot;cert-manager-pki<br>    VAULT_ADDR=https://vault.local.az:8200<br>    VAULT_TOKEN=&lt;TOKEN&gt;<br>    VAULT_PATH_PREFIX=devops/vault/pki-secrets<br><br>    # Fetch all secrets in the namespace<br>    secrets=$(kubectl get secrets -n $NAMESPACE -o json | jq -r &#39;.items[].metadata.name&#39;)<br><br>    # Loop through each secret<br>    for secret_name in $secrets; do<br>      # Skip the regcred secret<br>      if [[ &quot;$secret_name&quot; == &quot;regcred&quot; ]]; then<br>        continue<br>      fi<br><br>      # Fetch the secret<br>      secret=$(kubectl get secret &quot;$secret_name&quot; -n &quot;$NAMESPACE&quot; -o json)<br><br>      # Extract and decode CA, Certificate, and Key<br>      ca=$(echo &quot;$secret&quot; | jq -r &#39;.data[&quot;ca.crt&quot;]&#39; | base64 --decode || echo &quot;&quot;)<br>      cert=$(echo &quot;$secret&quot; | jq -r &#39;.data[&quot;tls.crt&quot;]&#39; | base64 --decode || echo &quot;&quot;)<br>      key=$(echo &quot;$secret&quot; | jq -r &#39;.data[&quot;tls.key&quot;]&#39; | base64 --decode || echo &quot;&quot;)<br><br>      # Check if data exists<br>      if [[ -z &quot;$ca&quot; &amp;&amp; -z &quot;$cert&quot; &amp;&amp; -z &quot;$key&quot; ]]; then<br>        echo &quot;No CA, Certificate, or Key data found for secret: $secret_name. Skipping.<br>        continue<br>      fi<br><br>      # Push to Vault<br>      echo &quot;Pushing secret:  to Vault<br>      vault kv put &quot;$VAULT_PATH_PREFIX/$secret_name&quot; ca.crt=&quot;$ca&quot; tls.crt=&quot;$cert&quot; tls.key=&quot;$key<br>    done<br><br>    echo &quot;Secrets synchronized to Vault successfully.<br>---<br>apiVersion: batch/v1<br>kind: CronJob<br>metadata:<br>  name: sync-secrets-to-vault<br>  namespace: cert-manager-pki<br>spec:<br>  schedule: &quot;30 23 * * *&quot;<br>  jobTemplate:<br>    spec:<br>      template:<br>        spec:<br>          initContainers:<br>          - name: copy-script<br>            image: $CI_REGISTRY_HOST/devops/image/helm-kubectl:latest<br>            command:<br>            - &quot;sh&quot;<br>            - &quot;-c&quot;<br>            - |<br>              cp /scripts/sync-secrets-to-vault.sh /tmp/sync-secrets-to-vault.sh<br>              chmod +x /tmp/sync-secrets-to-vault.sh<br>            volumeMounts:<br>            - name: script-volume<br>              mountPath: /scripts<br>            - name: tmp-scripts<br>              mountPath: /tmp<br>          containers:<br>          - name: sync-secrets-to-vault<br>            image: $CI_REGISTRY_HOST/devops/image/helm-kubectl:latest<br>            imagePullPolicy: Always<br>            command:<br>            - &quot;/bin/sh&quot;<br>            - &quot;-c&quot;<br>            - |<br>              export VAULT_TOKEN=CI_VAULT_TOKEN<br>              export VAULT_ADDR=CI_VAULT_ADDR<br>              export VAULT_SKIP_VERIFY=1<br>              /tmp/sync-secrets-to-vault.sh<br>            volumeMounts:<br>            - name: tmp-scripts<br>              mountPath: /tmp<br>          restartPolicy: OnFailure<br>          volumes:<br>          - name: script-volume<br>            configMap:<br>              name: sync-secrets-to-vault-script<br>          - name: tmp-scripts<br>            emptyDir: {}<br>          imagePullSecrets:<br>          - name: regcred</pre><h3>Vault → VM (consul-template)</h3><p>consul-template deployed on VMs watches certificates stored in Vault<br>and renders them in the format required by each service.<br>When a certificate change is detected, it triggers a pipeline instead of reloading services directly.</p><p>This approach separates certificate renewal from service reload<br>and allows reload operations to be executed in a controlled, observable, and auditable way.</p><h3>Ansible Role: Consul-Template</h3><p>Below is the Ansible role used to deploy and configure the consul-template service on VMs.</p><p>The main responsibilities of this role are:</p><ul><li>Install and manage the consul-template service</li><li>Configure the connection to Vault</li><li>Render certificates in the format required by each service</li><li>Forward certificate changes to the pipeline layer</li></ul><p>The role is designed to be idempotent and environment-agnostic.<br>Service reloads are not executed by this role and are instead handled at the pipeline level.</p><p><strong>./defaults/main.yml:</strong></p><pre><br>consul_template_version: &quot;0.26.0&quot;<br>vault_address: &quot;{{ lookup(&#39;env&#39;, &#39;CI_VAULT_URL&#39;) }}&quot;<br>vault_token: &quot;{{ lookup(&#39;env&#39;, &#39;VAULT_TOKEN&#39;) }}&quot;<br>vault_addr: &quot;{{ lookup(&#39;env&#39;, &#39;VAULT_ADDR&#39;) }}&quot;<br>vault_path: &quot;{{ lookup(&#39;env&#39;, &#39;VAULT_PATH&#39;) }}&quot;<br>gitlab_url: &quot;{{ lookup(&#39;env&#39;, &#39;CI_GITLAB_URL&#39;) }}&quot;<br>gitlab_project_id: &quot;{{ lookup(&#39;env&#39;, &#39;CI_GITLAB_PROJECT_ID&#39;) }}&quot;<br>gitlab_ref: &quot;{{ lookup(&#39;env&#39;, &#39;CI_GITLAB_REF&#39;) }}&quot;<br>gitlab_trigger_token: &quot;{{ lookup(&#39;env&#39;, &#39;CI_GITLAB_TOKEN&#39;) }}&quot;<br>dns: dev.nginx.local.az #(for example)</pre><p><strong>./defaults/cert-update-trigger.sh:</strong></p><pre>#!/usr/bin/env bash<br>set -euo pipefail<br><br>IP=&quot;${1:?ip required}&quot;<br>ACTION=&quot;${2:?action required}&quot;     # reload|restart|cmd<br>SERVICE=&quot;${3:-}&quot;<br>CMD=&quot;${4:-}&quot;<br><br>if [[ -z &quot;${GITLAB_URL:-}&quot; || -z &quot;${PROJECT_ID:-}&quot; || -z &quot;${TRIGGER_TOKEN:-}&quot; || -z &quot;${REF:-}&quot; ]]; then<br>  eval &quot;$(systemctl show -p Environment --value consul-template \<br>  | sed &#39;s/^/export /; s/ \+/;\nexport /g&#39;)&quot;<br>fi<br><br>: &quot;${GITLAB_URL:?need GITLAB_URL}&quot;<br>: &quot;${PROJECT_ID:?need PROJECT_ID}&quot;<br>: &quot;${TRIGGER_TOKEN:?need TRIGGER_TOKEN}&quot;<br>: &quot;${REF:?need REF}&quot;<br><br>curl -skS -X POST \<br>  &quot;${GITLAB_URL}/api/v4/projects/${PROJECT_ID}/trigger/pipeline&quot; \<br>  -F &quot;token=${TRIGGER_TOKEN}&quot; \<br>  -F &quot;ref=${REF}&quot; \<br>  -F &quot;variables[CI_CERT_TRIGGER_ENABLED]=TRUE&quot; \<br>  -F &quot;variables[CERT_TARGET_IP]=${IP}&quot; \<br>  -F &quot;variables[CERT_TARGET_ACTION]=${ACTION}&quot; \<br>  -F &quot;variables[CERT_TARGET_SERVICE]=${SERVICE}&quot; \<br>  -F &quot;variables[CERT_TARGET_CMD]=${CMD}&quot;</pre><p><strong>./handlers/main.yml:</strong></p><pre>---<br># handlers file for nginx<br>- name: reload consul-template<br>  service:<br>    name: consul-template<br>    state: restarted</pre><p><strong>./templates/cert-bundle-template.ctmpl.j2:</strong></p><pre>{% raw %}{{ with secret &quot;devops/vault/pki-secrets/{% endraw %}{{ item }}{% raw %}&quot; }}<br>{{ with .Data }}<br>{{ printf &quot;%s&quot; (index . &quot;tls.crt&quot;) }}<br>{{ printf &quot;%s&quot; (index . &quot;ca.crt&quot;) }}<br>{{ printf &quot;%s&quot; (index . &quot;tls.key&quot;) }}<br>{{ end }}<br>{{ end }}<br>{% endraw %}</pre><p><strong>./templates/cert-template.ctmpl.j2:</strong></p><pre>{% raw %}{{ with secret &quot;devops/vault/pki-secrets/{% endraw %}{{ item }}{% raw %}&quot; }}<br>{{ with .Data }}<br>{{ printf &quot;%s&quot; (index . &quot;tls.crt&quot;) }}<br>{{ printf &quot;%s&quot; (index . &quot;ca.crt&quot;) }}<br>{{ end }}<br>{{ end }}<br>{% endraw %}</pre><p><strong>./templates/key-template.ctmpl.j2:</strong></p><pre>{% raw %}{{ with secret &quot;devops/vault/pki-secrets/{% endraw %}{{ item }}{% raw %}&quot; }}<br>{{ with .Data }}<br>{{ printf &quot;%s&quot; (index . &quot;tls.key&quot;) }}<br>{{ end }}<br>{{ end }}<br>{% endraw %}</pre><p><strong>./templates/cert-bundle-template.ctmpl.j2:</strong></p><pre>{% raw %}{{ with secret &quot;devops/vault/pki-secrets/{% endraw %}{{ item }}{% raw %}&quot; }}<br>{{ with .Data }}<br>{{ printf &quot;%s&quot; (index . &quot;tls.crt&quot;) }}<br>{{ printf &quot;%s&quot; (index . &quot;ca.crt&quot;) }}<br>{{ printf &quot;%s&quot; (index . &quot;tls.key&quot;) }}<br>{{ end }}<br>{{ end }}<br>{% endraw %}</pre><p><strong>./templates/consul-template-config.hcl.j2:</strong></p><pre># Vault connection settings<br>vault {<br>  address = &quot;{{ vault_address }}&quot;<br>  token   = &quot;{{ vault_token }}&quot;<br>  unwrap_token = false<br>  renew_token  = true<br>}<br><br>log_level = &quot;debug&quot;<br><br>{% if &#39;nginx&#39; in group_names %}<br>template {<br>  source = &quot;/etc/consul-template/cert-template-{{ dns }}.ctmpl&quot;<br>  destination = &quot;/etc/nginx/certs/{{ dns }}.pem&quot;<br>  perms = 0600<br>  backup = true<br>}<br><br>template {<br>  source = &quot;/etc/consul-template/key-template-{{ dns }}.ctmpl&quot;<br>  destination = &quot;/etc/nginx/certs/{{ dns }}.key&quot;<br>  perms = 0600<br>  backup = true<br>  {% if consul_template_cmd_enabled %}<br>  command = &quot;/usr/local/bin/cert-update-trigger.sh {{ ansible_host | default(inventory_hostname) }} reload nginx&quot;<br>  {% endif %}<br>}<br>{% endif %}<br><br>{% if &#39;haproxy&#39; in group_names %}<br>template {<br>  source = &quot;/etc/consul-template/cert-bundle-template-{{ dns }}.ctmpl&quot;<br>  destination = &quot;/etc/haproxy/ssl/{{ dns }}.pem&quot;<br>  perms = 0600<br>  backup = true<br>  {% if consul_template_cmd_enabled %}<br>  command = &quot;/usr/local/bin/cert-update-trigger.sh {{ ansible_host | default(inventory_hostname) }} reload haproxy&quot;<br>  {% endif %}<br>}<br>{% endif %}</pre><p><strong>./templates/consul-template.service.j2:</strong></p><pre>[Unit]<br>Description=Consul Template<br>After=network.target<br><br>[Service]<br>Environment=GITLAB_URL={{ gitlab_url | quote }}<br>Environment=PROJECT_ID={{ gitlab_project_id | quote }}<br>Environment=TRIGGER_TOKEN={{ gitlab_trigger_token | quote }}<br>Environment=REF={{ gitlab_ref | default(&#39;master&#39;) | quote }}<br><br>ExecStart=/usr/bin/consul-template -config=/etc/consul-template/config.hcl<br>ExecReload=/bin/kill -HUP $MAINPID<br>Restart=on-failure<br><br>[Install]<br>WantedBy=multi-user.target</pre><p><strong>./tasks/main.yml:</strong></p><pre># Check if consul-template binary exists<br>- name: Check if Consul Template is installed<br>  command: which consul-template<br>  register: consul_template_installed<br>  failed_when: false<br>  changed_when: false<br><br># Get current version if installed<br>- name: Check current Consul Template version<br>  command: consul-template --version<br>  register: consul_template_version_output<br>  when: consul_template_installed.rc == 0<br>  failed_when: false<br>  changed_when: false<br><br># Display current version<br>- name: Print current Consul Template version<br>  debug:<br>    msg: &quot;Current Consul Template version: {{ consul_template_version_output.stdout }}&quot;<br>  when: consul_template_version_output.stdout is defined<br><br># Extract version number for comparison<br>- name: Set current Consul Template version<br>  set_fact:<br>    current_consul_template_version: &quot;{{ consul_template_version_output.stdout.split(&#39; &#39;)[1] | regex_replace(&#39;[^0-9.]&#39;, &#39;&#39;) }}&quot;<br>  when: consul_template_version_output.stdout is defined<br><br># Display target version<br>- name: Print desired Consul Template version<br>  debug:<br>    msg: &quot;Desired Consul Template version: {{ consul_template_version }}&quot;<br><br># === Repository Setup ===<br><br># Add HashiCorp official GPG key<br>- name: Add HashiCorp GPG key<br>  apt_key:<br>    url: https://apt.releases.hashicorp.com/gpg<br>    state: present<br><br># Add HashiCorp APT repository<br>- name: Add HashiCorp repository<br>  apt_repository:<br>    repo: &quot;deb [arch=amd64] https://apt.releases.hashicorp.com {{ ansible_distribution_release }} main&quot;<br>    state: present<br><br># Refresh package cache<br>- name: Update APT package index<br>  apt:<br>    update_cache: yes<br><br># === Installation ===<br><br># Install unzip (required for some HashiCorp tools)<br>- name: Ensure unzip is installed<br>  apt:<br>    name: unzip<br>    state: present<br><br># Install consul-template from HashiCorp repo<br>- name: Install Consul Template<br>  apt:<br>    name: &quot;consul-template&quot;<br>    state: present<br><br># Verify installation<br>- name: Check new Consul Template version<br>  command: consul-template --version<br>  register: new_consul_template_version_output<br>  failed_when: false<br>  changed_when: false<br><br># Display installed version<br>- name: Print new Consul Template version<br>  debug:<br>    msg: &quot;New Consul Template version: {{ new_consul_template_version_output.stdout }}&quot;<br><br># === Configuration ===<br><br># Create config directory<br>- name: Create Consul Template configuration directory<br>  file:<br>    path: /etc/consul-template<br>    state: directory<br>    owner: root<br>    group: root<br>    mode: &#39;0755&#39;<br><br># Deploy webhook script that triggers GitLab pipeline<br>- name: Install cert update trigger script<br>  copy:<br>    src: cert-update-trigger.sh<br>    dest: /usr/local/bin/cert-update-trigger.sh<br>    owner: root<br>    group: root<br>    mode: &quot;0755&quot;<br><br># Deploy main config (Vault connection, templates)<br>- name: Create Consul Template configuration file<br>  template:<br>    src: consul-template-config.hcl.j2<br>    dest: /etc/consul-template/config.hcl<br>    owner: root<br>    group: root<br>    mode: &#39;0644&#39;<br>  notify: reload consul-template<br><br># Deploy certificate template (crt + ca)<br>- name: Create cert template for Consul Template<br>  template:<br>    src: cert-template.ctmpl.j2<br>    dest: &quot;/etc/consul-template/cert-template-{{ item }}.ctmpl&quot;<br>    owner: root<br>    group: root<br>    mode: &#39;0644&#39;<br>  loop: &quot;{{ dns_names }}&quot;<br>  notify: reload consul-template<br><br># Deploy key template (private key)<br>- name: Create key template for Consul Template<br>  template:<br>    src: key-template.ctmpl.j2<br>    dest: &quot;/etc/consul-template/key-template-{{ item }}.ctmpl&quot;<br>    owner: root<br>    group: root<br>    mode: &#39;0644&#39;<br>  loop: &quot;{{ dns_names }}&quot;<br>  notify: reload consul-template<br><br># Deploy bundle template (crt + ca + key for HAProxy)<br>- name: Create cert bundle templates for Consul Template<br>  template:<br>    src: cert-bundle-template.ctmpl.j2<br>    dest: &quot;/etc/consul-template/cert-bundle-template-{{ item }}.ctmpl&quot;<br>    owner: root<br>    group: root<br>    mode: &#39;0644&#39;<br>  loop: &quot;{{ dns_names }}&quot;<br>  notify: reload consul-template<br><br># === Service Setup ===<br><br># Deploy systemd unit file<br>- name: Create systemd service file for Consul Template<br>  template:<br>    src: consul-template.service.j2<br>    dest: /etc/systemd/system/consul-template.service<br>    owner: root<br>    group: root<br>    mode: &#39;0644&#39;<br>  notify: reload consul-template<br><br># Reload systemd to recognize new service<br>- name: Reload systemd daemon<br>  command: systemctl daemon-reload<br>  notify: reload consul-template<br><br># Enable and start service<br>- name: Start and enable consul-template service<br>  systemd:<br>    name: consul-template<br>    enabled: yes<br>    state: started<br><br># Ensure service is running<br>- name: Ensure consul-template is running<br>  systemd:<br>    name: consul-template<br>    state: started<br><br># Verify final version<br>- name: Check new Consul Template version<br>  command: consul-template --version<br>  register: new_consul_template_version_output<br>  failed_when: false<br>  changed_when: false<br><br># Display final version<br>- name: Print new Consul Template version<br>  debug:<br>    msg: &quot;New Consul Template version: {{ new_consul_template_version_output.stdout }}&quot;<br><br># Schedule nightly service reload to refresh Vault token<br>- name: Add cron job to reload consul-template service at midnight<br>  cron:<br>    name: &quot;Reload consul-template service&quot;<br>    minute: &quot;0&quot;<br>    hour: &quot;0&quot;<br>    job: &quot;/bin/systemctl reload consul-template&quot;<br>    state: present</pre><h3>Monitoring-Driven Reload</h3><p>At this stage, certificate changes are treated as observable events at the pipeline level and reload operations are executed with manual approval.</p><p>This process is measured and tracked through the following components.</p><ul><li>Metrics are collected via Pushgateway</li><li>Alerts are generated using Prometheus and Alertmanager</li><li>Real-time notifications are sent through Telegram</li></ul><pre><br>- name: VaultAlerts<br>  rules:<br>  - alert: CertificateRenewalDue<br>    expr: ( time()- certificate_renewal_time ) &gt; 86400<br>    for: 5m<br>    labels:<br>      severity: critical<br>      alert_group: vault<br>      alert_source: prometheus-custom-rules<br>    annotations:<br>      summary: &quot;Certificate Renewal Due&quot;<br>      description: &quot;{{ $labels.name }} certificate will be renewed&quot;<br><br>  - alert: CertificateUpdated<br>    expr: changes(certificate_renewal_time[10m]) &gt; 0<br>    for: 0m<br>    labels:<br>      severity: info<br>      alert_group: certificate<br>      alert_source: prometheus-custom-rules<br>    annotations:<br>      summary: &quot;Certificate updated&quot;<br>      description: &quot;Certificate {{ $labels.name }} was successfully renewed&quot;<br><br>  - alert: CertTriggerManualPending<br>    expr: cert_trigger_pending{exported_job=&quot;cert_trigger&quot;} == 1<br>    for: 1m<br>    labels:<br>      severity: warning<br>      alert_source: prometheus-custom-rules<br>    annotations:<br>      summary: &quot;Manual service restart is pending&quot;<br>      description: &quot;Waiting manual job: ip={{ $labels.ip }} action={{ $labels.action }} service={{ $labels.service }}&quot;</pre><p><strong>./scripts/webhook-triggers/CertRenewal/reload.yml</strong></p><pre>- hosts: all<br>  become: yes<br>  tasks:<br>    - name: Run action for service<br>      block:<br>        - name: Restart via systemctl<br>          ansible.builtin.systemd:<br>            name: &quot;{{ target_service }}&quot;<br>            state: restarted<br>          when: target_action == &quot;restart&quot;<br><br>        - name: Reload via systemctl<br>          ansible.builtin.systemd:<br>            name: &quot;{{ target_service }}&quot;<br>            state: reloaded<br>          when: target_action == &quot;reload&quot;<br><br>        - name: Run custom command<br>          ansible.builtin.shell: &quot;{{ target_cmd }}&quot;<br>          when: target_action == &quot;cmd&quot;</pre><p><strong>.gitlab-ci.yml:</strong></p><pre>cert-trigger-created:<br>  stage: emergency-tasks<br>  image: $CI_REGISTRY_HOST/devops/image/webhook-triggers:latest<br>  script:<br>    - |<br>      set -euo pipefail<br><br>      echo &quot;Cert update detected.&quot;<br>      echo &quot;Target IP:      ${CERT_TARGET_IP}&quot;<br>      echo &quot;Target action:  ${CERT_TARGET_ACTION}&quot;<br>      echo &quot;Target service: ${CERT_TARGET_SERVICE}&quot;<br>      echo &quot;Target cmd:     ${CERT_TARGET_CMD}&quot;<br>      echo &quot;&quot;<br>      echo &quot;Now run MANUAL job: cert-trigger-reload&quot;<br><br>      PUSHGW=&quot;https://pushgateway.local.az&quot;<br>      REQUEST_ID=&quot;${CI_PIPELINE_ID}&quot;<br><br>      cat &lt;&lt;EOF | curl -k -sS --fail --data-binary @- \<br>        &quot;${PUSHGW}/metrics/job/cert_trigger/instance/${CERT_TARGET_IP}/request/${REQUEST_ID}&quot; || true<br>      cert_trigger_pending{project=&quot;4203&quot;,manual_job=&quot;cert-trigger-service-restart&quot;,ip=&quot;${CERT_TARGET_IP}&quot;,service=&quot;${CERT_TARGET_SERVICE}&quot;,action=&quot;${CERT_TARGET_ACTION}&quot;,pipeline_id=&quot;${CI_PIPELINE_ID}&quot;,project_path=&quot;${CI_PROJECT_PATH}&quot;,pipeline_url=&quot;${CI_PIPELINE_URL}&quot;} 1<br>      EOF<br>  rules:<br>    - if: &#39;$CI_CERT_TRIGGER_ENABLED == &quot;TRUE&quot;&#39;<br>      when: on_success<br>  allow_failure: true<br><br>cert-trigger-reload:<br>  stage: maintenance-tasks<br>  needs: [&quot;cert-trigger-created&quot;]<br>  image: $CI_REGISTRY_HOST/devops/image/webhook-triggers:latest<br>  script:<br>    - |<br>      set -euo pipefail<br><br>      IP=&quot;${CERT_TARGET_IP:?missing CERT_TARGET_IP}&quot;<br>      TARGET_ACTION=&quot;${CERT_TARGET_ACTION:?missing CERT_TARGET_ACTION}&quot;<br>      TARGET_SERVICE=&quot;${CERT_TARGET_SERVICE:-}&quot;<br>      TARGET_CMD=&quot;${CERT_TARGET_CMD:-}&quot;<br><br>      echo &quot;IP=$IP ACTION=$TARGET_ACTION SERVICE=$TARGET_SERVICE CMD=$TARGET_CMD&quot;<br><br>      cd scripts/webhook-triggers/CertRenewal<br>      export ANSIBLE_HOST_KEY_CHECKING=False<br><br>      ansible-playbook reload.yml -i &quot;${IP},&quot; -u &quot;$CI_ANSIBLE_USERNAME&quot; \<br>        --extra-vars &quot;ansible_become_pass=$CI_ANSIBLE_PASSWORD ansible_password=$CI_ANSIBLE_PASSWORD target_service=$TARGET_SERVICE target_action=$TARGET_ACTION target_cmd=$TARGET_CMD&quot;<br><br>      # --- Pushgateway: close request ---<br>      PUSHGW=&quot;https://pushgateway.local.az&quot;<br>      REQUEST_ID=&quot;${CI_PIPELINE_ID}&quot;<br><br>      # 1) DONE =&gt; 0 (честный RESOLVED по правилу == 1)<br>      cat &lt;&lt;EOF | curl -k -sS --fail --data-binary @- \<br>        &quot;${PUSHGW}/metrics/job/cert_trigger/instance/${IP}/request/${REQUEST_ID}&quot; || true<br>      cert_trigger_pending{project=&quot;4203&quot;,manual_job=&quot;cert-trigger-service-restart&quot;,ip=&quot;${IP}&quot;,service=&quot;${TARGET_SERVICE}&quot;,action=&quot;${TARGET_ACTION}&quot;,pipeline_id=&quot;${CI_PIPELINE_ID}&quot;,project_path=&quot;${CI_PROJECT_PATH}&quot;,pipeline_url=&quot;${CI_PIPELINE_URL}&quot;} 0<br>      EOF<br><br>      # 2) cleanup — чтобы не копилось<br>      curl -k -sS -X DELETE \<br>        &quot;${PUSHGW}/metrics/job/cert_trigger/instance/${IP}/request/${REQUEST_ID}&quot; || true<br>  rules:<br>    - if: &#39;$CI_CERT_TRIGGER_ENABLED == &quot;TRUE&quot;&#39;<br>      when: manual<br>  allow_failure: true</pre><h3>Acknowledgements</h3><p>Special thanks to <a href="https://www.linkedin.com/in/yusuf-nasirov-002703164/"><strong>Yusuf Nasirov</strong></a> for his invaluable contributions to the monitoring and observability design.<br>His expertise in Prometheus and Pushgateway integration was critical to making this solution production-ready.</p><h3>Conclusion</h3><p>This approach keeps SSL renewal fully automated while adding visibility and control to the parts that matter most.</p><p>The focus is not on increasing automation, but on making existing automation observable, auditable, and safe to operate in production.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb519c024aac" width="1" height="1" alt=""><hr><p><a href="https://medium.com/opsuniverse/automating-ssl-renewals-a-gitops-approach-eb519c024aac">GitOps-Driven Control for Automated SSL Renewals</a> was originally published in <a href="https://medium.com/opsuniverse">OpsUniverse</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Designing Multi-Approval Pipelines in GitLab CI/CD]]></title>
            <link>https://medium.com/opsuniverse/designing-multi-approval-pipelines-in-gitlab-ci-cd-ed287eabf2f8?source=rss----c13c3d080b5d---4</link>
            <guid isPermaLink="false">https://medium.com/p/ed287eabf2f8</guid>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Samir Nabadov]]></dc:creator>
            <pubDate>Fri, 21 Nov 2025 12:11:07 GMT</pubDate>
            <atom:updated>2025-11-21T12:12:05.513Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Lightweight Approval Enforcement Model for Development Workflows</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*63O6c2YdXFM8dnKo-ejaSg.jpeg" /></figure><h3>Overview</h3><p>GitLab CI/CD supports basic Merge Request approvals, but enforcing key review rules — such as:</p><ul><li>blocking author self-approval</li><li>requiring a minimum number of approvers</li><li>enforcing multi-approval logic</li></ul><p>— is only available in the <strong>Enterprise Edition</strong>.</p><p>Because these features are not included in the <strong>Free Edition</strong>, we created a lightweight but effective <strong>CI-based multi-approval enforcement pipeline</strong> specifically for the development workflow.</p><p>The goal is simple:<br><strong>standardize the peer-review process and prevent accidental or unreviewed merges.</strong></p><h3>Why We Needed CI-Based Approval Logic</h3><p>During development, we faced several limitations:</p><ul><li>The MR author could approve their own Merge Request</li><li>The minimum review requirement was not enforced</li><li>The merge button could still be active even without enough reviews</li><li>CI had no built-in way to validate approval rules</li></ul><p>In the Enterprise Edition, these issues can be solved with GitLab’s policy engine.<br>But in the Free Edition, we needed to automate all these rules directly inside the CI pipeline.</p><h3>Target Design for the Development Workflow</h3><p>The pipeline enforces two main rules:</p><p>✔️ <strong>1. Author approvals are invalid</strong><br>The MR author is automatically removed from the approver list.</p><p>✔️ <strong>2. At least two different users must approve the Merge Request</strong><br>No additional approver lists or senior-level approvals are required.</p><p>This creates a minimal, practical, and effective review policy for the development stage.</p><h3>Pipeline Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*jn2muuZc6nbSt9Sz9WXLNw.png" /></figure><h3>Pipeline Architecture</h3><p>The pipeline is composed of four stages:</p><pre>approver → build → test → deploy</pre><ul><li><strong>approver</strong> — core logic for multi-approval validation</li><li><strong>build / test / deploy</strong> — illustrative placeholders (teams may modify or replace them)</li></ul><p>To make this workflow function correctly, two GitLab settings are important:</p><h3>1. “Pipelines must succeed” must be enabled</h3><p>This blocks merging until the approval-check job succeeds.</p><h3>2. The check-approval job is manual</h3><p>Reviewers approve first →<br>developer triggers the approval job →<br>job passes →<br><strong>merge becomes allowed</strong>.</p><p>This prevents auto-merges and gives full control over the review process.</p><h3>Pipeline Configuration (Inline Script Version)</h3><pre>stages:<br>  - approver<br>  - build<br>  - test<br>  - deploy<br><br>check-approval:<br>  stage: approver<br>  image: $CI_REGISTRY_HOST/devops/image/python:latest<br>  variables:<br>    GITLAB_TOKEN_FOR_CI: &quot;&lt;token&gt;&quot;<br>  script:<br>    - |<br>      GREEN=&quot;\033[0;32m&quot;<br>      RED=&quot;\033[0;31m&quot;<br>      BLUE=&quot;\033[0;34m&quot;<br>      NC=&quot;\033[0m&quot;<br>      <br>      echo -e &quot;${BLUE}[INFO]${NC} Checking MR approvals...&quot;<br>      <br>      # Get MR IID<br>      MR_IID=$(curl --silent --header &quot;PRIVATE-TOKEN: $GITLAB_TOKEN_FOR_CI&quot; \<br>        &quot;${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/merge_requests?state=opened&quot; | \<br>        jq -r &quot;.[] | select(.sha == \&quot;${CI_COMMIT_SHA}\&quot;) | .iid&quot;)<br>      <br>      # Get MR info<br>      MR_INFO=$(curl --silent --header &quot;PRIVATE-TOKEN: $GITLAB_TOKEN_FOR_CI&quot; \<br>        &quot;${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/merge_requests/${MR_IID}&quot;)<br>      MR_AUTHOR=$(echo &quot;$MR_INFO&quot; | jq -r &#39;.author.username&#39;)<br>      <br>      # Get approvals<br>      APPROVAL_INFO=$(curl --silent --header &quot;PRIVATE-TOKEN: $GITLAB_TOKEN_FOR_CI&quot; \<br>        &quot;${CI_API_V4_URL}/projects/${CI_PROJECT_ID}/merge_requests/${MR_IID}/approvals&quot;)<br>      APPROVED_BY=$(echo &quot;$APPROVAL_INFO&quot; | jq -r &#39;.approved_by[].user.username&#39;)<br>      echo -e &quot;${BLUE}[INFO]${NC} Approved by:&quot;<br>      echo &quot;$APPROVED_BY&quot; | sed &#39;s/^/   - /&#39;<br>      <br>      # Remove author<br>      FILTERED_APPROVERS=$(echo &quot;$APPROVED_BY&quot; | grep -v &quot;^${MR_AUTHOR}$&quot; || true)<br>      echo -e &quot;\n${BLUE}[INFO]${NC} Merge author: ${MR_AUTHOR}&quot;<br>      echo -e &quot;${BLUE}[INFO]${NC} Approvals considered (excluding author):&quot;<br>      echo &quot;$FILTERED_APPROVERS&quot; | sed &#39;s/^/   - /&#39;<br>      <br>      # At least 2 valid approvers<br>      APPROVAL_COUNT=$(echo &quot;$FILTERED_APPROVERS&quot; | grep -v &#39;^$&#39; | sort -u | wc -l)<br>      if [ &quot;$APPROVAL_COUNT&quot; -lt 2 ]; then<br>        echo -e &quot;\n${RED}[ERROR]${NC} Less than 2 valid approvals.&quot;<br>        exit 1<br>      fi<br>      echo -e &quot;\n${GREEN}[SUCCESS]${NC} Approval check passed.&quot;<br>  when: manual<br>  allow_failure: false<br>  rules:<br>    - if: &#39;$CI_PIPELINE_SOURCE == &quot;merge_request_event&quot; &amp;&amp; <br>           $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == &quot;master&quot;&#39;<br>      when: manual<br>    - when: never<br><br>build:<br>  stage: build<br>  script:<br>    - echo &quot;build&quot;<br>  rules:<br>    - if: &#39;$CI_COMMIT_REF_NAME == &quot;master&quot;&#39;<br><br>test:<br>  stage: test<br>  script:<br>    - echo &quot;test&quot;<br>  rules:<br>    - if: &#39;$CI_COMMIT_REF_NAME == &quot;master&quot;&#39;<br><br>deploy:<br>  stage: deploy<br>  script:<br>    - echo &quot;deploy&quot;<br>  when: manual<br>  allow_failure: false<br>  rules:<br>    - if: &#39;$CI_COMMIT_REF_NAME == &quot;master&quot;&#39;</pre><h3>Optional Alternative: Using a Prebuild Docker Image</h3><p>Instead of embedding the approval logic directly inside the .gitlab-ci.yml script,<br>you can use a ready-to-run lightweight Docker image that contains all validation logic:</p><pre>check-approval:<br>  stage: approver<br>  image: opsuniverse/gl-approval-checker:v18.5.1<br>  variables:<br>    GITLAB_TOKEN_FOR_CI: &quot;&lt;gitlab-token&gt;&quot;<br>    #MIN_APPROVALS: &quot;3&quot;                    # Optional: override minimum required approvals<br>    #APPROVER_LIST: &quot;user1,user2,user3&quot;    # Optional: restrict approval to specific users<br>  script:<br>    - &quot;&quot;   # No script needed — validation is done inside the container<br>  when: manual<br>  allow_failure: false<br>  rules:<br>    - if: &#39;$CI_PIPELINE_SOURCE == &quot;merge_request_event&quot; &amp;&amp;<br>           $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == &quot;master&quot;&#39;<br>      when: manual<br>    - when: never</pre><h3>How it works</h3><p>The container automatically:</p><ul><li>reads MR metadata</li><li>removes author approval</li><li>evaluates minimum required approvals</li><li>optionally validates against a custom approver whitelist</li></ul><p><strong>If no custom variables are provided</strong>, defaults apply:<br>✔ author excluded<br>✔ at least <strong>2 unique</strong> reviewers</p><h3>Why This Works Well in the Free Edition</h3><p>✔ Replaces missing Enterprise enforcement features<br>✔ Guarantees consistent review quality<br>✔ Adapts to any pipeline structure<br>✔ Logs all validation steps for traceability</p><h3>Conclusion</h3><p>The multi-approval pipeline we designed compensates for the limitations of GitLab Free Edition by:</p><ul><li>blocking author self-approval</li><li>enforcing at least two peer reviews</li><li>standardizing merge rules</li><li>making the development process more stable and controlled</li></ul><p>It provides a simple and practical way to build a safe, well-governed development workflow — even without an Enterprise license.</p><h3>Additional Notes</h3><p>The multi-approval model described in this article is a basic example. It can be expanded based on project needs, for example:</p><ul><li>custom approver groups</li><li>defining different approval levels for different roles</li><li>applying dynamic rules depending on the type of change</li></ul><p>In short, the multi-approval mechanism can be designed to be stricter, more flexible, or more complex depending on the team’s requirements.</p><p>The idea of packaging the approval validation logic into a standalone, reusable Docker image was originally proposed by <a href="https://www.linkedin.com/in/eminbayramzadeh/"><strong>Emin Bayramzadeh</strong></a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed287eabf2f8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/opsuniverse/designing-multi-approval-pipelines-in-gitlab-ci-cd-ed287eabf2f8">Designing Multi-Approval Pipelines in GitLab CI/CD</a> was originally published in <a href="https://medium.com/opsuniverse">OpsUniverse</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling Custom Image Workflows with GitOps CI/CD]]></title>
            <link>https://medium.com/opsuniverse/scaling-custom-image-workflows-with-gitops-ci-cd-80dd61d7d67f?source=rss----c13c3d080b5d---4</link>
            <guid isPermaLink="false">https://medium.com/p/80dd61d7d67f</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Samir Nabadov]]></dc:creator>
            <pubDate>Fri, 31 Oct 2025 10:48:55 GMT</pubDate>
            <atom:updated>2025-10-31T10:48:55.332Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*WSXjw9GwrGpizF4n9XtMXA.jpeg" /></figure><blockquote>Dozens of Dockerfiles, different repos, scattered pipelines…<br>Every version update felt like an adventure.<br>Then we decided: our images should be managed like code.</blockquote><h3>🔥 The Chaos Before Structure</h3><p>Some time ago, the number of custom container images in our infrastructure started to grow fast.<br>Every component had its own needs, dependencies, and “perfect” image — for example, nodejs, exporters, CLI tools, even Java runtimes.</p><p>We already had pipelines for each image — but they lived in <strong>separate repositories</strong>, with their own Dockerfiles and CI configurations.<br>That meant every small change had to be repeated across multiple repos, making updates slow and hard to track.</p><p>The biggest mess was with Java-based images.<br>Different teams were using different Java versions — 8, 11, 17, and 21. Each version had its own Dockerfile, its own base image, and its own isolated pipeline.</p><p>Even though builds were automated, they were <strong>scattered everywhere</strong>, and no one had a full picture of what was built, where, or when.</p><h3>🧭 The Turning Point: Structuring the Image Layer</h3><p>We decided to fix this chaos with a GitOps approach.<br>The idea was simple — but the impact was huge.</p><blockquote><em>“Store all custom images in Git, keep them structured, and build and release them automatically through pipelines.”</em></blockquote><p>That’s how the <strong>shared-workflow-images</strong> repository was born.<br>The structure became centralized, versioned, and ready for full CI/CD automation.</p><pre>shared-workflow-images/<br>└── custom-images/<br>    ├── fluentd/<br>    │   └── v1.14.6-debian-elasticsearch7-1.0/<br>    │       └── Dockerfile<br>    ├── maven/<br>    │   ├── 3.5-jdk-8/<br>    │   │   └── Dockerfile<br>    │   ├── 3.8.4-openjdk-17-slim/<br>    │   │   └── Dockerfile<br>    │   ├── 3.8.5-openjdk-11/<br>    │   │   └── Dockerfile<br>    │   └── 3.9.5-openjdk-21/<br>    │       └── Dockerfile<br>    ├── openjdk/<br>    │   ├── 17-jdk-slim/<br>    │   │   └── Dockerfile<br>    │   └── 21-jdk-slim-runtime/<br>    │       └── Dockerfile<br>    ├── consul/<br>    │   └── 1.16.1/<br>    │       └── Dockerfile<br>    ├── grafana/<br>    │   └── 10.1.5/<br>    │       └── Dockerfile<br>    ├── node/<br>    │   ├── 16-alpine/<br>    │   │   └── Dockerfile<br>    │   ├── 18-alpine/<br>    │   │   └── Dockerfile<br>    │   └── 18.19-alpine/<br>    │       └── Dockerfile<br>    ├── pyspark-notebook/<br>    │   └── 3.11.6/<br>    │       └── Dockerfile<br>    └── prometheus-msteams/<br>        └── v1.5.2/<br>            └── Dockerfile<br><br>scripts/<br>└── image-build/<br>    ├── main.py<br>    ├── requirements.txt<br>    └── pipeline_template.j2<br><br>.gitlab-ci.yml</pre><h3>🧱 Example: Fluentd and Consul Dockerfiles</h3><p><strong>./custom-images/fluentd/v1.14.6-debian-elasticsearch7–1.0/Dockerfile:</strong></p><pre>FROM fluent/fluentd-kubernetes-daemonset:v1.14.6-debian-elasticsearch7-1.0<br>RUN apt-get update &amp;&amp; apt-get install -y ca-certificates<br>RUN fluent-gem install fluent-plugin-detect-exceptions<br>RUN fluent-gem install fluent-plugin-record-modifier --no-document<br>RUN fluent-gem install fluent-plugin-lua --no-document<br>RUN mkdir -p /fluentd/scripts &amp;&amp; \<br>    printf &#39;%s\n&#39; \<br>      &#39;function remove_labels_app(tag, timestamp, record)&#39; \<br>      &#39;  record[&quot;kubernetes.labels.app&quot;] = nil&#39; \<br>      &#39;  return 1, timestamp, record&#39; \<br>      &#39;end&#39; &gt; /fluentd/scripts/remove_label_app.lua</pre><p><strong>./custom-images/consul/1.16.1/Dockerfile:</strong></p><pre>FROM ubuntu:22.04<br>ENV DEBIAN_FRONTEND=noninteractive<br>ENV TZ=UTC<br>RUN apt update &amp;&amp; \<br>    apt install -y ca-certificates openssl wget curl git python3 python3-pip openssh-client unzip &amp;&amp; \<br>    rm -rf /var/lib/apt/lists/*<br>RUN wget --no-check-certificate https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 -O /usr/bin/yq &amp;&amp; chmod +x /usr/bin/yq<br>ENV CONSUL_VERSION=1.16.1<br>RUN wget --no-check-certificate https://releases.hashicorp.com/consul/${CONSUL_VERSION}/consul_${CONSUL_VERSION}_linux_amd64.zip \<br>    &amp;&amp; unzip consul_${CONSUL_VERSION}_linux_amd64.zip \<br>    &amp;&amp; mv consul /usr/local/bin &amp;&amp; rm consul_${CONSUL_VERSION}_linux_amd64.zip<br>RUN consul --version</pre><h3>🧩 Dynamic Pipeline Files</h3><p>It only took a few simple files to make the dynamic pipelines work.</p><p><strong>./scripts/image-build/requirements.txt:</strong></p><pre>Jinja2==3.1.2</pre><p><strong>./scripts/pipeline_template.j2:</strong></p><pre>stages:<br>{% for image in directory %}<br>  - {{ image.image_name }}<br>{% endfor %}<br><br>{% for image in directory %}<br>release_{{ image.image_name }}-{{ image.image_tag }}:<br>  stage: {{ image.image_name }}<br>  image:<br>    name: gcr.io/kaniko-project/executor:latest<br>    entrypoint: [&quot;&quot;]<br>  variables:<br>    CI_PROJECT_NAME_IMAGE: devops/image<br>  script:<br>    - mkdir -p /kaniko/.docker<br>    - echo &quot;{\&quot;auths\&quot;:{\&quot;${CI_NEXUS_REGISTRY}\&quot;:{\&quot;auth\&quot;:\&quot;$(echo -n ${CI_NEXUS_USERNAME}:${CI_NEXUS_PASSWORD}| base64)\&quot;}}}&quot; &gt; /kaniko/.docker/config.json<br>    - /kaniko/executor --context $CI_PROJECT_DIR --dockerfile $CI_PROJECT_DIR/custom-images/{{ image.image_name }}/{{ image.image_tag }}/Dockerfile --insecure --skip-tls-verify --destination ${CI_NEXUS_REGISTRY}/${CI_PROJECT_NAME_IMAGE}/{{ image.image_name }}:{{ image.image_tag }} --use-new-run<br>  when: manual<br>  allow_failure: true<br>  tags:<br>    - devops<br>{% endfor %}</pre><p><strong>./scripts/main.py:</strong></p><pre>from jinja2 import Environment, FileSystemLoader<br>import os<br>import glob<br><br>ci_project_dir = os.getenv(&#39;CI_PROJECT_DIR&#39;)<br><br>def setup_jinja_environment():<br>    file_loader = FileSystemLoader(&#39;./&#39;)<br>    return Environment(loader=file_loader)<br><br>def render_template(environment, template_file, context):<br>    template = environment.get_template(template_file)<br>    return template.render(context)<br><br>def write_output_to_file(output, file_path):<br>    with open(file_path, &quot;x&quot;) as file:<br>        file.write(output)<br><br>def get_directories(root_path):<br>    directories = []<br>    for dir_path in glob.glob(os.path.join(root_path, &quot;*&quot;, &quot;*&quot;)):<br>        dir_parts = dir_path.split(os.sep)<br>        if os.path.isdir(dir_path):<br>            dir_name_index = dir_parts.index(&quot;custom-images&quot;) + 1<br>            dir_name = dir_parts[dir_name_index]<br>            sub_dir_name = dir_parts[dir_name_index + 1]<br>            directories.append({&#39;image_name&#39;: dir_name, &#39;image_tag&#39;: sub_dir_name})<br>    return directories<br><br>def main():<br>    jinja_env = setup_jinja_environment()<br><br>    directories = get_directories(f&#39;{ci_project_dir}/shared-workflow-images/custom-images/&#39;)<br><br>    output = render_template(jinja_env, &#39;pipeline_template.j2&#39;, {&#39;directory&#39;: directories})<br><br>    write_output_to_file(output, &#39;child_pipeline_gitlab_ci.yml&#39;)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h3>🔧 How the Pipeline Works</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bkkBmwMCOofHrneKyvP9EA.png" /></figure><p>Here’s how the process flows step by step:</p><p><strong>1. Commit the Dockerfile</strong><br>A new Dockerfile is committed for any image.<br>GitLab automatically triggers the pipeline.</p><p><strong>2. Trigger Image Build Job</strong><br>This stage runs main.py, which scans and analyzes all existing images.</p><p><strong>3. Generate Child Pipeline YAML</strong><br>The script goes through all folders inside custom-images/<br>and automatically creates a job named release_&lt;image&gt;_&lt;tag&gt; for each one.</p><p><strong>4. Parallel Execution</strong><br>Each image build job can run in parallel to speed up the process, or sequentially when needed — providing full control over how workloads are executed.</p><p><strong>5. Push to Nexus Registry</strong><br>Each image is built with Kaniko and pushed directly to the Nexus registry.</p><p><strong>6. All Images Built and Pushed</strong><br>Once the pipeline completes, all image statuses are visible and fully traceable.</p><p><strong>6. All Images Built and Pushed</strong><br>Once the pipeline completes, all image statuses are visible and fully traceable.</p><h3>🚀 Result: From Chaos to Structured Automation</h3><p>With this approach:<br>✅ Image builds are now fully centralized and automated — no more scattered pipelines across multiple repos.<br>✅ All images are versioned and easy to trace.<br>✅ The CI/CD process runs automatically — or can be triggered manually when needed.<br>✅ Every change is linked to a Git commit.<br>✅ All images in the registry are auditable and fully traceable.</p><h3>🧠 Expanding This Approach</h3><p>This approach isn’t limited to just the build stage — it can also cover security, configuration, and integration steps within the same flow.</p><p>For example:</p><ul><li>Certificates, CAs, or other configurations can be integrated directly into the image build process. They can be stored securely in systems like Vault and automatically added to images during build time.</li><li>Security and scanning tools (like <strong>Trivy</strong>, <strong>Grype</strong>, etc.) can be easily integrated into the pipeline so that every image is checked for vulnerabilities during build.</li><li>Common scripts, agents, or policies can also be centralized and reused across multiple images.</li></ul><p>In short, this approach creates a solid foundation not just for building container images — but for automating, securing, and monitoring your entire DevOps ecosystem.</p><h3>💡 Final Thoughts: “Images Are Code Too”</h3><p>Today, images are no longer just artifacts — they are stored, versioned, and managed just like code.<br>The GitOps approach allowed us to extend the “infrastructure as code” principle to container images.</p><p>With this model:</p><ul><li>The build process no longer depends on manual effort.</li><li>The CI/CD flow becomes more transparent and scalable.</li><li>And most importantly — we get a reliable, consistent container ecosystem.</li></ul><p>✨ For us, docker build is no longer just a command — it’s a Git commit.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80dd61d7d67f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/opsuniverse/scaling-custom-image-workflows-with-gitops-ci-cd-80dd61d7d67f">Scaling Custom Image Workflows with GitOps CI/CD</a> was originally published in <a href="https://medium.com/opsuniverse">OpsUniverse</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Centralized GitLab Pipelines — The End of CI Chaos]]></title>
            <link>https://medium.com/opsuniverse/centralized-gitlab-pipelines-the-end-of-ci-chaos-3d3497ef456c?source=rss----c13c3d080b5d---4</link>
            <guid isPermaLink="false">https://medium.com/p/3d3497ef456c</guid>
            <category><![CDATA[gitops]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[gitlab]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Samir Nabadov]]></dc:creator>
            <pubDate>Mon, 20 Oct 2025 10:27:39 GMT</pubDate>
            <atom:updated>2025-10-21T13:38:08.219Z</atom:updated>
            <content:encoded><![CDATA[<h3>Centralized GitLab Pipelines — The End of CI Chaos</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1007/1*NHF4cFzbSq4D-uA1cqpWSQ.png" /></figure><h3>🧠 Introduction: It Starts Simple… Then Grows</h3><p>Everything started simple — one repo for each service, one .gitlab-ci.yml, and a few jobs. At first, it worked well. But as the number of services grew, that simplicity didn’t last long. We soon noticed that the same jobs were copied across dozens or even hundreds of repos. Each change meant opening multiple PRs, waiting for merges, and tracking versions manually.</p><blockquote>Slowly, what started as <em>“CI flexibility”</em> turned into <em>“CI chaos.”</em></blockquote><p>This article explains how we fixed that chaos — <br>how we started with local pipelines, introduced shared CI templates,<br>and finally built a centralized CI/CD setup that is simple, secure, and scalable.</p><h3>⚙️ Previous Structure: Every Repo on Its Own</h3><p>In the early years, each service had its own .gitlab-ci.yml file — all jobs and CI logic were written directly inside that repo.<br>This worked fine when there were only a few projects, but as the number of services grew, it quickly became a problem.</p><blockquote>The same jobs were repeated across dozens — sometimes hundreds — of repositories.<br>Every small change or fix had to be done manually in each repo.</blockquote><p>As a result:</p><ul><li><strong>Redundant configuration:</strong> The same build, test, and deploy jobs existed in many repos.</li><li><strong>Hard to maintain:</strong> Changing one job meant opening PRs and waiting for merges across all projects.</li><li><strong>Inconsistency:</strong> Different repos started using different variables, images, and behaviors for the same processes.</li></ul><h3>🧠 First Step: Creating CI Templates</h3><p>To partially solve the problem, we created <strong>central CI templates</strong>.<br>A new “central CI repository” was introduced, and all main jobs were moved there.</p><p>Each service’s .gitlab-ci.yml only included the jobs relevant to its stack.<br>For example, backend projects used <strong>Java (Gradle or Maven)</strong> templates,<br>Python services had their own build and deploy logic, frontend apps used <strong>Node.js</strong> pipelines, and mobile projects had dedicated jobs.</p><p>Every project simply included the correct CI template for its stack, and all required pipeline stages were applied automatically.</p><p><em>(Note: This article focuses on the centralized CI structure — <br>the details of the individual templates are not covered here.)</em></p><p><strong>.gitlab-ci.yml:</strong></p><pre>include:<br>  - project: &quot;devops/ci-templates&quot;<br>    file: &quot;templates/.gitlab-ci.yml&quot;<br><br>variables:<br>  # Project Configuration Variables<br>  CI_PROJECT_MODE:     &quot;MONO&quot;<br>  CI_PROJECT_TYPE:     &quot;BACKEND&quot;<br>  CI_APPLICATION_TYPE: &quot;GRADLE&quot;<br>  CI_BRANCHING_TYPE:   &quot;GITFLOW&quot;<br>  CI_CODE_STYLE:       &quot;TRUE&quot;<br>  CI_RELEASE_TYPE:     &quot;JIB&quot;<br><br>  # Base image used for building and running the project<br>  CI_IMAGE_BUILD:   $CI_REGISTRY_HOST/devops/image/openjdk:11-jdk<br>  CI_IMAGE_RUNTIME: $CI_REGISTRY_HOST/devops/image/openjdk:11-jre</pre><p>As a result, the CI structure became more standardized — <br>repeated jobs for each stack were moved to a central place.</p><h3>🚧 But… As Projects Grew, This Wasn’t Enough</h3><p>Over time, the number of projects kept increasing.<br>There were now dozens of teams and hundreds of services — each storing different variables in their own .gitlab-ci.yml files.</p><p>Whenever we needed to add a new variable, update a Snyk configuration, or change an image, we had to contact every team and make the same update in all repositories again.</p><p>As a result:</p><ul><li>We had <strong>centralized jobs</strong>, but <strong>scattered variables</strong>.</li><li>CI became <strong>less flexible</strong> and <strong>slower to change</strong>.</li><li>The <strong>DevOps team</strong> ended up handling a growing amount of manual work.</li></ul><h3>🧱 The Real Structure: The New Form of the Central CI Repository</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t3_ZiLkE4TFr4yIK9pGvHA.png" /></figure><p>This new CI/CD architecture doesn’t just centralize project configuration — <br>it also integrates <strong>DevSecOps processes</strong> directly into the structure.<br>Security policies and <strong>Snyk configurations</strong> are no longer stored separately in each project; they are managed centrally from one place.</p><pre>ci-shared-resources/<br>├── pipeline-resources/<br>│   └── development/<br>│       └── code/<br>│           ├── group01/<br>│           │   ├── project01/<br>│           │   │   ├── .gitlab-ci.yml<br>│           │   │   └── .snyk<br>│           │   ├── project02/<br>│           │   │   ├── .gitlab-ci.yml<br>│           │   │   └── .snyk<br>│           │   └── project03/<br>│           │       ├── .gitlab-ci.yml<br>│           │       └── .snyk<br>│           ├── group02/<br>│           │   ├── project01/<br>│           │   │   ├── .gitlab-ci.yml<br>│           │   │   └── .snyk<br>│           │   ├── project02/<br>│           │   │   ├── .gitlab-ci.yml<br>│           │   │   └── .snyk<br>│           │   └── project03/<br>│           │       ├── .gitlab-ci.yml<br>│           │       └── .snyk<br>│           └── ...<br>│<br>├── shared-settings/<br>│   └── .snyk<br>└── README.md</pre><h3>🔧 <strong>Design Principles:</strong></h3><ul><li>All <strong>shared CI variables</strong> and <strong>DevSecOps configurations</strong> (like Snyk rules, severity thresholds, and prevent modes) are stored in a <strong>central repository</strong>.</li><li>Each project’s .gitlab-ci.yml includes references to these shared configurations instead of redefining them locally.</li><li><strong>Reusable design</strong> — adding a new group or project is as easy as creating a new folder.<br>With custom scripts, you can make this process even more seamless by automatically generating the required structure and initial CI files.</li><li><strong>Centralized change management</strong> — any change to variables, images, or security rules is made once and automatically applied across all projects.</li></ul><h3>🚀 Key Benefits</h3><ul><li><strong>Full CI independence</strong> — Each project’s .gitlab-ci.yml and .snyk configurations are stored centrally.<br>In the project repo, only an include reference remains.</li><li><strong>Centralized security and DevSecOps integration</strong> –<br>Security policies, Snyk organizations, and prevent strategies are now managed directly from the central repository.<br>The DevSecOps team can apply updates without touching individual code repositories.</li><li><strong>Simplified management and transparency</strong> –<br>All CI changes are visible and controlled from one place, eliminating inconsistency and duplication.</li><li><strong>Automatic update mechanism</strong> –<br>Any change (to variables, images, or security policies) is made once in the central repository<br>and automatically propagated to all projects.</li></ul><h3>⚙️ Simple and Universal .gitlab-ci.yml at the Project Level</h3><p>Now, every project’s CI configuration is this simple 👇</p><p><strong>.gitlab-ci.yml:</strong></p><pre># Including shared and reusable CI/CD configurations and templates <br>include:<br>  # Core CI/CD templates from central repo (jobs, stages, build &amp; deploy logic)<br>  - project: $CI_PROJECT_TEMPLATE_PATH<br>    file: .gitlab-ci.yml<br><br>  # Project-specific shared configs (variables, security settings, Snyk configs)<br>  - project: $CI_PROJECT_SHARED_PATH<br>    file: $CI_PIPELINE_SHARED_PATH/$CI_PROJECT_NAMESPACE/$CI_PROJECT_NAME/.gitlab-ci.yml</pre><p>💡 <strong>Quick explanation:</strong><br>The first include brings in the <strong>core pipeline stages</strong> (build, test, deploy).<br>The second include adds the <strong>project-specific variables and security configurations</strong>.</p><h3>🧱 <strong>Example: Central Variables File</strong></h3><p>The .gitlab-ci.yml stored in the central repository looks like this 👇</p><p><strong>ci-shared-resources/pipeline-resources/development/code/group01/project01/.gitlab-ci.yml:</strong></p><pre># CI/CD pipeline variables for Snyk job configuration<br>variables:<br>  <br>  # Project Configuration Variables<br>  CI_PROJECT_MODE:     &quot;MONO&quot;<br>  CI_PROJECT_TYPE:     &quot;BACKEND&quot;<br>  CI_BRANCHING_TYPE:   &quot;GITFLOW&quot;<br>  CI_APPLICATION_TYPE: &quot;GRADLE&quot;<br>  CI_RELEASE_TYPE:     &quot;JIB&quot;<br>  <br>  # Base image used for building and running the project<br>  CI_IMAGE_BUILD:   $CI_REGISTRY_HOST/devops/image/openjdk:11-jdk<br>  CI_IMAGE_RUNTIME: $CI_REGISTRY_HOST/devops/image/openjdk:11-jre<br>  <br>  # DevSecOps-related variables<br>  CI_SQUAD_NAME:    &quot;Unknown&quot;<br>  CI_SNYK_ORG_NAME: &quot;Unknown&quot;<br>  <br>  # Unified prevent mode variables<br>  CI_SCA_SEVERITY_THRESHOLD: &quot;critical&quot;<br>  CI_PREVENT_MODE: |<br>    {<br>      &quot;develop&quot;: {&quot;SAST&quot;: false, &quot;SCA&quot;: true},<br>      &quot;stage&quot;: {&quot;SAST&quot;: false, &quot;SCA&quot;: true},<br>      &quot;master&quot;: {&quot;SAST&quot;: false, &quot;SCA&quot;: true}<br>    }</pre><p>💡 <strong>Quick explanation:</strong><br>All core variables and DevSecOps configurations are centralized.<br>Any change made once is automatically applied across all projects.</p><h3>🧭 <strong>Conclusion: From CI Chaos to an Automated, Organized System</strong></h3><p>With this approach, GitLab CI/CD is no longer a chaotic mix of dozens of duplicated files and scattered configurations — <br>it’s now a unified, flexible, and secure automation platform.</p><p><strong>As a result:</strong></p><ul><li>All CI/CD changes are managed centrally.</li><li>New projects can be integrated within seconds.</li><li>Security rules and variables are applied automatically.</li><li>Inconsistencies and duplication risks are completely eliminated.</li><li>Developers can focus on writing code instead of managing CI logic.</li></ul><p>This model represents the real-world implementation of the <strong>“Pipelines as Code”</strong> principle within the GitLab ecosystem — a scalable CI/CD strategy that combines simplicity, consistency, and transparency.</p><blockquote>💡 <strong>Note:</strong><br>This structure doesn’t just centralize existing CI processes — it also opens the door for broader centralization in the future. For example, <strong>QA strategies</strong>, <strong>monitoring and observability steps</strong>, or even <strong>audit and compliance workflows</strong> can all be managed under the same centralized model.</blockquote><blockquote>In essence, this approach lays the foundation for a unified and scalable <strong>DevOps management ecosystem</strong>.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d3497ef456c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/opsuniverse/centralized-gitlab-pipelines-the-end-of-ci-chaos-3d3497ef456c">Centralized GitLab Pipelines — The End of CI Chaos</a> was originally published in <a href="https://medium.com/opsuniverse">OpsUniverse</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pipeline-Driven Kubernetes — Add-ons Deployment (Part 2)]]></title>
            <link>https://medium.com/opsuniverse/pipeline-driven-kubernetes-add-ons-deployment-part-2-c5ae2d801a77?source=rss----c13c3d080b5d---4</link>
            <guid isPermaLink="false">https://medium.com/p/c5ae2d801a77</guid>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Samir Nabadov]]></dc:creator>
            <pubDate>Thu, 09 Oct 2025 11:47:41 GMT</pubDate>
            <atom:updated>2025-10-09T11:47:40.877Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pipeline-Driven Kubernetes — Add-ons Deployment (Part 2)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3l9PNsj5p--Evzxsj0ALXw.png" /></figure><h3>Introduction: Add-on Orchestration</h3><p>In the previous article — <a href="https://medium.com/opsuniverse/pipeline-driven-kubernetes-cluster-management-part-1-02f9b96228ef">📄 <em>Pipeline-Driven Kubernetes — Cluster Management (Part 1)</em></a> — we explored how Kubernetes clusters can be managed automatically through CI/CD pipelines.</p><p>In this part, we take the approach one step further: explaining a structured, pipeline-driven process for deploying cluster add-ons such as <strong>MetalLB</strong>, <strong>Ingress</strong>, <strong>ArgoCD</strong>, <strong>Cert-Manager</strong>, and others.</p><p>The goal is to build a <strong>fully automated system</strong> where each add-on is managed through its own YAML definitions, configuration, and GitLab CI stage — ensuring consistency, traceability, and repeatability across all environments.</p><h3>Our Approach</h3><p>Manual installation of add-ons (for example, using <strong>kubectl apply -f</strong> or <strong>helm install</strong>) may work fine for quick tests, but in large-scale environments it creates serious management and stability challenges.</p><p>The main drawbacks of manual deployment are:</p><p>⚠️ <strong>Inconsistency risk</strong> — the same commands can produce different results across environments (DEV, STAGE, PROD).<br>🔄 <strong>Human error and repetition</strong> — each manual step can introduce mistakes, version mismatches, or missing configurations, leading to instability.<br>🧩 <strong>Lack of traceability</strong> — it’s hard to track which engineer deployed which add-on, when, and in what version.<br>🕒 <strong>Time waste</strong> — repeating the same configuration manually across multiple environments consumes valuable engineering time.<br>🧠 <strong>Decentralized management</strong> — when add-on configurations are stored across multiple repositories or systems, overall visibility is lost.</p><p>In contrast, a <strong>pipeline-driven model</strong> automates the entire add-on deployment process through CI/CD pipelines using Git-managed <strong>metadata</strong>, <strong>values</strong>, and <strong>manifest</strong> files.</p><p>This approach makes deployments:</p><ul><li>Fully <strong>traceable</strong>,</li><li><strong>Repeatable</strong> and <strong>standardized</strong>,</li><li>And ensures consistent configurations and version control across all environments.</li></ul><h3>Repository Structure</h3><pre>k8s-cluster-provisioning-repository/<br>├── ENVIRONMENT/<br>│   ├── DEV/<br>│   │   └── HA-CLUSTER-K8S/<br>│   │       ├── addons/<br>│   │       │   ├── nfs-provisioner/<br>│   │       │   │   ├── manifests.yml<br>│   │       │   │   ├── metadata.yml<br>│   │       │   │   └── values.yml<br>│   │       │   ├── metallb/<br>│   │       │   │   ├── manifests.yml<br>│   │       │   │   ├── metadata.yml<br>│   │       │   │   └── values.yml<br>│   │       │   ├── ...<br>│   │       │   └── ...<br>│   │       │<br>│   │       ├── group_vars/<br>│   │       │   ├── haproxy.yml<br>│   │       │   └── k8s_cluster.yml<br>│   │       └── inventory.yml<br>│   │<br>│   └── PROD/<br>│       └── HA-CLUSTER-K8S/<br>│           ├── addons/<br>│           │   ├── nfs-provisioner/<br>│           │   ├── metallb/<br>│           │   ├── ...<br>│           │   └── ...<br>│           │<br>│           ├── group_vars/<br>│           │   ├── haproxy.yml<br>│           │   └── k8s_cluster.yml<br>│           └── inventory.yml<br>│<br>└── .gitlab-ci.yml</pre><h3>Add-on Deployment Flow — End-to-End</h3><p>The main configuration of Kubernetes clusters (<em>inventory.yml</em> and <em>group_vars/</em>) was explained in detail in the previous article.<br>In this section, we focus on a <strong>structured deployment model at the add-on level</strong>, where each component is managed in a consistent, automated, and version-controlled way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IRxVkynUPXuKJG1ZKjmvsQ.png" /></figure><h3>Step 1: Add-on Folder &amp; File Structure</h3><p>Each cluster (for example, <strong>HA-CLUSTER-K8S</strong>) can contain dozens of add-ons — such as <strong>Istio</strong>, <strong>MetalLB</strong>, <strong>Cert-Manager</strong>, <strong>ArgoCD</strong>, <strong>Prometheus</strong>, <strong>Trivy</strong>, and others. Each add-on is stored in its own dedicated folder and consists of <strong>three main YAML files</strong>:</p><h4>1. metadata.yml</h4><p>Stores the add-on’s source and identification details, including:</p><ul><li>Chart repository URL and version</li><li>Application or release name</li><li>Namespace</li><li>Deployment and repository parameters</li></ul><p><strong>./environmet/dev/ha-cluster-k8s/addons/nfs-provisioner/metadata.yml:</strong></p><pre>app_version: 4.0.18<br>repository_url: https://kubernetes-sigs.github.io/nfs-subdir-external-provisioner/<br>repository_name: nfs-provisioner<br>chart_name: nfs-subdir-external-provisioner<br>deployment_name: nfs-provisioner<br>namespace: nfs-provisioner</pre><p><strong>./environmet/dev/ha-cluster-k8s/addons/metallb/metadata.yml:</strong></p><pre>app_version: 4.7.0<br>repository_url: https://charts.bitnami.com/bitnami<br>repository_name: metallb<br>chart_name: metallb<br>deployment_name: metallb<br>namespace: metallb</pre><h4>2. values.yml</h4><p>Contains Helm chart or custom configuration parameters for the add-on.<br>Only the parameters that need to override the default <em>values.yaml</em> are defined here. During pipeline execution, this file is passed to the Helm command using <strong>-f values.yml</strong>, overriding the chart’s default values.</p><p><strong>./environmet/dev/ha-cluster-k8s/addons/nfs-provisioner/values.yml:</strong></p><pre>nfs:<br>  server: 10.0.0.11<br>  path: /var/nfs<br>storageClass:<br>  create: true  <br>  name: nfs-client<br>  defaultClass: true</pre><p><strong>./environment/dev/ha-cluster-k8s/addons/metallb/values.yml</strong></p><pre>global:<br>  security:<br>    allowInsecureImages: true<br>  imageRegistry: registry.devops.az<br><br>controller:<br>  image:<br>    repository: metallb/controller<br>    tag: latest<br>    pullPolicy: IfNotPresent</pre><p>➡️ In this file, only environment-specific changes (e.g., <strong>DEV</strong>, <strong>PROD</strong>, etc.) are stored, while all other parameters are automatically inherited from the Helm chart’s default <em>values.yaml</em>.</p><p>📦 <strong>Note:</strong> The Helm chart itself is <strong>not stored</strong> in the Git repository — only the <em>values.yml</em> configuration files are. During pipeline execution, the chart is dynamically fetched from its repository and deployed using the parameters defined here.</p><h4>3. manifests.yml</h4><p>Contains additional Kubernetes objects related to the add-on (e.g., <strong>Gateway</strong>, <strong>VirtualService</strong>, <strong>Certificate</strong>, <strong>ConfigMap</strong>, <strong>Ingress</strong>, etc.).<br>All supplementary manifests required for the component are collected and managed within this file.</p><p><strong>./environment/dev/ha-cluster-k8s/addons/nfs-provisioner/manifests.yml</strong></p><pre>---<br>apiVersion: storage.k8s.io/v1<br>kind: StorageClass<br>metadata:<br>  name: nfs<br>allowVolumeExpansion: true<br>provisioner: cluster.local/nfs-provisioner-nfs-subdir-external-provisioner<br>reclaimPolicy: Delete<br>volumeBindingMode: Immediate</pre><p><strong>./environment/dev/ha-cluster-k8s/addons/metallb/manifests.yml</strong></p><pre>---<br>apiVersion: metallb.io/v1beta1<br>kind: L2Advertisement<br>metadata:<br>  name: data-l2<br>  namespace: metallb<br>spec:<br>  ipAddressPools:<br>  - data-pool<br>---<br>apiVersion: metallb.io/v1beta1<br>kind: IPAddressPool<br>metadata:<br>  name: data-pool<br>  namespace: metallb<br>spec:<br>  addresses:<br>    - 10.0.0.10/32</pre><p>➡➡️ This approach ensures that each add-on’s configuration is <strong>isolated</strong>, <strong>version-controlled</strong>, and <strong>fully traceable</strong>. As a result, all manifests required for any component are stored in one place, enabling precise and repeatable deployments.</p><h3>Step 4: Vault Secrets Structure</h3><p>All data stored in Vault follows a clear hierarchy based on <strong>Environment → Component → Secret Type</strong>. This structure gives every cluster and add-on its own <strong>dedicated and isolated secret space</strong>, ensuring security and separation between environments.</p><pre>devops_kv/<br>├── DEV/                       <br>│   ├── HA-CLUSTER-K8S/<br>│   │   ├── config                     <br>│   │   ├── addons/<br>│   │   │   ├── nfs-provisioner/<br>│   │   │   │   └── credentials-auth   <br>│   │   │   ├── metallb/<br>│   │   │   │   └── credentials-auth   <br>│   │   │   └── ...<br>│   └── ...<br>│<br>├── PROD/                      <br>│   ├── HA-CLUSTER-K8S/<br>│   │   ├── config<br>│   │   ├── addons/<br>│   │   │   ├── nfs-provisioner/<br>│   │   │   │   └── credentials-auth<br>│   │   │   ├── metallb/<br>│   │   │   │   └── credentials-auth<br>│   │   │   └── ...<br>│   │   └── credentials-auth<br>│   └── ...</pre><h3>💡 <strong>Explanation</strong></h3><ul><li><strong>config</strong> → Stores the cluster’s kubeconfig (<strong>CI_KUBE_CONFIG</strong>) and related parameters.<br><strong>addons/*/credentials-auth</strong> → Contains add-on–specific secrets (e.g., Metallb IP pool, NFS server IP, etc.).<br><strong>...</strong> → The same structure can be extended to include other components such as ArgoCD, Cert-Manager, Keycloak, Prometheus, and more.</li></ul><p>💬 <strong>Note:</strong><br>To add a new add-on, simply create the path <strong>addons/&lt;addon-name&gt;/credentials-auth</strong> in Vault and store the corresponding secrets there.</p><h3>Step 3: Add-on Deployment Pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NUlA1Q8QRuxZb1VRH99UPg.png" /></figure><p>The add-on deployment process is managed through a <strong>centralized GitLab CI/CD pipeline</strong>. Each add-on has its own job defined in the <strong>.gitlab-ci.yml </strong>file (for example, <em>istio-addons-setup</em>, <em>argocd-addons-setup</em>, <em>metallb-addons-setup</em>, etc.).<br>These jobs are defined statically but become active only for the selected <strong>environment</strong>, <strong>scope</strong>, and <strong>component</strong> using <strong>rules</strong>.</p><p>The pipeline runs mainly under a single stage — <strong>addons-deploy</strong> — where all active add-on jobs for the target environment can be triggered manually.</p><p>Each job extends the <strong>.common-k8s-addons-deployment</strong> template, which reads the <strong>metadata.yml</strong>, <strong>values.yml</strong>, and <strong>manifests.yml</strong> files to deploy add-ons via <strong>Helm</strong> or <strong>kubectl</strong>.</p><p>During deployment, <strong>Vault secrets</strong> are automatically fetched and exported as environment variables.<br>These variables are then injected into YAML files using <strong>envsubst</strong>, allowing each add-on’s configuration to be rendered dynamically at runtime.</p><p>This approach ensures that:</p><ul><li>Secrets are managed centrally and securely.</li><li>YAML templates are dynamically rendered per environment.</li><li>All add-ons follow a standardized, repeatable, and consistent deployment process.</li></ul><p><strong>.gitlab-ci.yml:</strong></p><pre>stages:<br>  - addons-deploy<br><br>variables:<br>  CI_RUNNER_TAG: devops  <br>  VAULT_ADDR: https://vault.devops.az:8200<br>  VAULT_KV_PATH: &quot;devops_kv&quot;<br><br># A collection of reusable tasks for various pipeline operations<br>.task-library:<br><br>  # Authenticate with Vault and retrieve secrets or kubeconfig based on context<br>  shared-vault-auth:<br>    - |<br>      # Determine Vault path based on whether an addon is specified<br>      if [ -n &quot;$CI_K8S_ADDON_NAME&quot; ]; then<br>        # Only addon defined<br>        export VAULT_PATH=&quot;${VAULT_KV_PATH}/${CI_INFRASTRUCTURE_ENVIRONMENT}/${CI_INFRASTRUCTURE_COMPONENT}/addons/${CI_K8S_ADDON_NAME}/credentials-auth&quot;<br><br>    - |<br>      # Check if VAULT_PATH is set and the secret exists in Vault<br>      if [ -n &quot;$VAULT_PATH&quot; ] &amp;&amp; vault kv get -format=json &quot;$VAULT_PATH&quot; &gt; /dev/null 2&gt;&amp;1; then<br>        echo &quot;Vault address: $VAULT_ADDR&quot;<br>        echo &quot;Secret found at $VAULT_PATH. Fetching secrets.&quot;<br><br>        # Get secret data in JSON format<br>        VAULT_RESPONSE=$(vault kv get -format=json &quot;$VAULT_PATH&quot;)<br><br>        # Export each key-value pair from the Vault response<br>        for key in $(echo &quot;$VAULT_RESPONSE&quot; | jq -r &#39;.data | keys[]&#39;); do<br>          value=$(echo &quot;$VAULT_RESPONSE&quot; | jq -r &quot;.data.$key&quot;)     <br>          echo &quot;Exporting $key&quot;<br>          export &quot;$key=$value&quot;<br>        done<br>      else<br>        echo &quot;VAULT_PATH is not set or secret not found. Skipping secret retrieval.&quot;<br>      fi<br><br>    - |<br>      # If an addon is defined, retrieve and configure kubeconfig from Vault<br>      if [ -n &quot;$CI_K8S_ADDON_NAME&quot; ] || [ &quot;$CI_KUBERNETES_OPERATION&quot; = &quot;True&quot; ]; then<br>        VAULT_PATH=&quot;$VAULT_KV_PATH/$CI_INFRASTRUCTURE_ENVIRONMENT/$CI_INFRASTRUCTURE_COMPONENT/config&quot;<br>        echo &quot;Addon detected. Fetching kubeconfig from: $VAULT_PATH&quot;<br><br>        # Retrieve kubeconfig YAML from Vault<br>        VAULT_RESPONSE_YAML=$(vault kv get -format=yaml &quot;$VAULT_PATH&quot;)<br>        CI_KUBE_CONFIG=$(echo &quot;$VAULT_RESPONSE_YAML&quot; | yq eval &#39;.data.CI_KUBE_CONFIG&#39; -)<br><br>        # Validate kubeconfig presence<br>        if [ -z &quot;$CI_KUBE_CONFIG&quot; ] || [ &quot;$CI_KUBE_CONFIG&quot; = &quot;null&quot; ]; then<br>          echo &quot;❌ CI_KUBE_CONFIG is missing or empty. Exiting.&quot;<br>          exit 1<br>        fi<br><br>        echo &quot;✅ CI_KUBE_CONFIG successfully retrieved.&quot;<br><br>        # Log cluster information<br>        echo &quot;$CI_KUBE_CONFIG&quot; | yq eval &#39;.clusters[] | .cluster.server&#39; -<br><br>        # Write kubeconfig to file with secure permissions<br>        mkdir -p ~/.kube<br>        echo &quot;$CI_KUBE_CONFIG&quot; &gt; ~/.kube/config<br>        chmod 400 ~/.kube/config<br>      else<br>        echo &quot;CI_K8S_ADDON_NAME is not set. Skipping kubeconfig retrieval.&quot;<br>      fi<br><br>  # Load metadata<br>  shared-load-metadata:<br>    - echo &quot;Loading metadata for addon $CI_K8S_ADDON_NAME...&quot;<br>    - CI_K8S_METADATA=$(yq &#39;.&#39; ./ENVIRONMENT/$CI_INFRASTRUCTURE_ENVIRONMENT/$CI_INFRASTRUCTURE_COMPONENT/addons/$CI_K8S_ADDON_NAME/metadata.yml)<br>    <br>  # Loop through metadata and assign variables<br>  shared-assign-metadata:<br>    - echo &quot;Assigning metadata variables...&quot;<br>    - |<br>      for key in $(echo &quot;$CI_K8S_METADATA&quot; | yq &#39;keys&#39; | yq -r &#39;.[]&#39;); do<br>        value=$(echo &quot;$CI_K8S_METADATA&quot; | yq -r &quot;.$key&quot;)<br>        eval &quot;$key=&#39;$value&#39;&quot;<br>      done<br><br>  # Check if namespace exists, and create it if not<br>  shared-create-namespace:<br>    - |<br>      kubectl get namespace &quot;$namespace&quot; &gt;/dev/null 2&gt;&amp;1 || \<br>      kubectl create namespace &quot;$namespace&quot; --dry-run=client -o yaml | kubectl apply -f -<br><br>  # Navigate to the directory containing the addon-specific files based on environment and component<br>  shared-k8s-navigate-addon-dir:<br>    - cd ENVIRONMENT/$CI_INFRASTRUCTURE_ENVIRONMENT/$CI_INFRASTRUCTURE_COMPONENT/addons/$CI_K8S_ADDON_NAME/<br><br>  # Conditionally apply Kubernetes manifests if manifests.yml exists<br>  shared-apply-manifests:<br>    - |<br>      if [ -f &quot;manifests.yml&quot; ]; then<br>        echo &quot;manifests.yml found, applying Kubernetes manifests.&quot;<br>        <br>        # Inject environment variables into the manifests.yml file using envsubst<br>        envsubst &lt; manifests.yml &gt; manifests.processed.yml<br>        <br>        # Apply the processed manifests file<br>        kubectl apply -f manifests.processed.yml<br>      else<br>        echo &quot;manifests.yml not found, skipping kubectl apply.&quot;<br>      fi<br><br>  # Conditionally add the Helm repository, update it, and run the Helm commands if values.yml exists<br>  shared-deploy-helm-charts:<br>    - |<br>      if [ -f &quot;values.yml&quot; ]; then<br>        echo &quot;values.yml found, proceeding with Helm commands.&quot;<br>        <br>        # Inject environment variables into the values.yml file using envsubst<br>        envsubst &lt; values.yml &gt; values.processed.yml<br><br>        # Conditionally use git clone or Helm based on GIT_BASED_INSTALL<br>        if [ -n &quot;$GIT_BASED_INSTALL&quot; ]; then<br>          echo &quot;GIT_BASED_INSTALL is True, using git clone method.&quot;<br><br>          # Clone the repository and deploy using Helm from the local directory<br>          git clone $repository_url -b $release_name<br>          helm upgrade --install $deployment_name $repository_path -f values.processed.yml -n $namespace --create-namespace --wait<br>        <br>        else<br>          echo &quot;GIT_BASED_INSTALL is not set or False, using Helm repository method.&quot;<br>          # Add the Helm repository, update, and install<br>          helm repo add $repository_name $repository_url<br>          helm repo update<br>          helm upgrade --install $deployment_name $repository_name/$chart_name -f values.processed.yml -n $namespace --create-namespace --version $app_version --timeout 20m --wait<br>        fi<br><br>      else<br>        echo &quot;values.yml not found, skipping Helm commands.&quot;<br>      fi<br><br># Common reusable job for deploying Kubernetes addons via Helm and kubectl<br>.common-k8s-addons-deployment:<br>  image: $CI_REGISTRY_HOST/devops/image/helm-kubectl:latest<br>  stage: addons-deploy<br>  script:<br>    # Step 1: Conditionally authenticate with Vault and retrieve the secrets if VAULT_PATH is set<br>    - !reference [.task-library, shared-vault-auth]<br>  <br>    # Step 2: Load the metadata and assign variables dynamically<br>    - !reference [.task-library, shared-load-metadata]<br><br>    # Step 3: Assign metadata variables to environment variables for use in the pipeline<br>    - !reference [.task-library, shared-assign-metadata]<br><br>    # Step 3: Check if the namespace exists, and create it if not<br>    - !reference [.task-library, shared-create-namespace]<br><br>    # Step 4: Navigate to the directory containing the addon-specific files based on environment and component<br>    - !reference [.task-library, shared-k8s-navigate-addon-dir]<br><br>    # Step 5: Conditionally add the Helm repository, update it, and run the Helm commands if values.yml exists<br>    - !reference [.task-library, shared-deploy-helm-charts]<br>    <br>    # Step 6: Conditionally apply Kubernetes manifests if manifests.yml exists<br>    - !reference [.task-library, shared-apply-manifests]<br>  when: manual<br><br>metallb-addons-setup:<br>  extends: .common-k8s-addons-deployment<br>  variables:<br>    CI_K8S_ADDON_NAME: metallb<br>  rules:<br>  <br>    # Rules for DEVOPS-PLATFORM Scope<br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DEVOPS-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ENVIRONMENT == &quot;DEV&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_COMPONENT == &quot;HA-CLUSTER-K8S&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;PROVISION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;DEPLOY&quot;&#39;<br>      when: manual<br>      <br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DEVOPS-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ENVIRONMENT == &quot;PROD&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_COMPONENT == &quot;HA-CLUSTER-K8S&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;PROVISION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;DEPLOY&quot;&#39;<br>      when: manual<br>  <br>  environment:<br>    name: &quot;$CI_INFRASTRUCTURE_SCOPE SCOPE - $CI_INFRASTRUCTURE_ENVIRONMENT ENVIRONMENT&quot;<br>    auto_stop_in: &quot;1 hour&quot;<br>  tags:<br>    - &quot;$CI_RUNNER_TAG&quot;<br><br>keycloak-addons-setup:<br>  extends: .common-k8s-addons-deployment<br>  variables:<br>    CI_K8S_ADDON_NAME: keycloak<br>  rules:<br>      <br>    # Rules for DEVOPS-PLATFORM Scope<br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DEVOPS-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ENVIRONMENT == &quot;DEV&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_COMPONENT == &quot;HA-CLUSTER-K8S&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;PROVISION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;DEPLOY&quot;&#39;<br>      when: manual<br>     <br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DEVOPS-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ENVIRONMENT == &quot;PROD&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_COMPONENT == &quot;HA-CLUSTER-K8S&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;PROVISION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;DEPLOY&quot;&#39;<br>      when: manual<br><br>  environment:<br>    name: &quot;$CI_INFRASTRUCTURE_SCOPE SCOPE - $CI_INFRASTRUCTURE_ENVIRONMENT ENVIRONMENT&quot;<br>    auto_stop_in: &quot;1 hour&quot;<br>  tags:<br>    - &quot;$CI_RUNNER_TAG&quot;</pre><h3>💡 Note</h3><p>In some cases, specific add-ons may require unique deployment logic.<br>When this happens, the behavior of the pipeline can be customized by adding extra script steps or defining different rules for those jobs inside <strong>.gitlab-ci.yml</strong>. This keeps the overall model stable while maintaining flexibility for special scenarios.</p><h3>🧭 <strong>Conclusion</strong></h3><p>This model makes add-on management within the Kubernetes ecosystem <strong>structured</strong>, <strong>auditable</strong>, and <strong>secure</strong>. Each add-on is stored in a unified structure, version-controlled, and managed through the same GitLab pipeline.</p><p>As a result:</p><ul><li>Deployment processes are standardized.</li><li>Cross-environment consistency is maintained.</li><li>Every change is fully auditable.</li><li>Operations become repeatable and independent of manual intervention.</li></ul><p>In essence, this approach implements the <strong>“Add-ons as Code”</strong> principle in a practical and scalable way — extending GitOps automation to Kubernetes add-on management.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5ae2d801a77" width="1" height="1" alt=""><hr><p><a href="https://medium.com/opsuniverse/pipeline-driven-kubernetes-add-ons-deployment-part-2-c5ae2d801a77">Pipeline-Driven Kubernetes — Add-ons Deployment (Part 2)</a> was originally published in <a href="https://medium.com/opsuniverse">OpsUniverse</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pipeline-Driven Kubernetes — Cluster Management (Part 1)]]></title>
            <link>https://medium.com/opsuniverse/pipeline-driven-kubernetes-cluster-management-part-1-02f9b96228ef?source=rss----c13c3d080b5d---4</link>
            <guid isPermaLink="false">https://medium.com/p/02f9b96228ef</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ansible]]></category>
            <dc:creator><![CDATA[Samir Nabadov]]></dc:creator>
            <pubDate>Fri, 03 Oct 2025 12:30:55 GMT</pubDate>
            <atom:updated>2025-10-03T12:46:33.237Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pipeline-Driven Kubernetes — Cluster Management (Part 1)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AlFnULglyHL6MscAU1WiLg.png" /></figure><h3>Introduction: Kubernetes Cluster Setup and Management</h3><p>In our previous articles, we covered <strong>why automation is important, how to properly structure inventories, and how to apply CI/CD pipelines</strong> to infrastructure. You can read them here:</p><p>👉 <a href="https://medium.com/opsuniverse/structuring-inventories-templates-and-pipelines-for-automation-bcff1aeb4000">Structuring Inventories, Templates, and Pipelines for Automation</a><br>👉 <a href="https://medium.com/opsuniverse/automating-vm-provisioning-and-lifecycle-management-c1afd33dbee9">Automating VM Provisioning and Lifecycle Management</a></p><p>In this article, we will focus directly on <strong>setting up and managing Kubernetes clusters</strong>. Our goal is to show how, after VM provisioning, the same philosophy can be extended to Kubernetes to build <strong>a fully automated, pipeline-driven</strong> management model.</p><p>We will specifically cover the following areas:</p><ul><li><strong>Cluster Installation</strong> — automated setup of control-plane and worker nodes</li><li><strong>Upgrades</strong> — step-by-step upgrade process (control-plane, network, nodes)</li><li><strong>Node Scaling</strong> — adding nodes through pipelines when needed</li></ul><p>Finally, we’ll explain our own approach and how we built the CI/CD pipeline architecture to manage these operations end-to-end.</p><h3>Our Approach</h3><p>Traditionally, setting up and managing Kubernetes clusters involves many manual steps: preparing the load balancer, configuring control-plane nodes, adding worker nodes, and carefully handling each stage during an upgrade. These processes are not only time-consuming but also prone to errors. If you manage <strong>multiple environments (DEV, STAGE, PROD) with separate clusters for each</strong>, things get even more complex. In such cases, a manual approach often leads to inefficient use of resources and creates serious risks for infrastructure stability.</p><p>Our approach is built entirely on a <strong>pipeline-driven model</strong>. This means that every operation — whether it’s creating a new cluster, upgrading existing ones, or scaling nodes — is executed through CI/CD pipelines in a fully automated way.</p><p>🔑 The core principle is:</p><ul><li><strong>Every change in the inventory</strong> (adding/removing nodes or updating configurations) is recorded in Git.</li><li><strong>The CI/CD process</strong> automatically detects these changes and prepares the corresponding actions.</li><li>The Engineer only needs t<strong>o manually run the appropriate job</strong> (install, upgrade, add node, etc.).</li><li>As a result, both new and existing <strong>clusters are brought into the desired state automatically</strong>.</li></ul><p>This approach provides us with several key benefits:</p><ul><li><strong>Repeatability</strong> — Every cluster is built using the same steps, ensuring consistency.</li><li><strong>Scalability</strong> — Adding a new node is as simple as updating the inventory file.</li><li><strong>Reliability</strong> — Upgrades are performed step by step in a controlled manner.</li><li><strong>Traceability</strong> — All changes are tracked in Git, making it easy to see who did what and when.</li></ul><p>Our pipelines are structured into four main stages:</p><ul><li><strong>Load Balancer Setup</strong> — Automated deployment of HAProxy and Keepalived (via Ansible).</li><li><strong>Cluster Setup</strong> — Provisioning control-plane and worker nodes with initial configuration (via Kubespray).</li><li><strong>Cluster Upgrade</strong> — Step-by-step upgrade of control-plane and worker nodes (via Kubespray).</li><li><strong>Cluster Scaling</strong> — Adding or removing nodes from the cluster (via Kubespray).</li></ul><h3>Repository Structure</h3><p>The repository is organized as follows:</p><pre>k8s-cluster-provisioning-repository/<br>├── ENVIRONMENT/<br>│   ├── DEV/<br>│   │   └── HA-CLUSTER-K8S/<br>│   │       ├── group_vars/<br>│   │       │   ├── haproxy.yml<br>│   │       │   └── k8s_cluster.yml<br>│   │       └── inventory.yml<br>│   │<br>│   └── PROD/<br>│       └── HA-CLUSTER-K8S/<br>│           ├── group_vars/<br>│           │   ├── haproxy.yml<br>│           │   └── k8s_cluster.yml<br>│           └── inventory.yml<br>│<br>├── scripts/<br>│   ├── k8s-cluster-add-node/<br>│   │   ├── main.py<br>│   │   ├── requirements.txt<br>│   │   └── pipeline_template.j2<br>│<br>└── .gitlab-ci.yml</pre><h3>Cluster Provisioning Flow — End-to-End Process</h3><p>Here’s how the process works, step by step:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OzF5D6PIOLJud8H3buI4fw.png" /></figure><h3>Step 1: YAML Parameters</h3><p>Cluster details (such as load balancer, control-plane and worker node IPs, and resource configurations) are stored in environment-specific YAML files (e.g., DEV, PROD).</p><p>ℹ️ Note: In this example, only cluster-related parameters are shown. VM provisioning details are not included here (they were explained in the previous article). The Ansible role for HAProxy is also not included — this part focuses only on demonstrating the structure.</p><p><strong>./environmet/dev/ha-cluster-k8s/inventory.yml:</strong></p><pre>all:<br>  hosts:<br>    dev-k8s-haproxy01.devops.local.az:<br>      ansible_host: 10.0.0.11<br>    dev-k8s-haproxy02.devops.local.az:<br>      ansible_host: 10.0.0.12<br>    dev-k8s-master01.devops.local.az:<br>      ansible_host: 10.0.0.21<br>      ip: 10.0.0.21<br>      access_ip: 10.0.0.21<br>      taints: []<br>      node_labels: {}<br>    dev-k8s-master02.devops.local.az:<br>      ansible_host: 10.0.0.22<br>      ip: 10.0.0.22<br>      access_ip: 10.0.0.22<br>      taints: []<br>      node_labels: {}<br>    dev-k8s-master03.devops.local.az:<br>      ansible_host: 10.0.0.23<br>      ip: 10.0.0.23<br>      access_ip: 10.0.0.23<br>      taints: []<br>      node_labels: {}<br>    dev-k8s-worker01.devops.local.az:<br>      ansible_host: 10.0.0.24<br>      ip: 10.0.0.24<br>      access_ip: 10.0.0.24<br>      taints: []<br>      node_labels: {}<br>    dev-k8s-worker02.devops.local.az:<br>      ansible_host: 10.0.0.25 <br>      ip: 10.0.0.25 <br>      access_ip: 10.0.0.25 <br>      taints: []<br>      node_labels: {}<br>    dev-k8s-worker03.devops.local.az:<br>      ansible_host: 10.0.0.26<br>      ip: 10.0.0.26<br>      access_ip: 10.0.0.26<br>      taints: []<br>      node_labels: {}<br>  children:<br>    haproxy:<br>      hosts:<br>        dev-k8s-haproxy01.devops.local.az:<br>        dev-k8s-haproxy02.devops.local.az:<br>    kube_control_plane:<br>      hosts:<br>        dev-k8s-master01.devops.local.az:<br>        dev-k8s-master02.devops.local.az:<br>        dev-k8s-master03.devops.local.az:<br>    kube_node:<br>      hosts:<br>        dev-k8s-worker01.devops.local.az:<br>        dev-k8s-worker02.devops.local.az:<br>        dev-k8s-worker03.devops.local.az:<br>    etcd:<br>      hosts:<br>        dev-k8s-master01.devops.local.az:<br>        dev-k8s-master02.devops.local.az:<br>        dev-k8s-master03.devops.local.az:<br>    k8s_cluster:<br>      children:<br>        kube_control_plane:<br>        kube_node:<br>    calico_rr:<br>      hosts: {}</pre><p><strong>./environmet/dev/ha-cluster-k8s/group_vars/haproxy.yml:</strong></p><pre># HAProxy configuration<br>haproxy_k8s_enabled: yes<br>haproxy_version: 3.1<br>haproxy_virtual_ipaddress:<br>  address: 10.0.0.10<br>  k8s_port: 8383<br><br># Keepalived configuration<br>keepalived_keepalived_version: 2.3.2</pre><p><strong>./environmet/dev/ha-cluster-k8s/group_vars/k8s_cluster.yml:</strong></p><pre># Release Configuration<br>release: v2.28.0<br>url: https://github.com/kubernetes-sigs/kubespray.git<br><br># Cluster Configuration<br>cluster_name: cluster.local<br>kube_version: 1.32.5<br><br># Container Manager Configuration<br>container_manager: containerd<br>containerd_version: 2.0.5<br><br># Etcd Configuration<br>etcd_version: 3.5.16<br><br># CoreDNS Configuration<br>coredns_version: 1.11.3<br><br># Networking Configuration<br>kube_network_plugin: calico<br>calico_version: 3.28.1<br>calico_install_crds: true<br><br># Kube Proxy Configuration<br>kube_proxy_mode: ipvs<br>kube_proxy_strict_arp: true<br>kube_proxy_metrics_bind_address: 0.0.0.0:10249<br><br># Certificate Management<br>auto_renew_certificates: true<br><br># API Server Load Balancer<br>apiserver_loadbalancer_domain_name: &quot;dev-k8s-haproxy.devops.local.az&quot;<br>loadbalancer_apiserver:<br>  address: 10.0.0.10<br>  port: 8383<br><br># DNS Search Domains<br>searchdomains:<br>  - local.az<br><br># Helm and Metrics Server<br>helm_enabled: true<br>metrics_server_enabled: true<br>metrics_server_kubelet_insecure_tls: true</pre><h3>Step 2: Ansible Roles</h3><ul><li><strong>haproxy</strong> — Handles load balancer installation and configuration (not detailed here).</li><li><strong>kubespray</strong> — Manages control-plane and worker node provisioning, upgrades, and join operations. During the pipeline run, Kubespray is cloned dynamically instead of being stored statically.</li></ul><h3>Step 3: Python &amp; Jinja2</h3><p>The k8s-cluster-add-node script reads the inventory file and extracts only the k8s_cluster hosts. Using Jinja2 templates (pipeline_template.j2), it generates dynamic child pipelines, creating a dedicated job for each node. This approach is used during node scaling, ensuring new nodes are seamlessly joined to the cluster via Kubespray playbooks.</p><p><strong>./scripts/k8s-cluster-add-nodes/requirements.txt:</strong></p><pre>Jinja2==3.1.2<br>envyaml==1.10.211231</pre><p><strong>./scripts/k8s-cluster-add-nodes/main.py:</strong></p><pre>from jinja2 import Environment, FileSystemLoader<br>from envyaml import EnvYAML<br><br>def load_yaml_config(file_path):<br>    env = EnvYAML(file_path, strict=False)<br>    return env[&#39;all&#39;]<br><br>def setup_jinja_environment():<br>    file_loader = FileSystemLoader(&#39;./&#39;)<br>    return Environment(loader=file_loader)<br><br>def render_template(environment, template_file, context):<br>    template = environment.get_template(template_file)<br>    return template.render(context)<br><br>def write_output_to_file(output, file_path):<br>    with open(file_path, &quot;w&quot;) as file:  # Use &quot;w&quot; instead of &quot;x&quot; to overwrite if the file exists<br>        file.write(output)<br><br>def main():<br>    inventory = load_yaml_config(&#39;HOSTS.yml&#39;)<br>    hosts = inventory[&#39;hosts&#39;]<br>    groups = inventory[&#39;children&#39;]<br><br>    # Extract only k8s_cluster and its children<br>    k8s_cluster = {<br>        &#39;k8s_cluster&#39;: {<br>            &#39;children&#39;: groups[&#39;k8s_cluster&#39;][&#39;children&#39;]<br>        }<br>    }<br><br>    # Add the related hosts to k8s_cluster dictionary<br>    for child in k8s_cluster[&#39;k8s_cluster&#39;][&#39;children&#39;]:<br>        k8s_cluster[&#39;k8s_cluster&#39;][&#39;children&#39;][child] = groups[child]<br><br>    # Filter hosts to include only those in k8s_cluster groups<br>    filtered_hosts = {}<br>    k8s_groups = k8s_cluster[&#39;k8s_cluster&#39;][&#39;children&#39;]<br><br>    for group in k8s_groups:<br>        for host in k8s_groups[group][&#39;hosts&#39;]:<br>            filtered_hosts[host] = hosts[host]<br><br>    jinja_env = setup_jinja_environment()<br><br>    output = render_template(jinja_env, &#39;pipeline_template.j2&#39;, {&#39;hosts&#39;: filtered_hosts, &#39;groups&#39;: k8s_groups})<br><br>    write_output_to_file(output, &#39;child_pipeline_gitlab_ci.yml&#39;)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p><strong>./scripts/k8s-cluster-add-nodes/pipeline_template.j2:</strong></p><pre>stages:<br>  - k8s-node-add<br><br>variables:<br>  ANSIBLE_ROLES_PATH: $CI_PROJECT_DIR/kubespray/roles<br>  ANSIBLE_HOST_KEY_CHECKING: False<br><br>{% for hostname, host in hosts.items() %}<br><br>k8s-add-node-{{ hostname }}:<br>  stage: k8s_node_add<br>  image: $CI_REGISTRY_HOST/devops/image/python:latest<br>  script:    <br>    # Initialize and prepare inventory and variables<br>    - |<br>      RELEASE=$(yq &#39;.release&#39; ./ENVIRONMENT/$CI_INFRASTRUCTURE_ENVIRONMENT/$CI_INFRASTRUCTURE_COMPONENT/group_vars/k8s_cluster.yml)<br>      URL=$(yq &#39;.url&#39; ./ENVIRONMENT/$CI_INFRASTRUCTURE_ENVIRONMENT/$CI_INFRASTRUCTURE_COMPONENT/group_vars/k8s_cluster.yml)<br>    <br>    # Clone kubespray and prepare inventory<br>    - |<br>      git clone $URL -b $RELEASE<br>      yq &#39;.&#39; ./ENVIRONMENT/$CI_INFRASTRUCTURE_ENVIRONMENT/$CI_INFRASTRUCTURE_COMPONENT/group_vars/k8s_cluster.yml &gt; kubespray/vars.yml<br>      yq &#39;.&#39; ./ENVIRONMENT/$CI_INFRASTRUCTURE_ENVIRONMENT/$CI_INFRASTRUCTURE_COMPONENT/inventory.yml &gt; kubespray/inventory.yml &amp;&amp; cd kubespray<br>      pip3 install -r requirements.txt<br><br>    # Run Kubespray playbook<br>    - |<br>      cd $CI_PROJECT_DIR/kubespray<br>      ansible-playbook -i inventory.yml  playbooks/facts.yml --extra-vars &quot;@vars.yml&quot; --extra-vars &quot;ansible_become_pass=$CI_ANSIBLE_PASSWORD ansible_user=$CI_ANSIBLE_USERNAME ansible_password=$CI_ANSIBLE_PASSWORD ansible_user=$CI_ANSIBLE_USERNAME&quot; --become --become-user=root<br>      ansible-playbook cluster.yml -i inventory.yml --extra-vars &quot;@vars.yml&quot; --extra-vars &quot;ansible_become_pass=$CI_ANSIBLE_PASSWORD ansible_user=$CI_ANSIBLE_USERNAME ansible_password=$CI_ANSIBLE_PASSWORD ansible_user=$CI_ANSIBLE_USERNAME&quot; --become --become-user=root -l {{ hostname }}<br>  when: manual<br>  timeout: 5h<br>  tags:<br>    - devops<br><br>{% endfor %}</pre><h3>4. CI/CD Pipeline</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*igxsReQPtp4IFAx8uWvJ-w.png" /></figure><p>The .gitlab-ci.yml file orchestrates the entire process. Any change in the inventory (adding a new node or updating configuration) automatically triggers the relevant jobs. The pipeline is organized into these stages:</p><ul><li><strong>Load Balancer Setup</strong> — Deploy HAProxy and Keepalived (via an Ansible role).</li><li><strong>K8s Cluster Setup</strong> — Full install, full upgrade, or step-by-step upgrades<br><em>(step 1: download → step 2: control plane → step 3: network → step 4: nodes)</em>.</li><li><strong>Cluster Scaling</strong> — Generate dynamic child pipelines (e.g., k8s-add-node) to add new nodes.</li></ul><p><strong>.gitlab-ci.yml:</strong></p><pre>stages:<br>  - setup-loadbalancer<br>  - setup-k8s-cluster<br>  - trigger-k8s-cluster<br><br>variables:<br>  ANSIBLE_ROLES_PATH: $CI_PROJECT_DIR/kubespray/roles<br><br>.task-library:<br>  # Load inventory and cluster-specific variables from environment directory<br>  shared-k8s-prepare-vars-and-inventory:<br>    - |<br>      echo &quot;Preparing inventory and variables...&quot;<br>      yq &#39;.&#39; ./ENVIRONMENT/$CI_INFRASTRUCTURE_ENVIRONMENT/$CI_INFRASTRUCTURE_COMPONENT/inventory.yml &gt; inventory.yml<br>      yq &#39;.&#39; ./ENVIRONMENT/$CI_INFRASTRUCTURE_ENVIRONMENT/$CI_INFRASTRUCTURE_COMPONENT/group_vars/k8s_cluster.yml &gt;&gt; vars.yml<br>      <br>      RELEASE=$(yq &#39;.release&#39; ./ENVIRONMENT/$CI_INFRASTRUCTURE_ENVIRONMENT/$CI_INFRASTRUCTURE_COMPONENT/group_vars/k8s_cluster.yml)<br>      URL=$(yq &#39;.url&#39; ./ENVIRONMENT/$CI_INFRASTRUCTURE_ENVIRONMENT/$CI_INFRASTRUCTURE_COMPONENT/group_vars/k8s_cluster.yml)<br><br>  # Clone Kubespray repo and prepare inventory directory for provisioning<br>  shared-k8s-prepare-kubespray:<br>    - |<br>      echo &quot;Cloning kubespray repo: $URL...&quot;<br>      git clone $URL -b $RELEASE<br><br>      cd kubespray<br>      pip3 install -r requirements.txt<br><br>      cp -rfp inventory/sample inventory/mycluster<br>      cp -r ../inventory.yml inventory/mycluster/inventory.yaml<br>      cp -r ../vars.yml .<br><br>      cd $CI_PROJECT_DIR/kubespray<br><br># Full Cluster Install (Manual Trigger)<br>.k8s-cluster-install:<br>  image: $CI_REGISTRY_HOST/devops/image/python:latest<br>  stage: setup-k8s-cluster<br>  script:<br>    # Step 1: Prepare inventory, vars and extract RELEASE/URL<br>    - !reference [.task-library, shared-k8s-prepare-vars-and-inventory]<br><br>    # Step 2: Clone Kubespray repo and prepare inventory<br>    - !reference [.task-library, shared-k8s-prepare-kubespray]<br><br>    # Step 3: Run Ansible playbook to install the cluster<br>    - |<br>      ansible-playbook cluster.yml \<br>        -i inventory/mycluster/inventory.yaml \<br>        --extra-vars &quot;@vars.yml&quot; \<br>        --extra-vars &quot;ansible_become_pass=$CI_ANSIBLE_PASSWORD ansible_user=$CI_ANSIBLE_USERNAME ansible_password=$CI_ANSIBLE_PASSWORD&quot; \<br>        --become \<br>        --become-user=root<br>  when: manual<br>  timeout: 10h<br><br># Full Cluster Upgrade (Manual Trigger)<br>.k8s-cluster-upgrade-all:<br>  stage: setup-k8s-cluster<br>  image: $CI_REGISTRY_HOST/devops/image/python:latest<br>  script:<br>    # Step 1: Prepare inventory, vars and extract RELEASE/URL<br>    - !reference [.task-library, shared-k8s-prepare-vars-and-inventory]<br><br>    # Step 2: Clone Kubespray repo and prepare inventory<br>    - !reference [.task-library, shared-k8s-prepare-kubespray]<br><br>    # Step 3: Run full cluster upgrade using Kubespray (all components)<br>    - |<br>      ansible-playbook cluster.yml \<br>        -i inventory/mycluster/inventory.yaml \<br>        --extra-vars &quot;@vars.yml&quot; \<br>        --extra-vars &quot;ansible_become_pass=$CI_ANSIBLE_PASSWORD ansible_user=$CI_ANSIBLE_USERNAME ansible_password=$CI_ANSIBLE_PASSWORD&quot; \<br>        --become \<br>        --become-user=root \<br>        -e upgrade_cluster_setup=true<br>  when: manual<br>  timeout: 10h<br><br># Preload Kubernetes container images to all nodes<br>.k8s-upgrade-step-1-download:<br>  stage: setup-k8s-cluster<br>  image: $CI_REGISTRY_HOST/devops/image/python:latest<br><br>  script:<br>    # Step 1: Prepare inventory, vars and extract RELEASE/URL<br>    - !reference [.task-library, shared-k8s-prepare-vars-and-inventory]<br><br>    # Step 2: Clone Kubespray repo and prepare inventory<br>    - !reference [.task-library, shared-k8s-prepare-kubespray]<br><br>    # Step 3: Preload container images using Kubespray (downloads all required images)<br>    - |<br>      ansible-playbook cluster.yml \<br>        -i inventory/mycluster/inventory.yaml \<br>        --extra-vars &quot;@vars.yml&quot; \<br>        --extra-vars &quot;ansible_become_pass=$CI_ANSIBLE_PASSWORD ansible_user=$CI_ANSIBLE_USERNAME ansible_password=$CI_ANSIBLE_PASSWORD&quot; \<br>        --become \<br>        --become-user=root \<br>        --tags=download \<br>        -e upgrade_cluster_setup=true<br>  when: manual<br>  timeout: 10h<br><br># Upgrade etcd, API server, and scheduler on control plane nodes<br>.k8s-upgrade-step-2-control-plane:<br>  stage: setup-k8s-cluster<br>  image: $CI_REGISTRY_HOST/devops/image/python:latest<br><br>  script:<br>    # Step 1: Prepare inventory, vars and extract RELEASE/URL<br>    - !reference [.task-library, shared-k8s-prepare-vars-and-inventory]<br><br>    # Step 2: Clone Kubespray repo and prepare inventory<br>    - !reference [.task-library, shared-k8s-prepare-kubespray]<br><br>    # Step 3: Run Kubespray upgrade playbook for control-plane components<br>    - |<br>      ansible-playbook cluster.yml \<br>        -i inventory/mycluster/inventory.yaml \<br>        --extra-vars &quot;@vars.yml&quot; \<br>        --extra-vars &quot;ansible_become_pass=$CI_ANSIBLE_PASSWORD ansible_user=$CI_ANSIBLE_USERNAME ansible_password=$CI_ANSIBLE_PASSWORD&quot; \<br>        --become \<br>        --become-user=root \<br>        --tags=master,etcd \<br>        -e upgrade_cluster_setup=true<br>  when: manual<br>  timeout: 10h<br><br># Upgrade Calico/CNI, containerd runtime and Kubernetes apps<br>.k8s-upgrade-step-3-network:<br>  stage: setup-k8s-cluster<br>  image: $CI_REGISTRY_HOST/devops/image/python:latest<br><br>  script:<br>    # Step 1: Prepare inventory, vars and extract RELEASE/URL<br>    - !reference [.task-library, shared-k8s-prepare-vars-and-inventory]<br><br>    # Step 2: Clone Kubespray repo and prepare inventory<br>    - !reference [.task-library, shared-k8s-prepare-kubespray]<br><br>    # Step 3: Run Kubespray playbook for CNI, containerd and apps upgrade<br>    - |<br>      ansible-playbook cluster.yml \<br>        -i inventory/mycluster/inventory.yaml \<br>        --extra-vars &quot;@vars.yml&quot; \<br>        --extra-vars &quot;ansible_become_pass=$CI_ANSIBLE_PASSWORD ansible_user=$CI_ANSIBLE_USERNAME ansible_password=$CI_ANSIBLE_PASSWORD&quot; \<br>        --become \<br>        --become-user=root \<br>        --tags=network,containerd,apps,calico,policy-controller \<br>        -e &quot;crio_installed={&#39;matched&#39;: 0}&quot; \<br>        -e upgrade_cluster_setup=true<br>  when: manual<br>  timeout: 10h<br><br># Upgrade kubelet and kube-proxy on all nodes<br>.k8s-upgrade-step-4-nodes:<br>  stage: setup-k8s-cluster<br>  image: $CI_REGISTRY_HOST/devops/image/python:latest<br><br>  script:<br>    # Step 1: Prepare inventory, vars and extract RELEASE/URL<br>    - !reference [.task-library, shared-k8s-prepare-vars-and-inventory]<br><br>    # Step 2: Clone Kubespray repo and prepare inventory<br>    - !reference [.task-library, shared-k8s-prepare-kubespray]<br><br>    # Step 3: Run Kubespray playbook to upgrade kubelet and kube-proxy<br>    - |<br>      ansible-playbook cluster.yml \<br>        -i inventory/mycluster/inventory.yaml \<br>        --extra-vars &quot;@vars.yml&quot; \<br>        --extra-vars &quot;ansible_become_pass=$CI_ANSIBLE_PASSWORD ansible_user=$CI_ANSIBLE_USERNAME ansible_password=$CI_ANSIBLE_PASSWORD&quot; \<br>        --become \<br>        --become-user=root \<br>        --tags=node \<br>        -e upgrade_cluster_setup=true<br>  when: manual<br>  timeout: 10h<br><br>.cluster-add-node:<br>  stage: setup-k8s-cluster<br>  image: $CI_REGISTRY_HOST/devops/image/python:latest<br>  script:<br>    - yq &#39;.&#39; ./ENVIRONMENT/$CI_INFRASTRUCTURE_ENVIRONMENT/$CI_INFRASTRUCTURE_COMPONENT/inventory.yml &gt; HOSTS.yml<br>    - mv HOSTS.yml ./scripts/k8s-cluster-add-nodes/<br>    - cd ./scripts/k8s-cluster-add-nodes/ &amp;&amp; pip3 install -r requirements.txt &amp;&amp; python3 main.py<br>  when: manual<br>  artifacts:<br>    untracked: false<br>    paths:<br>      - ./scripts/k8s-cluster-add-nodes/child_pipeline_gitlab_ci.yml<br>    expire_in: 1 day<br><br>k8s-cluster-install:<br>  extends: .k8s-cluster-install<br>  rules:<br>    # Rules for DEVOPS-PLATFORM Scope<br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DEVOPS-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ENVIRONMENT == &quot;DEV&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_COMPONENT == &quot;HA-CLUSTER-K8S&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;PROVISION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;DEPLOY&quot;&#39;<br>      when: manual<br><br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DEVOPS-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ENVIRONMENT == &quot;PROD&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_COMPONENT == &quot;HA-CLUSTER-K8S&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;PROVISION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;DEPLOY&quot;&#39;<br>      when: manual<br><br>  environment:<br>    name: &quot;$CI_INFRASTRUCTURE_SCOPE SCOPE - $CI_INFRASTRUCTURE_ENVIRONMENT ENVIRONMENT&quot;<br>    auto_stop_in: &quot;1 hour&quot;<br>  tags:<br>    - &quot;devops<br><br>k8s-cluster-upgrade-all:<br>  extends: .k8s-cluster-upgrade-all<br>  rules:<br>    # Rules for DEVOPS-PLATFORM Scope<br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DEVOPS-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ENVIRONMENT == &quot;DEV&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_COMPONENT == &quot;HA-CLUSTER-K8S&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;PROVISION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;DEPLOY&quot;&#39;<br>      when: manual<br><br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DEVOPS-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ENVIRONMENT == &quot;PROD&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_COMPONENT == &quot;HA-CLUSTER-K8S&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;PROVISION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;DEPLOY&quot;&#39;<br>      when: manual<br><br>  environment:<br>    name: &quot;$CI_INFRASTRUCTURE_SCOPE SCOPE - $CI_INFRASTRUCTURE_ENVIRONMENT ENVIRONMENT&quot;<br>    auto_stop_in: &quot;1 hour&quot;<br>  tags:<br>    - &quot;devops<br><br>k8s-upgrade-step-1-download:<br>  extends: .k8s-upgrade-step-1-download<br><br>  rules:<br>    # Rules for DEVOPS-PLATFORM Scope<br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DEVOPS-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ENVIRONMENT == &quot;DEV&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_COMPONENT == &quot;HA-CLUSTER-K8S&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;PROVISION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;DEPLOY&quot;&#39;<br>      when: manual<br><br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DEVOPS-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ENVIRONMENT == &quot;PROD&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_COMPONENT == &quot;HA-CLUSTER-K8S&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;PROVISION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;DEPLOY&quot;&#39;<br>      when: manual<br><br>  environment:<br>    name: &quot;$CI_INFRASTRUCTURE_SCOPE SCOPE - $CI_INFRASTRUCTURE_ENVIRONMENT ENVIRONMENT&quot;<br>    auto_stop_in: &quot;1 hour&quot;<br>  tags:<br>    - &quot;devops<br><br>k8s-upgrade-step-2-control-plane:<br>  extends: .k8s-upgrade-step-2-control-plane<br>  rules:<br>    # Rules for DEVOPS-PLATFORM Scope<br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DEVOPS-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ENVIRONMENT == &quot;DEV&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_COMPONENT == &quot;HA-CLUSTER-K8S&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;PROVISION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;DEPLOY&quot;&#39;<br>      when: manual<br><br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DEVOPS-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ENVIRONMENT == &quot;PROD&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_COMPONENT == &quot;HA-CLUSTER-K8S&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;PROVISION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;DEPLOY&quot;&#39;<br>      when: manual<br><br>  environment:<br>    name: &quot;$CI_INFRASTRUCTURE_SCOPE SCOPE - $CI_INFRASTRUCTURE_ENVIRONMENT ENVIRONMENT&quot;<br>    auto_stop_in: &quot;1 hour&quot;<br>  tags:<br>    - &quot;devops<br><br>k8s-upgrade-step-3-network:<br>  extends: .k8s-upgrade-step-3-network<br>  rules:<br>    # Rules for DEVOPS-PLATFORM Scope<br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DEVOPS-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ENVIRONMENT == &quot;DEV&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_COMPONENT == &quot;HA-CLUSTER-K8S&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;PROVISION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;DEPLOY&quot;&#39;<br>      when: manual<br><br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DEVOPS-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ENVIRONMENT == &quot;PROD&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_COMPONENT == &quot;HA-CLUSTER-K8S&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;PROVISION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;DEPLOY&quot;&#39;<br>      when: manual<br><br>  environment:<br>    name: &quot;$CI_INFRASTRUCTURE_SCOPE SCOPE - $CI_INFRASTRUCTURE_ENVIRONMENT ENVIRONMENT&quot;<br>    auto_stop_in: &quot;1 hour&quot;<br>  tags:<br>    - &quot;devops<br><br>k8s-upgrade-step-4-nodes:<br>  extends: .k8s-upgrade-step-4-nodes<br>  rules:<br>    # Rules for DEVOPS-PLATFORM Scope<br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DEVOPS-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ENVIRONMENT == &quot;DEV&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_COMPONENT == &quot;HA-CLUSTER-K8S&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;PROVISION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;DEPLOY&quot;&#39;<br>      when: manual<br><br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DEVOPS-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ENVIRONMENT == &quot;PROD&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_COMPONENT == &quot;HA-CLUSTER-K8S&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;PROVISION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;DEPLOY&quot;&#39;<br>      when: manual<br><br>  environment:<br>    name: &quot;$CI_INFRASTRUCTURE_SCOPE SCOPE - $CI_INFRASTRUCTURE_ENVIRONMENT ENVIRONMENT&quot;<br>    auto_stop_in: &quot;1 hour&quot;<br>  tags:<br>    - &quot;devops<br><br>k8s-cluster-add-node:<br>  extends: .cluster-add-node<br><br>  rules:<br>    # Rules for DEVOPS-PLATFORM Scope<br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DEVOPS-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ENVIRONMENT == &quot;DEV&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_COMPONENT == &quot;HA-CLUSTER-K8S&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;PROVISION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;DEPLOY&quot;&#39;<br>      when: manual<br><br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DEVOPS-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ENVIRONMENT == &quot;PROD&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_COMPONENT == &quot;HA-CLUSTER-K8S&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;PROVISION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;DEPLOY&quot;&#39;<br>      when: manual<br><br>  environment:<br>    name: &quot;$CI_INFRASTRUCTURE_SCOPE SCOPE - $CI_INFRASTRUCTURE_ENVIRONMENT ENVIRONMENT&quot;<br>    auto_stop_in: &quot;1 hour&quot;<br>  tags:<br>    - devops<br><br>k8s-cluster-add-node-trigger:<br>  stage: trigger-k8s-cluster<br>  variables:<br>    CI_INFRASTRUCTURE_ENVIRONMENT: $CI_INFRASTRUCTURE_ENVIRONMENT<br>    CI_INFRASTRUCTURE_COMPONENT: $CI_INFRASTRUCTURE_COMPONENT<br>  allow_failure: true<br>  rules:<br>    # Rules for DEVOPS-PLATFORM Scope<br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DEVOPS-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ENVIRONMENT == &quot;DEV&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_COMPONENT == &quot;HA-CLUSTER-K8S&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;PROVISION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;DEPLOY&quot;&#39;<br><br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DEVOPS-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ENVIRONMENT == &quot;PROD&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_COMPONENT == &quot;HA-CLUSTER-K8S&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;PROVISION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;DEPLOY&quot;&#39;<br><br>  trigger:<br>    include:<br>      - artifact: ./scripts/k8s-cluster-add-nodes/child_pipeline_gitlab_ci.yml<br>        job: k8s-cluster-add-node<br>    strategy: depend<br><br>  needs:<br>    - k8s-cluster-add-node</pre><h3>Conclusion &amp; Benefits</h3><p>With a pipeline-driven approach, clusters are no longer just technical assets — they become a strategic resource for the organization. The goal is not only to automate infrastructure but also to shape it into a managed, observable, and resilient system.</p><p>This model provides additional advantages:</p><ul><li><strong>Faster response</strong> — adapting to new requirements takes hours instead of days.</li><li><strong>Audit and transparency</strong> — every change is clearly tracked in code.</li><li><strong>Optimized team resources</strong> — repetitive tasks are reduced, allowing teams to focus on development and optimization.</li><li><strong>Reduced risk</strong> — tested pipelines minimize the chance of errors.</li><li><strong>Organizational resilience</strong> — knowledge is embedded into the system, not locked in individuals.</li></ul><p>In short, this approach makes infrastructure management not just an operational task, but an integral part of long-term growth strategy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02f9b96228ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/opsuniverse/pipeline-driven-kubernetes-cluster-management-part-1-02f9b96228ef">Pipeline-Driven Kubernetes — Cluster Management (Part 1)</a> was originally published in <a href="https://medium.com/opsuniverse">OpsUniverse</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating VM Provisioning and Lifecycle Management]]></title>
            <link>https://medium.com/opsuniverse/automating-vm-provisioning-and-lifecycle-management-c1afd33dbee9?source=rss----c13c3d080b5d---4</link>
            <guid isPermaLink="false">https://medium.com/p/c1afd33dbee9</guid>
            <category><![CDATA[gitops]]></category>
            <category><![CDATA[iac]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[Samir Nabadov]]></dc:creator>
            <pubDate>Tue, 30 Sep 2025 06:03:11 GMT</pubDate>
            <atom:updated>2025-09-30T06:22:13.803Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UdnMW0WVGqGriqUrZ7a0vQ.jpeg" /></figure><h3>Introduction: Why Provisioning Management Need Automation</h3><p>In large infrastructures, managing VMs manually (creating, allocating resources, expanding disks, and tracking parameters) often leads to several challenges:</p><ul><li><strong>Time-consuming and error-prone</strong> — Tasks like creating VMs, assigning resources, or expanding disks take too long when done manually. Plus, it’s easy to enter the wrong parameters, which can lead to failures or misconfigurations.</li><li><strong>Unbalanced resource usage</strong> — If CPU and RAM aren’t distributed optimally across ESXi hosts, some become overloaded while others remain underutilized, resulting in poor performance.</li><li><strong>Lack of audit and traceability</strong> — With manual operations, it’s hard to track who made changes and when. This weakens accountability and makes troubleshooting slower.</li><li><strong>Dev/Prod inconsistencies</strong> — Parameters stored in different places for different environments cause confusion and make management harder.</li><li><strong>Slow response to business needs</strong> — Delivering new VMs quickly or adjusting resources on existing ones becomes delayed, making it difficult to meet fast-changing requirements.</li></ul><p>➡️ That’s why automating VM provisioning and lifecycle management with a <strong>GitOps-driven approach</strong> is critical for reliable and efficient infrastructure. While VM provisioning is common in many DevOps environments, our approach stands out: it combines full automation, balanced resource management, and the power of CI/CD pipelines, while also making it easy to extend into future lifecycle operations.</p><h3>Inventory Management: Quick Note</h3><p>In the VM provisioning process, the inventory structure plays a key role, since all parameters are stored there based on the environment and component.</p><p>📖 For a detailed explanation and examples, you can check out my other article:<br>👉 <a href="https://medium.com/opsuniverse/structuring-inventories-templates-and-pipelines-for-automation-bcff1aeb4000?utm_source=chatgpt.com">Structuring Inventories, Templates, and Pipelines for Automation</a></p><p>💡 In this article, we show the provisioning flow for Elasticsearch servers as an example, but the same approach can easily be applied to other components (e.g., MinIO, Kubernetes, or Postgres).</p><h3>Repository Structure</h3><p>The repository is organized as follows:</p><pre>vm-provisioning-repository/<br>├── environment/<br>│   ├── dev/<br>│   │   └── elasticsearch/<br>│   │       ├── group_vars/<br>│   │       │   └── elasticsearch.yml<br>│   │       └── inventory.yml<br>│   └── prod/<br>│       └── elasticsearch/<br>│           ├── group_vars/<br>│           │   └── elasticsearch.yml<br>│           └── inventory.yml<br>│<br>├── deploy/<br>│   ├── ansible.cfg<br>│   ├── main.yml<br>│   └── roles/<br>│       ├── vmprovision/<br>│       │   ├── files/<br>│       │   │   └── expand_root_disk.sh<br>│       │   └── tasks/<br>│       │       ├── main.yml<br>│       │       ├── provision.yml<br>│       │       └── update.yml<br>│       │<br>│       ├── vm_disk_manager/<br>│       │   ├── files/<br>│       │   │   └── expand_root_disk.sh<br>│       │   └── tasks/<br>│       │       └── main.yml<br>│       │<br>│       └── vcenter_scheduler/<br>│           ├── files/<br>│           │   └── sort_datastores.py<br>│           └── tasks/<br>│               └── main.yml<br>│<br>├── scripts/<br>│   ├── templates/<br>│   │   ├── pipeline.j2<br>│   │   └── playbook.j2<br>│   ├── variables/<br>│   │   ├── main-data.j2<br>│   │   └── main-devops.j2<br>│   ├── main.py<br>│   ├── requirements.txt<br>│   └── setup_config_files.py<br>│<br>└── .gitlab-ci.yml</pre><h3>VM Provisioning Flow — End-to-End Process</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yIVSZ0lofFlNKjs00uBeWQ.png" /></figure><p>This is how the full process works:</p><p><strong>YAML Parameters</strong> — All VM details (name, CPU/RAM, disk size, and network settings) are stored in YAML files, organized by environment.</p><p><strong>Python &amp; Jinja2</strong> — YAML files are parsed and dynamic child pipelines are generated. For every host in the inventory, a separate job is created, so provisioning runs in parallel and independently.</p><p><strong>Ansible Roles</strong> –</p><ul><li>vmprovision: Create or update VMs</li><li>vcenter_scheduler: Pick the most optimal ESXi host</li><li>vm_disk_manager: Manage and expand VM disks</li></ul><p><strong>CI/CD Pipeline</strong> — Managed through .gitlab-ci.yml, where every change automatically triggers the provisioning process.</p><h3>1. VM Parameters Management with YAML</h3><p>All VM parameters (name, CPU, RAM, disk size, network, and metadata) are stored in <strong>YAML files</strong>. For each environment, there is a separate inventory.yml and group_vars/elasticsearch.yml.</p><p>🔹 <strong>Note</strong>: For VM provisioning, the group_vars/elasticsearch.yml file is not directly required. It mostly contains tool-specific configuration variables. I’ve included it in the folder structure only to show the overall organization.</p><p><strong>./environmet/dev/elasticsearch/inventory.yml:</strong></p><pre>all:<br>  hosts:<br>    dev-elasticsearch-node01.devops.local.az:<br>      ansible_host: 10.0.1.11<br>      vm_params:<br>        vm_name: &quot;dev-elasticsearch-node01.devops.local.az&quot;<br>        memory_size: &quot;4096&quot;<br>        vcpus: &quot;2&quot;<br>        storage:<br>          root_disk_size: &quot;20&quot;<br>          external_disks:<br>          -  size_gb: 100<br>             unit_number: 1 <br>             disk: sdb <br>             mount_point: /data <br>             name: elastic<br>        network:<br>          vlan: &quot;VLAN 1001&quot;<br>          netmask: &quot;255.255.255.0&quot;<br>          gateway: &quot;10.0.1.1&quot;<br>        metadata:<br>          note: &quot;SD-100001&quot;<br>  children:<br>    postgresql:<br>      hosts:<br>        dev-elasticsearch-node01.devops.local.az:</pre><p><strong>./environmet/prod/elasticsearch/inventory.yml:</strong></p><pre>all:<br>  hosts:<br>    prod-elasticsearch-node01.devops.local.az:<br>      ansible_host: 10.0.2.11<br>      vm_params:<br>        vm_name: &quot;prod-elasticsearch-node01.devops.local.az&quot;<br>        memory_size: &quot;8192&quot;<br>        vcpus: &quot;4&quot;<br>        storage:<br>          root_disk_size: &quot;50&quot;<br>          external_disks:<br>          -  size_gb: 100<br>             unit_number: 1 <br>             disk: sdb <br>             mount_point: /data <br>             name: elastic<br>        network:<br>          vlan: &quot;VLAN 1002&quot;<br>          netmask: &quot;255.255.255.0&quot;<br>          gateway: &quot;10.0.2.1&quot;<br>        metadata:<br>          note: &quot;SD-100002&quot;<br>    prod-elasticsearch-node02.devops.local.az:<br>      ansible_host: 10.0.2.12<br>      vm_params:<br>        vm_name: &quot;prod-elasticsearch-node02.devops.local.az&quot;<br>        memory_size: &quot;8192&quot;<br>        vcpus: &quot;4&quot;<br>        storage:<br>          root_disk_size: &quot;50&quot;<br>          external_disks:<br>          -  size_gb: 100<br>             unit_number: 1 <br>             disk: sdb <br>             mount_point: /data <br>             name: elastic<br>        network:<br>          vlan: &quot;VLAN 1002&quot;<br>          netmask: &quot;255.255.255.0&quot;<br>          gateway: &quot;10.0.2.1&quot;<br>        metadata:<br>          note: &quot;SD-100002&quot;<br>    prod-elasticsearch-node03.devops.local.az:<br>      ansible_host: 10.0.2.13<br>      vm_params:<br>        vm_name: &quot;prod-elasticsearch-node03.devops.local.az&quot;<br>        memory_size: &quot;8192&quot;<br>        vcpus: &quot;4&quot;<br>        storage:<br>          root_disk_size: &quot;50&quot;<br>          external_disks:<br>          -  size_gb: 100<br>             unit_number: 1 <br>             disk: sdb <br>             mount_point: /data <br>             name: elastic<br>        network:<br>          vlan: &quot;VLAN 1002&quot;<br>          netmask: &quot;255.255.255.0&quot;<br>          gateway: &quot;10.0.2.1&quot;<br>        metadata:<br>          note: &quot;SD-100002&quot;<br>  children:<br>    postgresql:<br>      hosts:<br>        prod-elasticsearch-node01.devops.local.az:<br>        prod-elasticsearch-node02.devops.local.az:<br>        prod-elasticsearch-node03.devops.local.az:</pre><h3>2. Python &amp; Jinja2 — Dynamic Pipeline Generation</h3><p>The provisioning process is not handled by Ansible alone — Python scripts and Jinja2 templates also play a key role.<br>The main idea: <strong>for every host in the inventory, a dedicated job and playbook are automatically generated</strong>.</p><ul><li><strong>main.py</strong> → reads the inventory file and processes VM parameters.</li><li><strong>pipeline.j2</strong> → generates a dynamic GitLab child pipeline per host.</li><li><strong>setup_config_files.py</strong> → reads host parameters from the inventory and produces two files via Jinja2 templates:</li><li>variables_hostname.yml → contains all VM parameters for that host.</li><li>main_hostname.yml → Ansible playbook specific to that host.</li><li><strong>playbook.j2</strong> → the base template for all generated playbooks.</li><li><strong>main-devops.j2, </strong><strong>main-data.j2, </strong><strong>dr-devops.j2, </strong><strong>dr-data.j2</strong> → environment (DEV, PROD, DR) and scope (DEVOPS-PLATFORM, DATA-PLATFORM) based variable templates.</li></ul><p>💡 <strong>Outcome:</strong></p><ul><li>If there are 5 hosts in the inventory, the CI/CD pipeline automatically spawns <strong>5 separate jobs</strong>.</li><li>Each job runs with its own variables.yml and main.yml.</li><li>Additionally, setup_config_files.py dynamically assigns the correct roles (vmprovision, vcenter_scheduler, vm_disk_manager) depending on environment, scope, and job type (e.g., <em>vm-provision</em> or <em>disk-provision</em>).</li></ul><p><strong>./scripts/templates/pipeline.j2:</strong></p><pre>stages:<br>  - deploy<br><br>variables:<br>  ANSIBLE_HOST_KEY_CHECKING: &quot;False&quot; <br>  ANSIBLE_COMMAND_WARNINGS: &quot;False&quot;  <br><br># Loop through each host in the inventory to create a job for each<br>{% for hostname, host in hosts.items() %}<br>{{ hostname }}:<br>  stage: deploy  # Define the stage for this job<br>  image: $CI_REGISTRY_HOST/devops/image/ansible:latest  # Use the specified Docker image for Ansible<br>  # Define the script to be executed for each job<br>  script:<br>      # Extract the inventory file and save it to the specified location<br>      - yq &#39;.&#39; $CI_PROJECT_DIR/ENVIRONMENT/$CI_INFRASTRUCTURE_ENVIRONMENT/$CI_INFRASTRUCTURE_COMPONENT/inventory.yml &gt; $CI_PROJECT_DIR/scripts/HOSTS.yml<br>      - yq &#39;.&#39; $CI_PROJECT_DIR/ENVIRONMENT/$CI_INFRASTRUCTURE_ENVIRONMENT/$CI_INFRASTRUCTURE_COMPONENT/inventory.yml &gt; $CI_PROJECT_DIR/deploy/inventory.yml<br><br>      # Navigate to the directory and install the required Python packages<br>      - cd $CI_PROJECT_DIR/scripts/ &amp;&amp; pip3 install -r requirements.txt<br><br>      # Run the Python script to generate the configuration files<br>      - python3 setup_config_files.py<br><br>      # Copy the generated variables and main files to the Ansible directory<br>      - cp -pr variables_{{ hostname }}.yml $CI_PROJECT_DIR/deploy/<br>      - cp -pr main_{{ hostname }}.yml $CI_PROJECT_DIR/deploy/<br><br>      # Navigate to the Ansible directory and Run the Ansible playbook with the specified inventory and extra variables<br>      - cd $CI_PROJECT_DIR/deploy/<br>      - ansible-playbook main_{{ hostname }}.yml --extra-vars &quot;@variables_{{ hostname }}.yml&quot; --extra-vars &quot;ansible_become_pass=$CI_ANSIBLE_PASSWORD ansible_user=$CI_ANSIBLE_USERNAME ansible_password=$CI_ANSIBLE_PASSWORD ansible_user=$CI_ANSIBLE_USERNAME&quot; --become --become-user=root<br>  when: manual<br>  tags:<br>    - devops-runner<br><br>{% endfor %}</pre><p><strong>./scripts/templates/playbook.j2:</strong></p><pre>---<br>- name: Install and Configure Infrastructure Components<br>  hosts: localhost<br>  serial: &quot;{{ sequential_host_limit | default(10) }}&quot;<br>  roles:<br>  {% for role in roles %}<br>    - &quot;{{ role }}&quot;<br>  {% endfor %}</pre><p><strong>./scripts/variables/main-data.j2:</strong></p><pre>vmware_vcenter_username: {{ vmware_vcenter_username }}<br>vmware_vcenter_password: {{ vmware_vcenter_password }}<br>virtual_machine_name: &quot;{{ virtual_machine_name }}&quot;<br>vmware_vcenter_folder: DATA/{{ folder }}<br><br>vmware_vcenter_host: vcenter.data.local.az<br>vmware_vcenter_datacenter: &quot;DATA DC&quot;<br>vmware_vcenter_cluster: &quot;DATA&quot;<br>vmware_vcenter_resource_pool: &quot;DATA&quot;<br>template_base: &quot;Data_Template_Ubuntu22&quot;<br><br>vmware_hosts:<br>    note: {{ note }}<br>    customization:<br>      dns_servers:<br>      - &quot;10.0.0.101&quot;<br>      - &quot;10.0.0.102&quot;<br>      domain: local.az<br>    so_guest: &quot;&quot;<br><br>    vcpus: {{ vcpus }}<br>    memory_size: {{ memory_size }}<br>    root_disk_size: {{ root_disk_size }}<br>    networks:<br>        name: {{ vlan }}<br>        ip: &quot;{{ ip }}&quot;<br>        netmask: &quot;{{ netmask }}&quot;<br>        gateway: &quot;{{ gateway }}&quot;<br><br>esxi_hosts:<br>  - esx01.data.local.az<br>  - esx02.data.local.az<br>  - esx03.data.local.az<br><br>disk_type: &#39;thick&#39; <br>disk_scsi_type: &#39;lsilogic&#39; <br>disk_scsi_controller: 0 <br>disks: {{ external_disks }}<br>filesystem_type: &quot;xfs&quot;<br>main_folder: /data<br>dev_path: &quot;/dev&quot;</pre><p><strong>./scripts/variables/main-devops.j2:</strong></p><pre>vmware_vcenter_username: {{ vmware_vcenter_username }}<br>vmware_vcenter_password: {{ vmware_vcenter_password }}<br>virtual_machine_name: &quot;{{ virtual_machine_name }}&quot;<br>vmware_vcenter_folder: DEVOPS/{{ folder }}<br><br>vmware_vcenter_host: vcenter.devops.local.az<br>vmware_vcenter_datacenter: &quot;DEVOPS DC&quot;<br>vmware_vcenter_cluster: &quot;DEVOPS&quot;<br>vmware_vcenter_resource_pool: &quot;DEVOPS&quot;<br>template_base: &quot;DevOps_Template_Ubuntu22&quot;<br><br>vmware_hosts:<br>    note: {{ note }}<br>    customization:<br>      dns_servers:<br>      - &quot;10.0.0.101&quot;<br>      - &quot;10.0.0.102&quot;<br>      domain: local.az<br>    so_guest: &quot;&quot;<br>    vcpus: {{ vcpus }}<br>    memory_size: {{ memory_size }}<br>    root_disk_size: {{ root_disk_size }}<br>    networks:<br>        name: {{ vlan }}<br>        ip: &quot;{{ ip }}&quot;<br>        netmask: &quot;{{ netmask }}&quot;<br>        gateway: &quot;{{ gateway }}&quot;<br><br>esxi_hosts:<br>  - esx01.devops.local.az<br>  - esx02.devops.local.az<br>  - esx03.devops.local.az<br><br>disk_type: &#39;thick&#39; <br>disk_scsi_type: &#39;lsilogic&#39; <br>disk_scsi_controller: 0 <br>disks: {{ external_disks }}<br>filesystem_type: &quot;xfs&quot;<br>main_folder: /data<br>dev_path: &quot;/dev&quot;</pre><p><strong>./scripts/main.py:</strong></p><pre>from jinja2 import Environment, FileSystemLoader<br>from envyaml import EnvYAML<br><br>def load_yaml_config(file_path):<br>    env = EnvYAML(file_path, strict=False)<br>    return env[&#39;all&#39;]<br><br>def setup_jinja_environment():<br>    file_loader = FileSystemLoader(&#39;./&#39;)<br>    return Environment(loader=file_loader)<br><br>def render_template(environment, template_file, context):<br>    template = environment.get_template(template_file)<br>    return template.render(context)<br><br>def write_output_to_file(output, file_path):<br>    with open(file_path, &quot;x&quot;) as file:<br>        file.write(output)<br><br>def main():<br>    inventory = load_yaml_config(&#39;HOSTS.yml&#39;)<br>    hosts = inventory[&#39;hosts&#39;]<br>    groups = inventory[&#39;children&#39;]<br><br>    jinja_env = setup_jinja_environment()<br><br>    output = render_template(jinja_env, &#39;/templates/pipeline.j2&#39;, {&#39;hosts&#39;: hosts, &#39;groups&#39;: groups})<br><br>    write_output_to_file(output, &#39;child_pipeline_gitlab_ci.yml&#39;)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p><strong>./scripts/requirements.txt:</strong></p><pre>Jinja2==3.1.2<br>envyaml==1.10.211231<br>pyVmomi<br>requests<br>colorama==0.4.6</pre><p><strong>./scripts/setup_config_files.py:</strong></p><pre>from jinja2 import Environment, FileSystemLoader<br>from envyaml import EnvYAML<br>from colorama import Fore, Style<br>import os<br><br>def load_yaml_config(file_path):<br>    # Load the YAML configuration file<br>    env = EnvYAML(file_path, strict=False)<br>    return env[&#39;all&#39;]<br><br>def setup_jinja_environment(jinja_folder):<br>    # Set up the Jinja2 environment to load templates from the &#39;templates&#39; directory<br>    file_loader = FileSystemLoader(f&#39;./{jinja_folder}&#39;)<br>    return Environment(loader=file_loader)<br><br>def render_template(environment, template_file, context):<br>    # Render the Jinja2 template with the given context<br>    template = environment.get_template(template_file)<br>    return template.render(context)<br><br>def write_output_to_file(output, file_path):<br>    # Write the rendered output to a file<br>    with open(file_path, &quot;w&quot;) as file:<br>        file.write(output)<br><br>def configure_environment():<br>    &quot;&quot;&quot;Determine roles and select template based on environment, scope, and job type.&quot;&quot;&quot;<br>    environment = os.getenv(&#39;CI_INFRASTRUCTURE_ENVIRONMENT&#39;)<br>    scope = os.getenv(&#39;CI_INFRASTRUCTURE_SCOPE&#39;)<br>    job_type = os.getenv(&#39;CI_JOB_TYPE&#39;)<br><br>    # Enhanced print statements with color and style<br>    print(f&quot;{Fore.CYAN}{Style.BRIGHT}Configuration Details:{Style.RESET_ALL}&quot;)<br>    print(f&quot;{Fore.GREEN}Scope: {Style.RESET_ALL}{scope}&quot;)<br>    print(f&quot;{Fore.GREEN}Environment: {Style.RESET_ALL}{environment}&quot;)<br>    print(f&quot;{Fore.GREEN}Job Type: {Style.RESET_ALL}{job_type}&quot;)<br>    print(f&quot;{Fore.CYAN}{&#39;=&#39;*40}{Style.RESET_ALL}&quot;)<br><br>    # Determine template based on environment and scope<br>    if environment.startswith(&#39;DR&#39;):<br>        if scope == &#39;DEVOPS-PLATFORM&#39;:<br>            template = &#39;dr-devops.j2&#39;<br>        elif scope == &#39;DATAOPS-PLATFORM&#39;:<br>            template = &#39;dr-data.j2&#39;<br>        else:<br>            raise ValueError(f&quot;Invalid CI_INFRASTRUCTURE_SCOPE for DR environment: {scope}&quot;)<br>    else:<br>        if scope == &#39;DEVOPS-PLATFORM&#39;:<br>            template = &#39;main-devops.j2&#39;<br>        elif scope == &#39;DATA-PLATFORM&#39;:<br>            template = &#39;main-data.j2&#39;<br>        else:<br>            raise ValueError(f&quot;Invalid CI_INFRASTRUCTURE_SCOPE: {scope}&quot;)<br><br>    # Display the selected template<br>    print(f&quot;{Fore.BLUE}Selected Template: {Style.RESET_ALL}{template}&quot;)<br><br>    # Determine roles based on job type<br>    if job_type == &#39;vm-provision&#39;:<br>        roles = [&#39;vcenter_scheduler&#39;, &#39;vmprovision&#39;]<br>    elif job_type == &#39;disk-provision&#39;:<br>        roles = [&#39;vcenter_scheduler&#39;, &#39;vm_disk_manager&#39;, &#39;linux_disk_manager&#39;]<br>    else:<br>        raise ValueError(f&quot;Invalid CI_JOB_TYPE: {job_type}&quot;)<br><br>    # Display assigned roles<br>    print(f&quot;{Fore.BLUE}Assigned Roles: {Style.RESET_ALL}{&#39;, &#39;.join(roles)}&quot;)<br>    print(f&quot;{Fore.CYAN}{&#39;=&#39;*40}{Style.RESET_ALL}&quot;)<br><br>    return roles, template<br><br>def main():<br>    # Load the inventory file<br>    inventory = load_yaml_config(&#39;HOSTS.yml&#39;)<br>    hosts = inventory[&#39;hosts&#39;]<br><br>    # Set up the Jinja2 environment<br>    variables_env = setup_jinja_environment(&#39;variables&#39;)<br>    templates_env = setup_jinja_environment(&#39;templates&#39;)<br><br>    # Get roles and template based on configuration<br>    roles, variables_template = configure_environment()<br><br>    # Generate configuration files for each host<br>    for hostname, host in hosts.items():<br>        if &#39;vm_params&#39; not in host:<br>            raise KeyError(f&quot;&#39;vm_params&#39; key not found in host &#39;{hostname}&#39;&quot;)<br>        <br>        vm_params = host[&#39;vm_params&#39;]<br>        context = {<br>            &#39;vmware_vcenter_username&#39;: os.getenv(&#39;CI_VCENTER_USERNAME&#39;),<br>            &#39;vmware_vcenter_password&#39;: os.getenv(&#39;CI_VCENTER_PASSWORD&#39;),<br>            &#39;virtual_machine_name&#39;: vm_params[&#39;vm_name&#39;],<br>            &#39;folder&#39;: f&quot;{os.getenv(&#39;CI_INFRASTRUCTURE_ENVIRONMENT&#39;)}/{os.getenv(&#39;CI_INFRASTRUCTURE_COMPONENT&#39;)}&quot;,<br>            &#39;ip&#39;: host[&#39;ansible_host&#39;],<br>            &#39;vlan&#39;: vm_params[&#39;network&#39;][&#39;vlan&#39;],<br>            &#39;netmask&#39;: vm_params[&#39;network&#39;][&#39;netmask&#39;],<br>            &#39;gateway&#39;: vm_params[&#39;network&#39;][&#39;gateway&#39;],<br>            &#39;vcpus&#39;: vm_params[&#39;vcpus&#39;],<br>            &#39;memory_size&#39;: vm_params[&#39;memory_size&#39;],<br>            &#39;root_disk_size&#39;: vm_params[&#39;storage&#39;][&#39;root_disk_size&#39;],<br>            &#39;external_disks&#39;: vm_params[&#39;storage&#39;].get(&#39;external_disks&#39;, &#39;&#39;),<br>            &#39;note&#39;: vm_params[&#39;metadata&#39;][&#39;note&#39;],<br>            &#39;roles&#39;: roles<br>        }<br><br>        # Render and write the variables file<br>        variables_output = render_template(variables_env, variables_template, context)<br>        write_output_to_file(variables_output, f&#39;variables_{hostname}.yml&#39;)<br><br>        # Render and write the main playbook file<br>        templates_output = render_template(templates_env, &#39;playbook.j2&#39;, context)<br>        write_output_to_file(templates_output, f&#39;main_{hostname}.yml&#39;)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><h3>3. Ansible Roles — Provisioning Logic</h3><p>In the VM provisioning process, each Ansible role has a specific responsibility. Together, they ensure full automation:</p><ul><li><strong>vmprovision</strong> → Creates new VMs or updates existing ones. This role handles both the initial deployment and resource adjustments (CPU, RAM, etc.). It can also send email notifications so that teams are instantly informed about newly created or updated VMs.</li><li><strong>vcenter_scheduler</strong> → Collects resource data (CPU, RAM, datastore space) from available ESXi hosts and selects the most optimal host/datastore. This guarantees balanced distribution of VMs and helps maintain infrastructure performance.</li><li><strong>vm_disk_manager</strong> → Manages VM disks: adding new external disks, expanding root disks, and applying changes at the filesystem level. At the end of each operation, it can also send email notifications to confirm successful execution.</li></ul><p><strong>./deploy/ansible.cfg:</strong></p><pre>[defaults]<br>remote_user = devops<br>role_path = ./roles<br>host_key_checking = False<br>deprecation_warnings = False<br>command_warnings=False<br>force_valid_group_names = False<br><br>[privilege_escalation]<br>become = True<br>become_method = sudo<br>become_user = root<br>become_ask_pass = True<br>ansible_become_timeout = 30</pre><p><strong>./deploy/main.yml:</strong></p><pre>---<br>- name: Install and Configure Infrastructure Components<br>  hosts: &quot;{{ lookup(&#39;env&#39;, &#39;CI_ANSIBLE_GROUP_NAME&#39;) }}&quot;<br>  serial: &quot;{{ sequential_host_limit | default(20) }}&quot;<br>  tasks:<br>    - name: Include the role dynamically<br>      include_role:<br>        name: &quot;{{ lookup(&#39;env&#39;, &#39;CI_ANSIBLE_ROLE_NAME&#39;) }}&quot;</pre><p><strong>./deploy/roles/vmprovision/files/expand_root_disk.sh:</strong></p><pre>pvresize /dev/sda3<br>lvextend /dev/ubuntu-vg/ubuntu-lv -r -l +100%FREE<br>sgdisk -e /dev/sda<br>partprobe /dev/sda<br>parted -s /dev/sda resizepart 3 100%<br>pvresize /dev/sda3<br>lvextend -r -l +100%FREE /dev/ubuntu-vg/ubuntu-lv</pre><p><strong>./deploy/roles/vmprovision/tasks/main.yml:</strong></p><pre>- name: Gather one specific VM<br>  community.vmware.vmware_vm_info:<br>      hostname: &quot;{{ vmware_vcenter_host }}&quot;<br>      username: &quot;{{ vmware_vcenter_username }}&quot;<br>      password: &quot;{{ vmware_vcenter_password }}&quot;<br>      vm_name: &quot;{{ virtual_machine_name }}&quot;<br>      validate_certs: false<br>  register: vm_info<br>  ignore_errors: true<br><br>- debug:<br>    var: vm_info<br><br>- name: Provision Vm<br>  include: provision.yml<br>  when: vm_info.failed<br>    <br>- name: Provision Vm<br>  include: update.yml<br>  when: vm_info is defined and not vm_info.failed</pre><p><strong>./deploy/roles/vmprovision/tasks/provision.yml:</strong></p><pre>- name: creating a VM Linux at vSphere vCenter<br>  vmware_guest:<br>    hostname: &quot;{{ vmware_vcenter_host }}&quot;<br>    username: &quot;{{ vmware_vcenter_username }}&quot;<br>    password: &quot;{{ vmware_vcenter_password }}&quot;<br>    datacenter: &quot;{{ vmware_vcenter_datacenter }}&quot;<br>    #cluster: &quot;{{ vmware_vcenter_cluster }}&quot;<br>    esxi_hostname: &quot;{{ vmware_vcenter_esxi_hostname }}&quot;<br>    datastore: &quot;{{ vmware_vcenter_datastore }}&quot;<br>    #resource_pool: &quot;{{ vmware_vcenter_resource_pool }}&quot;<br>    name: &quot;{{ virtual_machine_name }}&quot;<br>    folder: &quot;/{{ vmware_vcenter_datacenter }}/vm/{{vmware_vcenter_folder}}&quot;<br>    annotation: &quot;{{ vmware_hosts.note }}&quot;<br>    customization: &quot;{{ vmware_hosts.customization }}&quot;<br>    guest_id: &quot;{{ vmware_hosts.so_guest }}&quot;<br>    state: poweredon<br>    disk:<br>    - size_gb: &quot;{{ vmware_hosts.root_disk_size }}&quot;<br>      type: &quot;thick&quot;<br>    hardware:<br>      hotadd_cpu: true<br>      hotremove_cpu: true  <br>      hotadd_memory: true<br>      memory_mb: &quot;{{ vmware_hosts.memory_size }}&quot;<br>      num_cpus: &quot;{{ vmware_hosts.vcpus }}&quot;<br>    networks:<br>    - name: &quot;{{ vmware_hosts.networks.name }}&quot;<br>      start_connected: True<br>      ip: &quot;{{ vmware_hosts.networks.ip }}&quot;<br>      netmask: &quot;{{ vmware_hosts.networks.netmask }}&quot;<br>      gateway: &quot;{{ vmware_hosts.networks.gateway }}&quot;<br>      device_type: &quot;vmxnet3&quot;<br>      type: &quot;static&quot;<br>    template: &quot;{{ template_base }}&quot;<br>    validate_certs: false<br>    wait_for_ip_address: true<br><br>- name: Check SSH connectivity<br>  wait_for:<br>    host: &quot;{{ vmware_hosts.networks.ip }}&quot;<br>    port: 22<br>    timeout: 20  # Timeout for each connection attempt<br>  delegate_to: localhost<br>  register: result<br>  until: result is succeeded<br>  retries: 10<br>  delay: 10<br><br>- name: sleep for 30 seconds and continue with play<br>  wait_for:<br>    timeout: 30<br>  delegate_to: localhost<br><br>- name: Copy file to remote node<br>  copy:<br>    src: expand_root_disk.sh<br>    dest: /tmp/expand_root_disk.sh<br>  delegate_to: &quot;{{ vmware_hosts.networks.ip }}&quot;<br><br>- name:  execute a script<br>  shell: bash /tmp/expand_root_disk.sh<br>  delegate_to: &quot;{{ vmware_hosts.networks.ip }}&quot;<br><br>- name: Set system hostname<br>  hostname:<br>    name: &quot;{{ inventory_hostname }}&quot;<br><br>- name: Send mail about vm provision<br>  mail:<br>    host: mail.local.az<br>    port: 25  <br>    to: <br>      - devops@local.az<br>      - it@local.az<br>    subject: &#39;Provisioning Successful&#39;<br>    body: |<br>      VM Provisioning Successful!<br>      VM Name: {{ virtual_machine_name }}<br>      IP Address: {{ vmware_hosts.networks.ip }}<br>      VMware Note: {{ vmware_hosts.note }}<br>      CPU: {{ ansible_facts[&#39;processor_cores&#39;] }}<br>      Memory: {{ ansible_facts[&#39;memtotal_mb&#39;] }} MB<br>      Disk: {{ vmware_hosts.root_disk_size }} GB<br>    sender: &#39;devops@local.az&#39;<br>  delegate_to: gitlab.local.az</pre><p><strong>./deploy/roles/vmprovision/tasks/update.yml:</strong></p><pre>- name: Update VM CPU and RAM<br>  community.vmware.vmware_guest:<br>    hostname: &quot;{{ vmware_vcenter_host }}&quot;<br>    username: &quot;{{ vmware_vcenter_username }}&quot;<br>    password: &quot;{{ vmware_vcenter_password }}&quot;<br>    name: &quot;{{ virtual_machine_name }}&quot;<br>    datacenter: &quot;{{ vmware_vcenter_datacenter }}&quot;<br>    validate_certs: false<br>    annotation: &quot;{{ vmware_hosts.note }}&quot;<br>    hardware:<br>      memory_mb: &quot;{{ vmware_hosts.memory_size }}&quot;<br>      num_cpus: &quot;{{ vmware_hosts.vcpus }}&quot;<br>    state: present<br>    <br>- name: Send mail about vm update<br>  mail:<br>    host: mail.local.az<br>    port: 25  <br>    to: <br>      - devops@local.az<br>      - it@local.az<br>    subject: &#39;Vm Update Successful&#39;<br>    body: &gt;<br>      &#39;VM Update Successful!<br>      VM Name: {{ virtual_machine_name }}<br>      VMware Note: {{ vmware_hosts.note }}<br>      CPU: {{ vmware_hosts.vcpus }}<br>      Memory: {{ vmware_hosts.memory_size }} MB<br>    sender: &#39;devops@local.az&#39;<br>  delegate_to: gitlab.local.az</pre><p><strong>./deploy/roles/vm_disk_manager/files/expand_root_disk.sh:</strong></p><pre>echo 1 &gt; /sys/block/sda/device/rescan <br>sgdisk -e /dev/sda<br>partprobe /dev/sda<br>parted -s /dev/sda resizepart 3 100%<br>pvresize /dev/sda3<br>lvextend -r -l +100%FREE /dev/ubuntu-vg/ubuntu-lv</pre><p><strong>./deploy/roles/vm_disk_manager/tasks/main.yml:</strong></p><pre>- name: Determine the type of &#39;disks&#39; variable<br>  set_fact:<br>      disks_type: &quot;{{ disks | type_debug }}&quot;<br><br>- name: Initialize &#39;disks&#39; if undefined<br>  set_fact:<br>    disks_info: []<br>  when: disks_type != &#39;list&#39;<br><br>- name: Initialize &#39;disks&#39; if undefined<br>  set_fact:<br>    disks_info: &quot;{{ disks }}&quot;<br>  when: disks_type == &#39;list&#39;<br><br>- name: Add multiple external disks to VM<br>  community.vmware.vmware_guest_disk:<br>        hostname: &quot;{{ vmware_vcenter_host }}&quot;<br>        username: &quot;{{ vmware_vcenter_username }}&quot;<br>        password: &quot;{{ vmware_vcenter_password }}&quot;<br>        validate_certs: no<br>        datacenter: &quot;{{ vmware_vcenter_datacenter }}&quot;<br>        name: &quot;{{ virtual_machine_name }}&quot;<br>        disk:<br>          - size_gb: &quot;{{ item.size_gb }}&quot;<br>            type: &quot;{{ disk_type }}&quot;<br>            datastore: &quot;{{ vmware_vcenter_datastore }}&quot;<br>            scsi_type: &quot;{{ disk_scsi_type }}&quot;<br>            scsi_controller: &quot;{{ disk_scsi_controller }}&quot;<br>            unit_number: &quot;{{ item.unit_number }}&quot;<br>            state: present<br>  loop: &quot;{{ disks_info }}&quot;<br>  delegate_to: localhost<br>  when: disks_type == &#39;list&#39;<br>  <br>- name: Extend  Root disks to VM<br>  community.vmware.vmware_guest_disk:<br>        hostname: &quot;{{ vmware_vcenter_host }}&quot;<br>        username: &quot;{{ vmware_vcenter_username }}&quot;<br>        password: &quot;{{ vmware_vcenter_password }}&quot;<br>        validate_certs: no<br>        datacenter: &quot;{{ vmware_vcenter_datacenter }}&quot;<br>        name: &quot;{{ virtual_machine_name }}&quot;<br>        disk:<br>          - size_gb: &quot;{{ vmware_hosts.root_disk_size }}&quot;<br>            type: &quot;{{ disk_type }}&quot;<br>            scsi_type: &quot;{{ disk_scsi_type }}&quot;<br>            scsi_controller: &quot;{{ disk_scsi_controller }}&quot;<br>            unit_number: 0<br>            state: present<br><br>### Extend Root disks file system level<br>- name: Extend Root Disk<br>  block:<br>    - name: Copy file to remote node<br>      copy:<br>        src: expand_root_disk.sh<br>        dest: /tmp/expand_root_disk.sh<br><br>    - name:  execute a script<br>      shell: bash /tmp/expand_root_disk.sh &amp;&amp; rm -rf /tmp/expand_root_disk.sh<br>  delegate_to: &quot;{{ vmware_hosts.networks.ip }}&quot;</pre><p><strong>./deploy/roles/vcenter_scheduler/files/sort_datastores.py:</strong></p><pre>import sys<br>import json<br><br>def main():<br>    data = json.load(sys.stdin)<br>    # Convert all sizes to GB for uniformity<br>    for ds in data:<br>        if &#39;TB&#39; in ds[&#39;free&#39;]:<br>            ds[&#39;free&#39;] = float(ds[&#39;free&#39;].replace(&#39;TB&#39;, &#39;&#39;).replace(&#39;,&#39;, &#39;&#39;).strip()) * 1000  # Convert TB to GB<br>        elif &#39;GB&#39; in ds[&#39;free&#39;]:<br>            ds[&#39;free&#39;] = float(ds[&#39;free&#39;].replace(&#39;GB&#39;, &#39;&#39;).replace(&#39;,&#39;, &#39;&#39;).strip())<br><br>    # Sort by &#39;free&#39; space, descending<br>    data_sorted = sorted(data, key=lambda x: x[&#39;free&#39;], reverse=True)<br>    # Print the datastore with the most free space<br>    print(json.dumps(data_sorted[0]))<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p><strong>./deploy/roles/vcenter_scheduler/tasks/main.yml:</strong></p><pre>---<br>- name: Collect Facts from All ESXi Hosts<br>  vmware_host_facts:<br>    hostname: &quot;{{ vmware_vcenter_host }}&quot;<br>    username: &quot;{{ vmware_vcenter_username }}&quot;<br>    password: &quot;{{ vmware_vcenter_password }}&quot;<br>    esxi_hostname: &quot;{{ item }}&quot;<br>    validate_certs: &quot;False&quot;<br>  loop: &quot;{{ esxi_hosts }}&quot;<br>  delegate_to: localhost<br>  register: hosts_data<br><br>- name: Copy the Python script to the local machine<br>  copy:<br>    src: sort_datastores.py<br>    dest: /tmp/sort_datastores.py<br>    mode: &#39;0755&#39;<br>  delegate_to: localhost<br><br>- name: Determine Best Host Based on Most Free Memory<br>  set_fact:<br>    best_host: &quot;{{ hosts_data.results | selectattr(&#39;ansible_facts.ansible_memfree_mb&#39;, &#39;defined&#39;) | sort(attribute=&#39;ansible_facts.ansible_memfree_mb&#39;) | last }}&quot;<br><br>- name: Display Best Host<br>  debug:<br>    msg: &quot;Best Host: {{ best_host.item }} with {{ best_host.ansible_facts.ansible_memfree_mb }} MB Free Memory&quot;<br><br>- name: Determine Best Datastore from the Best Host<br>  set_fact:<br>    all_datastores: &quot;{{ best_host.ansible_facts.ansible_datastore | sort(attribute=&#39;free&#39;, reverse=true) }}&quot;<br><br>- name: Gather datastores fact from remote hosts<br>  # Assuming you have a way to gather your datastore facts<br>  set_fact:<br>    datastores: &quot;{{ best_host.ansible_facts.ansible_datastore | sort(attribute=&#39;free&#39;, reverse=true) }}&quot;<br><br>- name: Sort datastores using local Python script<br>  shell: |<br>    echo &#39;{{ datastores | to_json }}&#39; | python3 /tmp/sort_datastores.py<br>  delegate_to: localhost<br>  register: best_datastore<br><br>- name: Display the best datastore<br>  debug:<br>    msg: &quot;The datastore with the most free space is {{ best_datastore.stdout }}&quot;<br>    <br>- name: Set a fact<br>  set_fact:<br>    vmware_vcenter_datastore: &quot;{{ (best_datastore.stdout  | from_json).name}}&quot;<br>    vmware_vcenter_esxi_hostname: &quot;{{ best_host.item }}&quot;<br><br>- name: Use the persistent fact in another task<br>  debug:<br>    msg:  &quot;The value of vmware_vcenter_datastore: {{ vmware_vcenter_datastore }} vmware_vcenter_esxi_hostname: {{ vmware_vcenter_esxi_hostname }}&quot;</pre><h3>4. CI/CD Pipeline — Automated Execution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_4q0Yj5OgZAV-BSAR46iwQ.png" /></figure><p>The entire process is fully automated through <strong>.gitlab-ci.yml</strong>:</p><ul><li><strong>vm-provision job</strong> → Creates VMs based on parameters defined in YAML.</li><li><strong>disk-provision job</strong> → Handles disk expansion tasks.</li><li><strong>trigger jobs</strong> → Launch child pipelines automatically, ensuring that resources are provisioned in the right environment.</li></ul><p>💡 <strong>Note:</strong> Some variables here are shown as static examples. In real usage, they are pulled dynamically from CI/CD variables. For a detailed explanation and the full structure, check the earlier article I linked above.</p><p><strong>.gitlab-ci.yml:</strong></p><pre>stages:<br>  - maintenance-tasks<br>  - triggering-tasks<br><br><br># Define the variables which will be available for all jobs<br>variables:<br>  ANSIBLE_FORCE_COLOR: &#39;true&#39;<br>  ANSIBLE_TRANSFORM_INVALID_GROUP_CHARS: &quot;ignore&quot;<br>  CI_RUNNER_TAG: &quot;devops-runner&quot;<br>  <br>  CI_INFRASTRUCTURE_SCOPE: &quot;DEVOPS-PLATFORM&quot;<br><br>  CI_INFRASTRUCTURE_ENVIRONMENT: &quot;dev&quot;<br>  CI_INFRASTRUCTURE_COMPONENT: &quot;elasticsearch&quot;<br>  <br>  CI_INFRASTRUCTURE_ACTION: &quot;OPERATION&quot;<br>  CI_INFRASTRUCTURE_PROCEDURE: &quot;VM-SETUP&quot;<br><br>.vm-setup:<br>  stage: maintenance-tasks<br>  image: $CI_REGISTRY_HOST/devops/image/python:latest<br>  script:<br>    # Extract the inventory file and save it to the specified location<br>    - yq &#39;.&#39; $CI_PROJECT_DIR/ENVIRONMENT/$CI_INFRASTRUCTURE_ENVIRONMENT/$CI_INFRASTRUCTURE_COMPONENT/inventory.yml &gt; $CI_PROJECT_DIR/scripts/HOSTS.yml<br>    - yq &#39;.&#39; $CI_PROJECT_DIR/ENVIRONMENT/$CI_INFRASTRUCTURE_ENVIRONMENT/$CI_INFRASTRUCTURE_COMPONENT/inventory.yml &gt; $CI_PROJECT_DIR/deploy/inventory.yml<br><br>    # Navigate to the directory and install the required Python packages<br>    - cd $CI_PROJECT_DIR/scripts/ &amp;&amp; pip3 install -r requirements.txt<br><br>    # Run the Python script to generate the configuration files<br>    - python3 main.py<br>  when: manual<br>  artifacts:<br>    untracked: false<br>    paths:<br>      - scripts/child_pipeline_gitlab_ci.yml<br>    expire_in: 1 hour<br><br>vm-provision:<br>  extends: .vm-setup<br>  rules:<br>    # Rules for DEVOPS-PLATFORM Scope<br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DEVOPS-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;OPERATION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;VM-SETUP&quot;&#39;<br>      when: manual<br><br>    # Rules for DATA-PLATFORM Scope<br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DATA-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;OPERATION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;VM-SETUP&quot;&#39;<br>      when: manual<br>      <br>  environment:<br>    name: &quot;$CI_INFRASTRUCTURE_SCOPE SCOPE - $CI_INFRASTRUCTURE_ENVIRONMENT ENVIRONMENT&quot;<br>    auto_stop_in: &quot;1 hour&quot;<br>  tags:<br>    - &quot;$CI_RUNNER_TAG&quot;<br><br>vm-provision-trigger:<br>  stage: triggering-tasks<br>  trigger:<br>    include:<br>      - artifact: scripts/child_pipeline_gitlab_ci.yml<br>        job: vm-provision<br>    strategy: depend<br>  needs:<br>    - vm-provision<br>  variables:<br>    CI_INFRASTRUCTURE_ENVIRONMENT: $CI_INFRASTRUCTURE_ENVIRONMENT<br>    CI_INFRASTRUCTURE_COMPONENT: $CI_INFRASTRUCTURE_COMPONENT<br>    CI_JOB_TYPE: &quot;vm-provision&quot;<br>  allow_failure: true<br>  rules:<br>    # Rules for DEVOPS-PLATFORM Scope<br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DEVOPS-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;OPERATION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;VM-SETUP&quot;&#39;<br>      variables:<br>        CI_VCENTER_USERNAME: $CI_DEVOPS_VCENTER_USERNAME<br>        CI_VCENTER_PASSWORD: $CI_DEVOPS_VCENTER_PASSWORD<br><br>    # Rules for DATA-PLATFORM Scope<br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DATA-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;OPERATION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;VM-SETUP&quot;&#39;<br>      variables:<br>        CI_VCENTER_USERNAME: $CI_DATA_VCENTER_USERNAME<br>        CI_VCENTER_PASSWORD: $CI_DATA_VCENTER_PASSWORD<br><br># Vm disk provisioning<br>disk-provision:<br>  extends: .vm-setup<br>  rules:<br>    # Rules for DEVOPS-PLATFORM Scope<br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DEVOPS-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;OPERATION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;VM-SETUP&quot;&#39;<br>      when: manual<br><br>    # Rules for DATA-PLATFORM Scope<br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DATA-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;OPERATION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;VM-SETUP&quot;&#39;<br>      when: manual<br>      <br>  environment:<br>    name: &quot;$CI_INFRASTRUCTURE_SCOPE SCOPE - $CI_INFRASTRUCTURE_ENVIRONMENT ENVIRONMENT&quot;<br>    auto_stop_in: &quot;1 hour&quot;<br>  tags:<br>    - &quot;$CI_RUNNER_TAG&quot;<br><br>disk-provision-trigger:<br>  stage: triggering-tasks<br>  trigger:<br>    include:<br>      - artifact: scripts/child_pipeline_gitlab_ci.yml<br>        job: disk-provision<br>    strategy: depend<br>  needs:<br>    - disk-provision<br>  variables:<br>    CI_INFRASTRUCTURE_ENVIRONMENT: $CI_INFRASTRUCTURE_ENVIRONMENT<br>    CI_INFRASTRUCTURE_COMPONENT: $CI_INFRASTRUCTURE_COMPONENT<br>    CI_JOB_TYPE: &quot;disk-provision&quot;<br>  allow_failure: true<br>  rules:<br>    # Rules for DEVOPS-PLATFORM Scope<br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DEVOPS-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;OPERATION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;VM-SETUP&quot;&#39;<br>      variables:<br>        CI_VCENTER_USERNAME: $CI_DEVOPS_VCENTER_USERNAME<br>        CI_VCENTER_PASSWORD: $CI_DEVOPS_VCENTER_PASSWORD<br><br>    # Rules for DATA-PLATFORM Scope<br>    - if: &#39;$CI_INFRASTRUCTURE_SCOPE == &quot;DATA-PLATFORM&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;OPERATION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;VM-SETUP&quot;&#39;<br>      variables:<br>        CI_VCENTER_USERNAME: $CI_DATA_VCENTER_USERNAME<br>        CI_VCENTER_PASSWORD: $CI_DATA_VCENTER_PASSWORD</pre><h3>🔚 Final Thoughts</h3><p>As a result of this approach:</p><ul><li><strong>Automation</strong> — VM creation, resource tuning, and disk management are now fully automated.</li><li><strong>GitOps philosophy</strong> — All changes are managed through Git repositories and applied via CI/CD pipelines.</li><li><strong>Speed and accuracy</strong> — Provisioning is faster and less error-prone compared to manual operations.</li><li><strong>Structured management</strong> — Separate inventories for each environment (DEV, PROD) and component minimize confusion.</li><li><strong>Dynamic pipelines</strong> — Every new node added to the inventory automatically generates a child pipeline and runs as an independent job, making scaling and management much easier.</li></ul><p>💡 Beyond provisioning and disk management, this structure also opens the door for automating many other day-to-day VM operations such as:</p><ul><li>Restarting VMs</li><li>Taking snapshots</li><li>Managing OS updates</li><li>Handling routine administrative tasks</li></ul><p>In other words, the current setup is not just for today’s needs, but also flexible enough to support any future VM lifecycle operations.</p><p>➡️ <strong>Overall, this methodology makes VM provisioning and lifecycle management in large and complex infrastructures more agile, traceable, and reliable.</strong></p><p>🙏 Special thanks to <a href="https://www.linkedin.com/in/elvin-aliyev-5a0772177/">Elvin Əliyev</a> for his big support, especially in building the Ansible roles and shaping the overall flow. His input made the whole process more practical and effective.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1afd33dbee9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/opsuniverse/automating-vm-provisioning-and-lifecycle-management-c1afd33dbee9">Automating VM Provisioning and Lifecycle Management</a> was originally published in <a href="https://medium.com/opsuniverse">OpsUniverse</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Structuring Inventories, Templates, and Pipelines for Automation]]></title>
            <link>https://medium.com/opsuniverse/structuring-inventories-templates-and-pipelines-for-automation-bcff1aeb4000?source=rss----c13c3d080b5d---4</link>
            <guid isPermaLink="false">https://medium.com/p/bcff1aeb4000</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <dc:creator><![CDATA[Samir Nabadov]]></dc:creator>
            <pubDate>Fri, 26 Sep 2025 12:06:55 GMT</pubDate>
            <atom:updated>2025-10-16T20:06:40.682Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*rYQiLo8aYQUA0-9sl_zqcA.jpeg" /></figure><h3>Introduction: Why Structure Matters</h3><p>In large infrastructures, one of the most common problems is <strong>manual server configuration</strong> and <strong>decentralized management</strong>. Often, new servers are set up by <strong>various team members</strong> without proper documentation or inventory. As a result:</p><ul><li>It becomes difficult to find information about a server (IP, host, etc.),</li><li>Nobody knows exactly which services are running or how they are configured,</li><li>Knowledge is lost when team members change.</li></ul><p>Without pipelines and templates:</p><ul><li>Configuration and deployments are done differently in each environment, so there is no standard,</li><li>The same tasks have to be repeated manually, which causes delays and human errors,</li><li>Processes are not traceable, and audit trails are lost after changes,</li><li>Most importantly, differences appear between Dev and Prod environments, leading to confusion and risks.</li></ul><p>In the end, all of these create <strong>operational inefficiency and security risks</strong>.</p><h3>What Happens When Structure Exists?</h3><p>If inventories, templates, and pipelines are stored in Git in a <strong>centralized and standardized</strong> way:</p><ul><li><strong>Server information is always visible</strong> — each VM’s IP, resources, and environment are clear.</li><li><strong>Deployments and configurations can be reused</strong> — templates and playbooks ensure Dev and Prod environments follow the same standards.</li><li><strong>Audit and tracking are guaranteed</strong> — Git history shows who made changes, what was changed, and when.</li><li><strong>Human error is reduced</strong> — instead of manual steps, pipelines handle tasks automatically.</li><li><strong>Security and control improve</strong> — the ESXi structure and Vault integration simplify management and protect sensitive data.</li></ul><h3>Approach: Structured Inventories and Automated Workflows</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GaMkyN2EKUEGtYQSqiNXHw.png" /></figure><h3>Git Repository Structure</h3><p>The first step is to keep all inventories, pipelines, and templates in <strong>separate repositories</strong>. This approach:</p><ul><li><strong>Clarifies responsibilities</strong> — it’s always clear who is committing to which repo.</li><li><strong>Enables reuse</strong> — a pipeline or template can be applied across different components.</li><li><strong>Makes CI/CD integration more transparent</strong> and easier to manage.</li></ul><p><em>Note: The structures shown here use Kafka and Redis as examples, but the same method applies to any other components.</em></p><h3>Inventory Structure</h3><p>The <strong>platform-resources-devops-repository</strong> stores environment-specific inventories and configuration files.</p><ul><li>The repository is organized by <strong>environment</strong> (DEV, PROD, STAGE).</li><li>Each environment contains <strong>components</strong> (Kafka, Redis, etc.), each with its own folder.</li><li>Inside each component folder:</li><li><strong>inventory.yml</strong> — defines hosts and groups.</li><li><strong>group_vars/</strong> — holds configuration variables for that component.</li></ul><p>Example structure:</p><pre>platform-resources-devops-repository/<br>├── ENVIRONMENT/<br>│   ├── DEV/<br>│   │   ├── CLUSTER-KAFKA/<br>│   │   │   ├── group_vars/<br>│   │   │   │   └── kafka.yml<br>│   │   │   └── inventory.yml<br>│   │   ├── CLUSTER-REDIS/<br>│   │   │   ├── group_vars/<br>│   │   │   │   └── redis.yml<br>│   │   │   └── inventory.yml<br>│   │   └── ...   # other components<br>│   │<br>│   ├── PROD/<br>│   │   ├── CLUSTER-KAFKA/<br>│   │   │   ├── group_vars/<br>│   │   │   │   └── kafka.yml<br>│   │   │   └── inventory.yml<br>│   │   ├── CLUSTER-REDIS/<br>│   │   │   ├── group_vars/<br>│   │   │   │   └── redis.yml<br>│   │   │   └── inventory.yml<br>│   │   └── ...   # other components<br>│   │<br>│   └── STAGE/<br>│       └── ...<br>│<br>└── .gitlab-ci.yml</pre><p>This structure ensures:</p><ul><li><strong>Clarity</strong> — you immediately see which hosts and configs belong to which environment.</li><li><strong>Consistency</strong> — DEV, STAGE, and PROD follow the same layout.</li><li><strong>Flexibility</strong> — adding new components only requires creating a new folder with inventory.yml and group_vars.</li></ul><p><strong>./ENVIRONMENT/DEV/CLUSTER-KAFKA/inventory.yml:</strong></p><pre># inventory.yml (DEV / CLUSTER-KAFKA)<br>all:<br>  hosts:<br>    dev-kafka01.devops.local.az:<br>      ansible_host: 10.0.0.11<br>    dev-kafka02.devops.local.az:<br>      ansible_host: 10.0.0.12<br>    dev-kafka03.devops.local.az:<br>      ansible_host: 10.0.0.13<br>  children:<br>    kafka:<br>      hosts:<br>        dev-kafka01.devops.local.az:<br>        dev-kafka02.devops.local.az:<br>        dev-kafka03.devops.local.az:</pre><p><strong>./ENVIRONMENT/DEV/CLUSTER-KAFKA/group_vars/kafka.yml:</strong></p><pre># group_vars/kafka.yml<br># Zookeeper configuration<br>zookeeper_version: 3.8.3<br><br># Kafka configuration<br>kafka_version: 3.5.1<br>kafka_scala_version: 2.13<br>kafka_java_heap: &quot;-Xms1G -Xmx2G&quot;</pre><p><strong>./ENVIRONMENT/DEV/CLUSTER-REDIS/inventory.yml:</strong></p><pre># inventory.yml (DEV / CLUSTER-REDIS)<br>all:<br>  hosts:<br>    dev-redis01.devops.local.az:<br>      ansible_host: 10.0.1.11<br>    dev-redis02.devops.local.az:<br>      ansible_host: 10.0.1.12<br>    dev-redis03.devops.local.az:<br>      ansible_host: 10.0.1.13<br>    dev-redis04.devops.local.az:<br>      ansible_host: 10.0.1.14<br>    dev-redis05.devops.local.az:<br>      ansible_host: 10.0.1.15<br>    dev-redis06.devops.local.az:<br>      ansible_host: 10.0.1.16<br>  children:<br>    kafka:<br>      hosts:<br>        dev-redis01.devops.local.az:<br>        dev-redis02.devops.local.az:<br>        dev-redis03.devops.local.az:<br>        dev-redis04.devops.local.az:<br>        dev-redis05.devops.local.az:<br>        dev-redis06.devops.local.az:</pre><p><strong>./ENVIRONMENT/DEV/CLUSTER-REDIS/group_vars/redis.yml:</strong></p><pre># group_vars/redis.yml<br># Redis configuration<br>redis_version: &quot;6:7.2.1-1rl1~focal1&quot;<br>redis_repository: ppa:redislabs/redis<br>redis_bind_address: &quot;0.0.0.0&quot;<br>redis_protected_mode: &quot;no&quot;<br>redis_node_conf_path: /etc/redis/nodes.conf<br>redis_cluster_enabled: &quot;yes&quot;<br>redis_cluster_config_file: /etc/redis/nodes.conf<br>redis_cluster_node_timeout: 15000<br>redis_appendonly: &quot;yes&quot;<br>redis_appendfsync: everysec<br>redis_save: 3600 1<br>redis_dir: /var/lib/redis<br>redis_logfile: /var/log/redis/redis-server.log<br>redis_supervised: systemd</pre><p><strong>./gitlab-ci.yml:</strong></p><pre>include:<br> - project: devops/automated-infrastructure-provisioning/shared-workflow-pipelines<br>   file: &quot;.gitlab-ci.yaml&quot;  # This will include all YAML files under the PIPELINE directory and its subdirectories<br><br># Define the stages of the pipeline. Jobs will be executed in the order of stages and in parallel for jobs in the same stage<br>stages:<br>  - component-setup<br>  # ...<br><br># Define the variables which will be available for all jobs<br>variables:<br>  ANSIBLE_FORCE_COLOR: &#39;true&#39;<br>  ANSIBLE_TRANSFORM_INVALID_GROUP_CHARS: ignore<br>  CI_INFRASTRUCTURE_ENVIRONMENT:<br>    value: DEV<br>    description: &quot;Select the environment&quot;<br>    options:  # selectable options<br>      - DEV<br>      - PROD<br>      - STAGE<br>      # ...<br>  <br>  CI_INFRASTRUCTURE_COMPONENT:<br>    value: &quot;CLUSTER-KAFKA&quot;<br>    description: &quot;Select the components&quot;<br>    options:<br>      - CLUSTER-KAFKA<br>      - CLUSTER-REDIS<br>      # ...<br>  <br>  CI_INFRASTRUCTURE_ACTION:<br>    value: &quot;PROVISION&quot;<br>    description: &quot;Select the action to be performed on the environment&quot;<br>    options:<br>      - PROVISION<br>      - OPERATION<br>      # ...<br>  <br>  CI_INFRASTRUCTURE_PROCEDURE:<br>    value: &quot;DEPLOY&quot;<br>    description: &quot;Select the action to be performed on the environment&quot;<br>    options:<br>      - DEPLOY<br>      # ...</pre><h3>Template Structure</h3><p>The <strong>shared-workflow-templates-repository</strong> stores reusable Ansible roles and templates. This repository brings together all the automation building blocks in one place.</p><ul><li><strong>roles/</strong> — each component (Kafka, Redis, etc.) has its own dedicated Ansible role.</li><li><strong>main.yml</strong> — the central playbook entry point.</li><li><strong>ansible.cfg</strong> — shared Ansible configuration.</li><li><strong>scripts/</strong> — additional helper scripts for specific components</li></ul><p>Example structure:</p><pre>shared-workflow-templates-repository/<br>├── automation_framework/<br>│   ├── ansible/<br>│   │   ├── roles/<br>│   │   │   ├── kafka/<br>│   │   │   ├── redis/<br>│   │   │   └── ...<br>│   │   ├── ansible.cfg<br>│   │   └── main.yml<br>│   └── scripts/<br>│       └── ...   # scripts for various components</pre><p>This setup ensures:</p><ul><li><strong>Reusability</strong> — the same roles and templates can be applied across different environments.</li><li><strong>Consistency</strong> — common configuration is centralized.</li><li><strong>Extensibility</strong> — new components can easily be added by creating a new role and script.</li></ul><p><strong>./automation_framework/ansible/ansible.cfg:</strong></p><pre>[defaults]<br>remote_user = devops<br>role_path = ./roles<br>host_key_checking = False<br>deprecation_warnings = False<br>command_warnings=False<br>force_valid_group_names = False<br><br>[privilege_escalation]<br>become = True<br>become_method = sudo<br>become_user = root<br>become_ask_pass = True<br>ansible_become_timeout = 30</pre><p><strong>./automation_framework/ansible/main.yml:</strong></p><pre>---<br>- name: Install and Configure Infrastructure Components<br>  hosts: &quot;{{ lookup(&#39;env&#39;, &#39;CI_ANSIBLE_GROUP_NAME&#39;) }}&quot;<br>  serial: &quot;{{ sequential_host_limit | default(20) }}&quot;<br>  tasks:<br>    - name: Include the role dynamically<br>      include_role:<br>        name: &quot;{{ lookup(&#39;env&#39;, &#39;CI_ANSIBLE_ROLE_NAME&#39;) }}&quot;</pre><h3>Pipeline Structure</h3><p>The <strong>shared-workflow-pipelines-repository</strong> is the central hub for all CI/CD pipelines. It is organized into three main layers:</p><ol><li><strong>Infrastructure Setup</strong> — each component (Kafka, Redis, etc.) has its own folder, where deployment and provisioning jobs are defined.</li><li><strong>Shared Resources</strong> — contains common variables, configurations, and reusable tasks (e.g., Vault authentication, post-actions, and Ansible job templates).</li><li><strong>Additional Workflows</strong> — reserved for special or custom processes.</li></ol><p>Example structure:</p><pre>shared-workflow-pipelines-repository/<br>├── workflow-pipeline/<br>│   ├── infrastructure-setup/<br>│   │   ├── cluster-kafka/<br>│   │   │   ├── kafka.yml<br>│   │   │   └── ...<br>│   │   ├── cluster-redis/<br>│   │   │   ├── redis.yml<br>│   │   │   └── ...<br>│   │   └── ...   # other components <br>│   │<br>│   ├── shared-resources/<br>│   │   ├── configs.yml<br>│   │   ├── post-actions.yml<br>│   │   ├── shared-tasks.yml<br>│   │   ├── workflows-common.yml<br>│   │   └── workflow-custom.yml<br>│   │<br>│   └── ...   # additional workflows<br>└── .gitlab-ci.yml</pre><p>This design ensures that:</p><ul><li><strong>Modularity</strong> — each component has its own isolated pipeline logic.</li><li><strong>Reusability</strong> — common tasks and templates are stored once and reused across multiple pipelines.</li><li><strong>Flexibility</strong> — custom workflows can be added without disrupting the standard CI/CD flow.</li></ul><p><strong>./workflow-pipeline/shared-resources/configs.yml:</strong></p><pre>variables:<br>  VAULT_ADDR: https://secretstore.local.az:8200<br>  VAULT_KV_PATH: &quot;devops_kv&quot;<br>  CI_RUNNER_TAG: &quot;devops&quot;<br><br>before_script:<br>  # Clone the repository containing shared pipeline templates<br>  - |<br>      # Disabling SSL verification due to CI environment constraints<br>      git -c http.sslVerify=false clone https://$CI_GITLAB_USERNAME:$CI_GITLAB_PASSWORD@$CI_SERVER_HOST/devops/automated-infrastructure-provisioning/shared-workflow-templates.git <br>      <br>      # Copying the templates to the current working directory<br>      cp -r shared-workflow-templates/automation_framework .</pre><p><strong>./workflow-pipeline/shared-resources/shared-tasks.yml:</strong></p><pre># A collection of reusable tasks for various pipeline operations<br>.task-library:<br><br># Authenticate with Vault and retrieve secrets<br>  shared-vault-auth:<br>    - export VAULT_PATH=&quot;${VAULT_KV_PATH}/${CI_INFRASTRUCTURE_ENVIRONMENT}/${CI_INFRASTRUCTURE_COMPONENT}/credentials-auth&quot;<br>    - |<br>      # Check if VAULT_PATH is set and the secret exists in Vault<br>      if [ -n &quot;$VAULT_PATH&quot; ] &amp;&amp; vault kv get -format=json &quot;$VAULT_PATH&quot; &gt; /dev/null 2&gt;&amp;1; then<br>        echo &quot;Vault address: $VAULT_ADDR&quot;<br>        echo &quot;Secret found at $VAULT_PATH. Fetching secrets.&quot;<br>        # Get secret data in JSON format<br>        VAULT_RESPONSE=$(vault kv get -format=json &quot;$VAULT_PATH&quot;)<br>        # Export each key-value pair from the Vault response<br>        for key in $(echo &quot;$VAULT_RESPONSE&quot; | jq -r &#39;.data | keys[]&#39;); do<br>          value=$(echo &quot;$VAULT_RESPONSE&quot; | jq -r &quot;.data.$key&quot;)     <br>          echo &quot;Exporting $key&quot;<br>          export &quot;$key=$value&quot;<br>        done<br>      else<br>        echo &quot;VAULT_PATH is not set or secret not found. Skipping secret retrieval.&quot;<br>      fi<br>  <br>  # ...</pre><p><strong>./workflow-pipeline/shared-resources/workflow-common.yml:</strong></p><pre># Common reusable job for generic Ansible resource deployments<br>.common-ansible-resource-deployment:<br>  image: $CI_REGISTRY_HOST/devops/image/ansible:latest<br>  script:<br>    # Step 1: Conditionally authenticate with Vault and retrieve the secrets if VAULT_PATH is set<br>    - !reference [.task-library, shared-vault-auth]<br>    <br>    # Step 2: Copy the environment-specific Ansible files into the automation_framework/ansible directory<br>    - mkdir -p ./automation_framework/ansible<br>    - cp -r ./ENVIRONMENT/$CI_INFRASTRUCTURE_ENVIRONMENT/$CI_INFRASTRUCTURE_COMPONENT/* ./automation_framework/ansible<br>    - cd ./automation_framework/ansible<br><br>    # Step 3: Conditionally run the Ansible playbook<br>    - ansible-playbook  main.yml -i inventory.yml --extra-vars &quot;ansible_become_pass=$CI_ANSIBLE_PASSWORD ansible_password=$CI_ANSIBLE_PASSWORD&quot;<br>  when: manual<br><br># ...</pre><p><strong>./workflow-pipeline/infrastructure-setup/cluster-kafka/kafka.yml:</strong></p><pre># Kafka Resource Setup Jobs<br><br>kafka-resource-setup:<br>  stage: component-setup<br>  extends: .common-ansible-resource-deployment<br>  variables:<br>    CI_ANSIBLE_GROUP_NAME: kafka<br>    CI_ANSIBLE_ROLE_NAME: kafka<br>  rules:<br>    <br>    - if: &#39;$CI_INFRASTRUCTURE_ENVIRONMENT == &quot;DEV&quot; &amp;&amp;<br>           $CI_INFRASTRUCTURE_COMPONENT == &quot;CLUSTER-KAFKA&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;PROVISION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;DEPLOY&quot;&#39;<br>      when: manual<br>    <br>    - if: &#39;$CI_INFRASTRUCTURE_ENVIRONMENT == &quot;PROD&quot; &amp;&amp;<br>           $CI_INFRASTRUCTURE_COMPONENT == &quot;CLUSTER-KAFKA&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;PROVISION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;DEPLOY&quot;&#39;<br>      when: manual<br>  <br>  environment:<br>    name: &quot;$CI_INFRASTRUCTURE_SCOPE SCOPE - $CI_INFRASTRUCTURE_ENVIRONMENT ENVIRONMENT&quot;<br>    auto_stop_in: &quot;1 hour&quot;<br>  tags:<br>    - &quot;$CI_RUNNER_TAG&quot;</pre><p><strong>./workflow-pipeline/infrastructure-setup/cluster-redis/redis.yml:</strong></p><pre># Redis Resource Setup Jobs<br><br>redis-resource-setup:<br>  stage: component-setup<br>  extends: .common-ansible-resource-deployment<br>  variables:<br>    CI_ANSIBLE_GROUP_NAME: redis<br>    CI_ANSIBLE_ROLE_NAME: redis<br>  rules:<br>    <br>    - if: &#39;$CI_INFRASTRUCTURE_ENVIRONMENT == &quot;DEV&quot; &amp;&amp;<br>           $CI_INFRASTRUCTURE_COMPONENT == &quot;CLUSTER-REDIS&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;PROVISION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;DEPLOY&quot;&#39;<br>      when: manual<br>    <br>    - if: &#39;$CI_INFRASTRUCTURE_ENVIRONMENT == &quot;PROD&quot; &amp;&amp;<br>           $CI_INFRASTRUCTURE_COMPONENT == &quot;CLUSTER-REDIS&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_ACTION == &quot;PROVISION&quot; &amp;&amp; <br>           $CI_INFRASTRUCTURE_PROCEDURE == &quot;DEPLOY&quot;&#39;<br>      when: manual<br>  <br>  environment:<br>    name: &quot;$CI_INFRASTRUCTURE_SCOPE SCOPE - $CI_INFRASTRUCTURE_ENVIRONMENT ENVIRONMENT&quot;<br>    auto_stop_in: &quot;1 hour&quot;<br>  tags:<br>    - &quot;$CI_RUNNER_TAG&quot;</pre><p><strong>./gitlab-ci.yml:</strong></p><pre>include:<br>   - workflow-pipeline/**/*</pre><h3>vCenter Folder and VMs Structure</h3><p>The inventory and component structure stored in Git is applied in the same way on <strong>vCenter</strong>.</p><p>This approach provides:</p><ul><li><strong>Direct mapping from code to infrastructure</strong> — hosts defined in inventory.yml match the actual VM names in vCenter.</li><li><strong>Simplified audit and management</strong> — environments and components are clearly separated.</li><li><strong>Consistent naming convention</strong> — VM names always include both the environment and component, ensuring uniqueness.</li></ul><p>Example structure:</p><pre>DEVOPS-DC/<br>├── DEV/<br>│   ├── CLUSTER-KAFKA/<br>│   │   ├── dev-kafka01.devops.local.az<br>│   │   ├── dev-kafka02.devops.local.az<br>│   │   └── dev-kafka03.devops.local.az<br>│   │<br>│   ├── CLUSTER-REDIS/<br>│   │   ├── dev-redis01.devops.local.az<br>│   │   ├── dev-redis02.devops.local.az<br>│   │   ├── dev-redis03.devops.local.az<br>│   │   ├── dev-redis04.devops.local.az<br>│   │   ├── dev-redis05.devops.local.az<br>│   │   └── dev-redis06.devops.local.az<br>│   │<br>│   └── ...   # other components (K8s, Minio, Postgres, etc.)<br>│<br>├── PROD/<br>│   ├── CLUSTER-KAFKA/<br>│   │   ├── prod-kafka01.devops.local.az<br>│   │   ├── prod-kafka02.devops.local.az<br>│   │   └── prod-kafka03.devops.local.az<br>│   │<br>│   ├── CLUSTER-REDIS/<br>│   │   ├── prod-redis01.devops.local.az<br>│   │   ├── prod-redis02.devops.local.az<br>│   │   ├── prod-redis03.devops.local.az<br>│   │   ├── prod-redis04.devops.local.az<br>│   │   ├── prod-redis05.devops.local.az<br>│   │   └── prod-redis06.devops.local.az<br>│   │<br>│   └── ...   # other components (K8s, Minio, Postgres, etc.)<br>│<br>└── STAGE/<br>    └── ...   </pre><h3>Quick Overview</h3><ul><li>Each environment (DEV, PROD, STAGE) has its own folder.</li><li>Each component (Kafka, Redis, Postgres, etc.) is stored in a dedicated folder.</li><li>VM names follow a clear pattern based on environment and component, for example:</li><li>dev-redis01.devops.local.az</li><li>prod-kafka02.devops.local.az</li></ul><p>This ensures a direct mapping between <strong>Git inventory.yml</strong> and <strong>vCenter VMs</strong>.</p><h3>Vault Secrets Structure</h3><p>Sensitive data (passwords, usernames, connection URLs, IPs, etc.) is stored in <strong>Vault</strong> and automatically retrieved during deployment.<br>The structure follows a clear hierarchy: <strong>Environment → Component → Secret Type</strong>.</p><p>This approach provides:</p><ul><li><strong>Clarity</strong> — secrets are immediately visible by environment and component.</li><li><strong>Standardization</strong> — the same structure applies across DEV, PROD, and STAGE.</li><li><strong>Security</strong> — each component has its own isolated credentials, preventing overlap.</li></ul><pre>devops_kv/<br>├── DEV/                       <br>│   ├── CLUSTER-KAFKA/         <br>│   │   └── credentials-auth   # Kafka admin user, password, ZooKeeper configs<br>│   ├── CLUSTER-REDIS/<br>│   │   └── credentials-auth   # Redis admin password, IPs<br>│   └── ...                    # other components’ secrets<br>│<br>├── PROD/                      <br>│   ├── CLUSTER-KAFKA/<br>│   │   └── credentials-auth   # Kafka production secrets<br>│   ├── CLUSTER-REDIS/<br>│   │   └── credentials-auth   # Redis production secrets<br>│   └── ...                    # other components’ secrets<br>│<br>└── STAGE/                     <br>    └── ...                    # only required components for testing</pre><h3>Pipeline Usage Flow</h3><h3>Inventory Changes</h3><p>The user updates inventory.yml and group_vars files inside the <strong>platform-resources-devops-repository</strong>. After committing and merging, the changes are applied to the master branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*9pWMNZaF1Vk2TFtOFxX0SA.png" /></figure><h3>Pipeline Trigger and Execution</h3><p>When <strong>“Run Pipeline”</strong> is selected in GitLab, the user is presented with input parameters:</p><ul><li><strong>Environment</strong> → DEV, PROD, STAGE</li><li><strong>Component</strong> → Kafka, Redis və s.</li><li><strong>Action</strong> → PROVISION</li><li><strong>Procedure</strong> → DEPLOY və s.</li></ul><p>Based on the selected parameters, the pipeline runs automatically and performs the following steps:</p><ol><li>Retrieve required secrets from <strong>Vault</strong></li><li>Load Ansible roles and playbooks from the <strong>Templates Repository</strong></li><li>Pull inventory.yml and group_vars from the <strong>Inventory Repository</strong></li><li>Run Ansible jobs on target VMs to execute the deployment</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*vY3BKFqr0XtEDaQxNjLvDA.png" /></figure><h3>Results and Observability</h3><p>This approach is designed for real <strong>production environments</strong> and provides key benefits:</p><ul><li><strong>Fully automated deployment</strong> — manual steps are removed, and only parameter-driven pipelines are executed.</li><li><strong>Audit and observability</strong> — Git commits and merge requests keep a clear change history, GitLab job results show execution status, and Vault logs track secret usage.</li><li><strong>Environment consistency</strong> — the same inventories and templates are reused across DEV → STAGE → PROD, removing version and configuration drift.</li></ul><p>At the same time, every organization’s infrastructure and requirements are unique. The structure described here can be applied directly or adapted to match your own environment.<br><strong>The primary purpose of this approach is to highlight a practical model for centralized and automated management, supporting more consistent and reliable CI/CD workflows.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcff1aeb4000" width="1" height="1" alt=""><hr><p><a href="https://medium.com/opsuniverse/structuring-inventories-templates-and-pipelines-for-automation-bcff1aeb4000">Structuring Inventories, Templates, and Pipelines for Automation</a> was originally published in <a href="https://medium.com/opsuniverse">OpsUniverse</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automated DNS Zone Management with GitOps]]></title>
            <link>https://medium.com/opsuniverse/automated-dns-zone-management-with-gitops-730e3942c437?source=rss----c13c3d080b5d---4</link>
            <guid isPermaLink="false">https://medium.com/p/730e3942c437</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[dns]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[bind]]></category>
            <dc:creator><![CDATA[Samir Nabadov]]></dc:creator>
            <pubDate>Mon, 22 Sep 2025 06:58:26 GMT</pubDate>
            <atom:updated>2025-09-22T06:58:26.539Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction: What Was the Problem?</h3><p>In large infrastructures, DNS zone management plays a critical role. But doing it manually often causes issues such as:</p><ul><li>Human mistakes,</li><li>Weak auditing and tracking capabilities,</li><li>Slower processes,</li><li>Duplicate records,</li><li>Dependence on other people or teams.</li></ul><p>Automating changes directly on the Domain Controller (DC) wasn’t a safe option. That’s why we chose a different path — using BIND9 together with the GitOps approach.</p><h3>Why GitOps?</h3><p>GitOps gave us several key benefits:</p><ul><li><strong>Audit and history</strong> — Every change is stored as a commit in Git.</li><li><strong>Review process</strong> — Changes go through <em>Merge Request → Review → Approval → Deployment</em>.</li><li><strong>Full automation</strong> — Any update in a YAML file is applied automatically through the pipeline.</li><li><strong>Consistency</strong> — Forward and reverse zones are managed in the same, unified way.</li><li><strong>Clean management</strong> — Instead of messy manual edits, records are now structured, organized, and conflict-free. Forgotten or duplicate entries are avoided.</li></ul><h3>Our Technical Approach</h3><p>The overall end-to-end flow: from Git to BIND9 and synchronized to Domain Controllers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y6CxQCojr6c4_LpkudiUeA.png" /></figure><p>The synchronization mechanism: BIND9 acts as master zones, while DCs maintain secondary zones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*VvvzCx-lUDSv70hf--OVsw.png" /></figure><p>After illustrating the overall flow and synchronization, here are the detailed steps of how we applied GitOps to DNS management:</p><ul><li><strong>Zone files in YAML</strong> — All DNS records are stored in YAML format. Each domain has its own file, with records grouped by service type.</li><li><strong>Python script</strong> — Reads the YAML files, validates records, and automatically generates both forward and reverse zones. It also manages named.conf.local and ensures serial numbers are updated correctly.</li><li><strong>Ansible roles</strong> –</li><li><em>bind9-install</em>: handles the initial installation and base configuration of BIND9.</li><li><em>bind9-update-zones</em>: deploys and updates zones generated from YAML files onto the DNS servers.</li><li><strong>CI/CD pipeline</strong> — Using GitLab pipelines, any change in YAML goes through <em>Commit → Merge Request → Review/Approve → Deploy</em>. This ensures every change is tracked and reproducible.</li><li><strong>BIND9 deployment</strong> — Generated zones and configs are applied to target server, syntax checks are run, and the service is safely reloaded.</li><li><strong>Domain Controller sync</strong> — BIND9 acts as the master, while Windows DCs are set as secondary zones. Updates are pushed to DCs via rndc reload.</li></ul><h3>Repository Structure</h3><p>The repository is organized as follows:</p><pre>dns-zone-management-repository/<br>├── zones/<br>│   ├── devops.local.az.yaml<br>│   └── data.local.az.yaml<br>├── deploy/<br>│   ├── ansible.cfg<br>│   ├── inventory.yml<br>│   └── main.yml<br>│   └── roles/<br>│       ├── bind9-install/<br>│       │   ├── defaults/main.yml<br>│       │   ├── handlers/main.yml<br>│       │   ├── tasks/main.yml<br>│       │   └── templates/named.conf.options.j2<br>│       └── bind9-update-zones/<br>│           ├── defaults/main.yml<br>│           ├── handlers/main.yml<br>│           └── tasks/main.yml<br>├── scripts/<br>│   ├── main.py<br>│   └── logger.py<br>└── .gitlab-ci.yml</pre><h3>1. Zone and Record Management with YAML</h3><p>All DNS records are stored in YAML files inside the Git repository. Each domain has its own .yaml file, and records are grouped by service type with comments for clarity.</p><p><strong>./zones/devops.local.az.yaml:</strong></p><pre># devops.local.az<br>records:<br>  # Core DNS servers<br>  - ns1:  10.0.1.10<br>  - ns2:  10.0.1.11<br><br>  # Application servers<br>  - app1-dev.devops.local.az:   10.1.1.101<br>  - app2-prod.devops.local.az:  10.1.1.102<br>  - app3-test.devops.local.az:  10.1.1.103<br>  - app4-stage.devops.local.az: 10.1.1.104<br><br>  # Cache servers<br>  - redis-dev.devops.local.az:   10.1.2.101<br>  - redis-prod.devops.local.az:  10.1.2.102<br><br>  # Database servers<br>  - db1.devops.local.az:  10.1.3.201<br>  - db2.devops.local.az:  10.1.3.202</pre><p><strong>./zones/data.local.az.yaml:</strong></p><pre># data.local.az<br>records:<br>  # Core DNS servers<br>  - ns1:  10.0.1.10<br>  - ns2:  10.0.1.11<br><br>  # API servers<br>  - api-dev.data.local.az:   10.2.1.20<br>  - api-prod.data.local.az:  10.2.1.21<br><br>  # Monitoring tools<br>  - grafana.data.local.az:   10.2.2.30<br>  - prometheus.data.local.az: 10.2.2.31<br><br>  # Security services<br>  - vault.data.local.az:     10.2.3.40<br>  - keycloak.data.local.az:  10.2.3.41<br><br>  # Logging / Observability<br>  - elk.data.local.az:       10.2.4.50<br>  - loki.data.local.az:      10.2.4.51</pre><p>This approach keeps each zone clean, structured, and easy to update. Any change is tracked in Git and can be rolled back if needed.</p><h3>2. Python Script — From YAML to Zone Files</h3><p>The core logic is handled by a Python script, executed through Ansible roles. Its main tasks are:</p><ul><li><strong>YAML parsing</strong> — Reads DNS records from .yaml files (e.g., data.local.az.yaml, devops.local.az.yaml).</li><li><strong>Validation</strong> — Stops if duplicate hostnames or conflicting IPs are found.</li><li><strong>Forward zone generation</strong> — Produces zone files like data.local.az.zone and devops.local.az.zone.</li><li><strong>Reverse zone generation</strong> — Builds corresponding PTR zones such as 1.2.10.in-addr.arpa.zone, 2.2.10.in-addr.arpa.zone, 1.1.10.in-addr.arpa.zone, etc.</li><li><strong>Subnet exclusion</strong> — Skips PTR creation for specific prefixes (e.g., 10.5.1, 10.5.2, 10.5.3, 10.5.4).</li><li><strong>named.conf.local management</strong> — Automatically updates named.conf.local when new zones are detected.</li><li><strong>Serial numbers</strong> — Generated from date + time (YYYYMMDDHHMM).</li><li><strong>Allow-transfer</strong> — Grants zone transfer rights to secondary DNS servers (e.g., 10.0.1.10, 10.0.1.11).</li></ul><p><strong>./scripts/logger.py:</strong></p><pre>import logging<br>import sys<br>from colorama import Fore, Style, init<br><br>init(autoreset=True, strip=False, convert=False, wrap=True)<br><br>class ColorFormatter(logging.Formatter):<br>    LEVEL_COLORS = {<br>        logging.DEBUG: Fore.CYAN,<br>        logging.INFO: Fore.GREEN,<br>        logging.WARNING: Fore.YELLOW,<br>        logging.ERROR: Fore.RED,<br>        logging.CRITICAL: Fore.RED + Style.BRIGHT,<br>    }<br><br>    def format(self, record):<br>        level_color = self.LEVEL_COLORS.get(record.levelno, &quot;&quot;)<br>        reset = Style.RESET_ALL<br>        record.levelname = f&quot;{level_color}{record.levelname}{reset}&quot;<br>        return super().format(record)<br><br>def setup_logging():<br>    handler = logging.StreamHandler(sys.stdout)<br>    handler.setFormatter(<br>        ColorFormatter(<br>            fmt=&quot;%(asctime)s [%(levelname)s] %(message)s&quot;,<br>            datefmt=&quot;%Y-%m-%d %H:%M:%S&quot;<br>        )<br>    )<br><br>    root = logging.getLogger()<br>    root.setLevel(logging.INFO)<br>    root.handlers = []  # prevent duplicate logs<br>    root.addHandler(handler)<br><br>    # disable noisy loggers<br>    logging.getLogger(&quot;urllib3&quot;).setLevel(logging.WARNING)<br>    logging.getLogger(&quot;requests&quot;).setLevel(logging.WARNING)<br>    logging.getLogger(&quot;hvac&quot;).setLevel(logging.WARNING)<br><br># Wrapper helpers<br>def info(action: str, message: str):<br>    logging.info(f&quot;{action} → {Fore.GREEN}{message}{Style.RESET_ALL}&quot;)<br><br>def warn(action: str, message: str):<br>    logging.warning(f&quot;{action} → {Fore.YELLOW}{message}{Style.RESET_ALL}&quot;)<br><br>def error(action: str, message: str):<br>    logging.error(f&quot;{action} → {Fore.RED}{message}{Style.RESET_ALL}&quot;)<br><br>def debug(action: str, message: str):<br>    logging.debug(f&quot;{action} → {Fore.CYAN}{message}{Style.RESET_ALL}&quot;)</pre><p><strong>./scripts/main.py:</strong></p><pre>#!/usr/bin/env python3<br>import yaml<br>import os<br>from collections import defaultdict<br>from datetime import datetime<br>from logger import setup_logging, info, warn, error<br><br># Set up logging<br>setup_logging()<br><br># Excluded PTR subnets<br>EXCLUDED_PTR_SUBNETS = {<br>    &quot;10.5.1&quot;,<br>    &quot;10.5.2&quot;,<br>    &quot;10.5.3&quot;,<br>    &quot;10.5.4&quot;<br>}<br><br># Extra DNS servers for allow-transfer<br>EXTRA_DNS = [&quot;10.0.1.10&quot;, &quot;10.0.1.11&quot;]<br><br># Serial number (date-time based)<br>SERIAL = datetime.now().strftime(&quot;%Y%m%d%H%M&quot;)<br><br># Named conf path<br>NAMED_CONF = &quot;named.conf.local&quot;<br><br>def normalize_host(host, domain):<br>    if host == &quot;@&quot;:<br>        return domain<br>    if host.endswith(f&quot;.{domain}&quot;):<br>        return host<br>    if &quot;.&quot; in host:<br>        return host<br>    return f&quot;{host}.{domain}&quot;<br><br>def owner_for_zone(host, domain):<br>    if host == &quot;@&quot;:<br>        return &quot;@&quot;<br>    suffix = f&quot;.{domain}&quot;<br>    if host.endswith(suffix):<br>        left = host[:-len(suffix)]<br>        if left.endswith(&quot;.&quot;):<br>            left = left[:-1]<br>        return left or &quot;@&quot;<br>    if &quot;.&quot; in host:<br>        return None<br>    return host<br><br>def validate_records(records, domain):<br>    seen_hosts = {}<br>    for entry in records:<br>        for host, ip in entry.items():<br>            fqdn = normalize_host(host, domain)<br>            if fqdn in seen_hosts:<br>                if seen_hosts[fqdn] == ip:<br>                    error(&quot;validate&quot;, f&quot;Duplicate record found: {fqdn} → {ip}&quot;)<br>                    raise SystemExit(1)<br>                else:<br>                    error(&quot;validate&quot;, f&quot;Host {fqdn} already mapped to {seen_hosts[fqdn]}, cannot map to {ip}&quot;)<br>                    raise SystemExit(1)<br>            seen_hosts[fqdn] = ip<br>    info(&quot;validate&quot;, f&quot;✓ Records validated for {domain}&quot;)<br><br>def parse_records(domain, records):<br>    a_records = []<br>    subnets = defaultdict(list)<br>    for entry in records:<br>        for host, ip in entry.items():<br>            fqdn = normalize_host(host, domain)<br>            is_dvpdtp = fqdn.endswith(&quot;.devops.local.az&quot;) or fqdn.endswith(&quot;.data.local.az&quot;)<br>            is_local = fqdn.endswith(&quot;.local.az&quot;)<br>            create_forward = is_dvpdtp<br>            create_reverse = is_local<br><br>            if create_forward:<br>                owner = owner_for_zone(host, domain)<br>                if owner is not None:<br>                    a_records.append(f&quot;{owner} IN A {ip}&quot;)<br><br>            if create_reverse and ip != &quot;0.0.0.0&quot;:<br>                if host.lower().startswith(&quot;ns&quot;) or host == &quot;@&quot;:<br>                    continue<br>                parts = ip.split(&quot;.&quot;)<br>                if len(parts) == 4 and all(p.isdigit() and 0 &lt;= int(p) &lt;= 255 for p in parts):<br>                    subnet = &quot;.&quot;.join(parts[0:3])<br>                    if subnet in EXCLUDED_PTR_SUBNETS:<br>                        warn(&quot;parse&quot;, f&quot;Skipping PTR for {fqdn} in excluded subnet {subnet}&quot;)<br>                        continue<br>                    last_octet = parts[3]<br>                    subnets[subnet].append(f&quot;{last_octet} IN PTR {fqdn}.&quot;)<br>                else:<br>                    warn(&quot;parse&quot;, f&quot;Skipping invalid IPv4: {ip} for {host}&quot;)<br>    return a_records, subnets<br><br>def ensure_named_conf_exists():<br>    if not os.path.exists(NAMED_CONF):<br>        with open(NAMED_CONF, &quot;w&quot;) as f:<br>            f.write(&quot;// Auto-generated named.conf.local\n&quot;)<br>            f.write(&quot;// Zones appended by script\n\n&quot;)<br>        info(&quot;named.conf.init&quot;, f&quot;Created {NAMED_CONF}&quot;)<br><br>def ensure_zone_in_namedconf(zone_name, file_path, domain=None, first_zone=False):<br>    ensure_named_conf_exists()<br>    with open(NAMED_CONF) as f:<br>        content = f.read()<br>    if zone_name in content:<br>        info(&quot;named.conf.skip&quot;, f&quot;{zone_name} already present&quot;)<br>        return False<br><br>    stanza = &quot;&quot;<br>    if domain and first_zone:<br>        stanza += f&quot;\n// =======================\n&quot;<br>        stanza += f&quot;// {domain} ZONES\n&quot;<br>        stanza += f&quot;// =======================\n\n&quot;<br><br>    # join extra dns with semicolons<br>    extra_dns = &quot; &quot;.join([ip + &quot;;&quot; for ip in EXTRA_DNS])<br><br>    stanza += f&quot;&quot;&quot;zone &quot;{zone_name}&quot; {{<br>    type master;<br>    file &quot;{file_path}&quot;;<br>    allow-transfer {{ {extra_dns} }};<br>    notify yes;<br>}};<br>&quot;&quot;&quot;<br>    with open(NAMED_CONF, &quot;a&quot;) as f:<br>        f.write(stanza)<br>    info(&quot;named.conf.add&quot;, f&quot;Added zone {zone_name}&quot;)<br>    return True<br><br>def process_yaml(yaml_file):<br>    if not os.path.exists(yaml_file):<br>        error(&quot;main&quot;, f&quot;{yaml_file} not found&quot;)<br>        return<br><br>    with open(yaml_file) as f:<br>        data = yaml.safe_load(f)<br><br>    domain = None<br>    for line in open(yaml_file):<br>        if line.strip().startswith(&quot;#&quot;):<br>            domain = line.strip(&quot;# &quot;).strip()<br>            break<br>    if not domain:<br>        error(&quot;main&quot;, f&quot;Domain not found in {yaml_file}&quot;)<br>        return<br><br>    info(&quot;domain.start&quot;, f&quot;====================================&quot;)<br>    info(&quot;domain.start&quot;, f&quot;==== Processing {domain} ====&quot;)<br>    info(&quot;domain.start&quot;, f&quot;====================================&quot;)<br><br>    records = data.get(&quot;records&quot;, [])<br>    validate_records(records, domain)<br>    a_records, subnets = parse_records(domain, records)<br><br>    zone_dir = f&quot;{domain}&quot;<br>    if not os.path.exists(zone_dir):<br>        os.makedirs(zone_dir, exist_ok=True)<br>        info(&quot;dir.create&quot;, f&quot;Created {zone_dir}/&quot;)<br><br>    if a_records:<br>        real_file = f&quot;{zone_dir}/{domain}.zone&quot;<br>        bind_file = f&quot;/etc/bind/zones/{domain}/{domain}.zone&quot;<br>        with open(real_file, &quot;w&quot;) as f:<br>            f.write(<br>                f&quot;&quot;&quot;$TTL 3600<br>@ IN SOA ns1.{domain}. admin.{domain}. (<br>        {SERIAL}   ; Serial (YYYYMMDDHHMM)<br>        3600       ; Refresh (1 hour)<br>        900        ; Retry (15 minutes)<br>        604800     ; Expire (1 week)<br>        86400      ; Minimum TTL<br>)<br><br>; Name servers<br>@ IN NS ns1.{domain}.<br><br>; Host records<br>&quot;&quot;&quot;<br>            )<br>            for record in a_records:<br>                f.write(record + &quot;\n&quot;)<br>        info(&quot;forward.write&quot;, f&quot;{real_file}&quot;)<br>        ensure_zone_in_namedconf(domain, bind_file, domain=domain, first_zone=True)<br>    else:<br>        info(&quot;forward.skip&quot;, f&quot;Skipping forward zone for {domain} (no A records)&quot;)<br><br>    for subnet, ptr_records in sorted(subnets.items()):<br>        rev_name = &quot;.&quot;.join(reversed(subnet.split(&quot;.&quot;))) + &quot;.in-addr.arpa&quot;<br>        real_file = f&quot;{zone_dir}/{rev_name}.zone&quot;<br>        bind_file = f&quot;/etc/bind/zones/{domain}/{rev_name}.zone&quot;<br>        with open(real_file, &quot;w&quot;) as f:<br>            f.write(<br>                f&quot;&quot;&quot;$TTL 3600<br>@ IN SOA ns1.{domain}. admin.{domain}. (<br>        {SERIAL}   ; Serial (YYYYMMDDHHMM)<br>        3600       ; Refresh (1 hour)<br>        900        ; Retry (15 minutes)<br>        604800     ; Expire (1 week)<br>        86400      ; Minimum TTL<br>)<br><br>; Name servers<br>@ IN NS ns1.{domain}.<br><br>; PTR records<br>&quot;&quot;&quot;<br>            )<br>            for record in ptr_records:<br>                f.write(record + &quot;\n&quot;)<br>        info(&quot;reverse.write&quot;, f&quot;{real_file}&quot;)<br>        ensure_zone_in_namedconf(rev_name, bind_file, domain=domain)<br><br>    info(&quot;domain.done&quot;, f&quot;✓ Finished {domain}&quot;)<br><br>def main():<br>    yaml_files = [<br>        &quot;devops.local.az.yaml&quot;,<br>        &quot;data.local.az.yaml&quot;,<br>    ]<br>    for y in yaml_files:<br>        process_yaml(y)<br><br>if __name__ == &quot;__main__&quot;:<br>    main()</pre><p>Sample run output:</p><pre>2025-09-18 23:26:07 [INFO] domain.start → ====================================<br>2025-09-18 23:26:07 [INFO] domain.start → ==== Processing devops.local.az ====<br>2025-09-18 23:26:07 [INFO] domain.start → ====================================<br>2025-09-18 23:26:07 [INFO] validate → ✓ Records validated for devops.local.az<br>2025-09-18 23:26:07 [INFO] dir.create → Created devops.local.az/<br>2025-09-18 23:26:07 [INFO] forward.write → devops.local.az/devops.local.az.zone<br>2025-09-18 23:26:07 [INFO] named.conf.init → Created named.conf.local<br>2025-09-18 23:26:07 [INFO] named.conf.add → Added zone devops.local.az<br>2025-09-18 23:26:07 [INFO] reverse.write → devops.local.az/1.1.10.in-addr.arpa.zone<br>2025-09-18 23:26:07 [INFO] named.conf.add → Added zone 1.1.10.in-addr.arpa<br>2025-09-18 23:26:07 [INFO] reverse.write → devops.local.az/2.1.10.in-addr.arpa.zone<br>2025-09-18 23:26:07 [INFO] named.conf.add → Added zone 2.1.10.in-addr.arpa<br>2025-09-18 23:26:07 [INFO] reverse.write → devops.local.az/3.1.10.in-addr.arpa.zone<br>2025-09-18 23:26:07 [INFO] named.conf.add → Added zone 3.1.10.in-addr.arpa<br>2025-09-18 23:26:07 [INFO] domain.done → ✓ Finished devops.local.az<br>2025-09-18 23:26:07 [INFO] domain.start → ====================================<br>2025-09-18 23:26:07 [INFO] domain.start → ==== Processing data.local.az ====<br>2025-09-18 23:26:07 [INFO] domain.start → ====================================<br>2025-09-18 23:26:07 [INFO] validate → ✓ Records validated for data.local.az<br>2025-09-18 23:26:07 [INFO] dir.create → Created data.local.az/<br>2025-09-18 23:26:07 [INFO] forward.write → data.local.az/data.local.az.zone<br>2025-09-18 23:26:07 [INFO] named.conf.add → Added zone data.local.az<br>2025-09-18 23:26:07 [INFO] reverse.write → data.local.az/1.2.10.in-addr.arpa.zone<br>2025-09-18 23:26:07 [INFO] named.conf.add → Added zone 1.2.10.in-addr.arpa<br>2025-09-18 23:26:07 [INFO] reverse.write → data.local.az/2.2.10.in-addr.arpa.zone<br>2025-09-18 23:26:07 [INFO] named.conf.add → Added zone 2.2.10.in-addr.arpa<br>2025-09-18 23:26:07 [INFO] reverse.write → data.local.az/3.2.10.in-addr.arpa.zone<br>2025-09-18 23:26:07 [INFO] named.conf.add → Added zone 3.2.10.in-addr.arpa<br>2025-09-18 23:26:07 [INFO] reverse.write → data.local.az/4.2.10.in-addr.arpa.zone<br>2025-09-18 23:26:07 [INFO] named.conf.add → Added zone 4.2.10.in-addr.arpa<br>2025-09-18 23:26:07 [INFO] domain.done → ✓ Finished data.local.az</pre><h3>3. Ansible roles</h3><p>Two Ansible roles were created to fully automate BIND9 setup and DNS record management:</p><ul><li><strong>bind9-install</strong> → Handles the initial installation of BIND9 and applies the base configuration.</li><li><strong>bind9-update-zones</strong> → Deploys and updates zones generated from YAML files onto the BIND9 server.</li></ul><p><strong>./deploy/ansible.cfg:</strong></p><pre>[defaults]<br>remote_user = devops<br>role_path = ./roles<br>host_key_checking = False<br>deprecation_warnings = False<br>command_warnings=False<br>force_valid_group_names = False<br><br>[privilege_escalation]<br>become = True<br>become_method = sudo<br>become_user = root<br>become_ask_pass = True<br>ansible_become_timeout = 30</pre><p><strong>./deploy/main.yml:</strong></p><pre>---<br>- name: Install and Configure Infrastructure Components<br>  hosts: &quot;{{ lookup(&#39;env&#39;, &#39;CI_ANSIBLE_GROUP_NAME&#39;) }}&quot;<br>  serial: &quot;{{ sequential_host_limit | default(20) }}&quot;<br>  tasks:<br>    - name: Include the role dynamically<br>      include_role:<br>        name: &quot;{{ lookup(&#39;env&#39;, &#39;CI_ANSIBLE_ROLE_NAME&#39;) }}&quot;</pre><p><strong>./deploy/invenotry.yml:</strong></p><pre>all:<br>  hosts:<br>    prod-bind9-instance01.devops.local.az:<br>      ansible_host: 10.0.1.12<br>  children:<br>    bind9:<br>      hosts:<br>        prod-bind9-instance01.devops.local.az:</pre><p><strong>./deploy/roles/bind9-install/defaults/main.yml:</strong></p><pre>---<br># Paths for the main zone directories<br>bind_zone_base_path: /etc/bind/zones<br>dvp_zone_dir: &quot;{{ bind_zone_base_path }}/devops.local.az&quot;<br>dtp_zone_dir: &quot;{{ bind_zone_base_path }}/data.local.az&quot;<br><br># Path to the main named configuration directory<br>named_conf_dir: /etc/bind</pre><p><strong>./deploy/roles/bind9-install/handlers/main.yml:</strong></p><pre>---<br>- name: Reload bind9<br>  service:<br>    name: bind9<br>    state: reloaded</pre><p><strong>./deploy/roles/bind9-install/templates/named.conf.options.j2:</strong></p><pre>options {<br>    directory &quot;/var/cache/bind&quot;;<br><br>    recursion yes;<br>    allow-recursion { {{ bind9_allow_recursion | join(&quot;; &quot;) }}; };<br><br>    forwarders {<br>        {% for fwd in bind9_forwarders %}<br>        {{ fwd }};<br>        {% endfor %}<br>    };<br><br>    dnssec-validation auto;<br><br>    listen-on { any; };<br>    listen-on-v6 { any; };<br><br>    allow-transfer { {{ bind9_allow_transfer | join(&quot;; &quot;) }}; };<br>};</pre><p><strong>./deploy/roles/bind9-install/tasks/main.yml:</strong></p><pre>---<br>- name: Install Bind9<br>  ansible.builtin.apt:<br>    name: bind9<br>    state: present<br>    update_cache: yes<br>  ignore_errors: yes<br><br>- name: Create a temporary directory for generated files<br>  ansible.builtin.tempfile:<br>    state: directory<br>    suffix: _bind_zones<br>  delegate_to: localhost<br>  register: temp_dir<br><br>- name: Install required Python dependencies on the control node<br>  ansible.builtin.pip:<br>    name:<br>      - pyyaml<br>      - colorama<br>  delegate_to: localhost<br>  run_once: true<br><br>- name: Copy Python script and YAML files to the temporary directory<br>  ansible.builtin.copy:<br>    src: &quot;{{ item }}&quot;<br>    dest: &quot;{{ temp_dir.path }}/&quot;<br>    mode: &#39;0755&#39;<br>  delegate_to: localhost<br>  loop:<br>    - main.py<br>    - logger.py<br>    - devops.local.az.yaml<br>    - data.local.az.yaml<br><br>- name: Generate BIND9 configuration and zone files<br>  ansible.builtin.command:<br>    cmd: python3 main.py<br>    chdir: &quot;{{ temp_dir.path }}&quot;<br>  delegate_to: localhost<br>  changed_when: true<br><br>- name: Ensure DVP and DTP zone directories exist<br>  ansible.builtin.file:<br>    path: &quot;{{ item }}&quot;<br>    state: directory<br>    owner: root<br>    group: bind<br>    mode: &#39;0755&#39;<br>  loop:<br>    - &quot;{{ dvp_zone_dir }}&quot;<br>    - &quot;{{ dtp_zone_dir }}&quot;<br><br>- name: Copy generated zone directories to the target<br>  ansible.builtin.copy:<br>    src: &quot;{{ temp_dir.path }}/{{ item }}&quot;<br>    dest: &quot;{{ bind_zone_base_path }}/&quot;<br>    owner: root<br>    group: bind<br>    mode: &#39;0644&#39;<br>  loop:<br>    - devops.local.az<br>    - data.local.az<br>  notify: Reload bind9<br><br>- name: Copy generated named.conf.local to the target<br>  ansible.builtin.copy:<br>    src: &quot;{{ temp_dir.path }}/named.conf.local&quot;<br>    dest: /etc/bind/named.conf.local<br>    owner: root<br>    group: bind<br>    mode: &#39;0644&#39;<br>  notify: Reload bind9<br><br>- name: Configure named.conf.options<br>  ansible.builtin.template:<br>    src: named.conf.options.j2<br>    dest: /etc/bind/named.conf.options<br>    owner: root<br>    group: bind<br>    mode: &#39;0644&#39;<br>  notify: Reload bind9<br><br>- name: Find all DVP and DTP zone files for syntax check<br>  ansible.builtin.find:<br>    paths:<br>      - &quot;{{ dvp_zone_dir }}&quot;<br>      - &quot;{{ dtp_zone_dir }}&quot;<br>    patterns: &quot;*.zone&quot;<br>  register: zone_files_to_check<br><br>- name: Check syntax of all DVP and DTP zone files<br>  ansible.builtin.command: named-checkzone {{ item.path | basename | regex_replace(&#39;\\.zone$&#39;, &#39;&#39;) }} {{ item.path }}<br>  loop: &quot;{{ zone_files_to_check.files }}&quot;<br>  register: check_zone_result<br>  changed_when: false<br>  failed_when: check_zone_result.rc != 0<br><br>- name: Check syntax of main BIND9 configuration files<br>  ansible.builtin.command: named-checkconf {{ item }}<br>  loop:<br>    - &quot;{{ named_conf_dir }}/named.conf.local&quot;<br>    - &quot;{{ named_conf_dir }}/named.conf.options&quot;<br>  register: check_conf_result<br>  changed_when: false<br>  failed_when: check_conf_result.rc != 0<br><br>- name: Ensure bind9 is running and enabled<br>  ansible.builtin.service:<br>    name: bind9<br>    state: started<br>    enabled: yes<br><br>- name: Clean up temporary directory<br>  ansible.builtin.file:<br>    path: &quot;{{ temp_dir.path }}&quot;<br>    state: absent<br>  delegate_to: localhost<br>  ignore_errors: true</pre><p><strong>./deploy/roles/bind9-update-zones/defaults/main.yml:</strong></p><pre>---<br># Base path for zone files<br>bind_zone_base_path: /etc/bind/zones<br><br># Paths for the main forward zone directories<br>dvp_zone_dir: &quot;{{ bind_zone_base_path }}/devops.local.az&quot;<br>dtp_zone_dir: &quot;{{ bind_zone_base_path }}/data.local.az&quot;</pre><p><strong>./deploy/roles/bind9-update-zones/handlers/main.yml:</strong></p><pre>---<br>- name: Reload bind9<br>  ansible.builtin.command:<br>    cmd: rndc reload<br>  become: true<br>  changed_when: true</pre><p><strong>./deploy/roles/bind9-update-zones/tasks/main.yml:</strong></p><pre>---<br>- name: Create a temporary directory for generated files<br>  ansible.builtin.tempfile:<br>    state: directory<br>    suffix: _bind_zones<br>  delegate_to: localhost<br>  register: temp_dir<br><br>- name: Install required Python dependencies on the control node<br>  ansible.builtin.pip:<br>    name:<br>      - pyyaml<br>      - colorama<br>  delegate_to: localhost<br>  run_once: true<br><br>- name: Copy Python script and YAML files to the temporary directory<br>  ansible.builtin.copy:<br>    src: &quot;{{ item }}&quot;<br>    dest: &quot;{{ temp_dir.path }}/&quot;<br>    mode: &#39;0755&#39;<br>  delegate_to: localhost<br>  loop:<br>    - main.py<br>    - logger.py<br>    - devops.local.az.yaml<br>    - data.local.az.yaml<br><br>- name: Generate BIND9 configuration and zone files<br>  ansible.builtin.command:<br>    cmd: python3 main.py<br>    chdir: &quot;{{ temp_dir.path }}&quot;<br>  delegate_to: localhost<br>  changed_when: true<br><br>- name: Ensure DVP and DTP zone directories exist and are clean<br>  ansible.builtin.file:<br>    path: &quot;{{ item }}&quot;<br>    state: absent<br>  loop:<br>    - &quot;{{ dvp_zone_dir }}&quot;<br>    - &quot;{{ dtp_zone_dir }}&quot;<br>  become: true<br><br>- name: Recreate fresh DVP and DTP zone directories<br>  ansible.builtin.file:<br>    path: &quot;{{ item }}&quot;<br>    state: directory<br>    owner: bind<br>    group: bind<br>    mode: &#39;0755&#39;<br>  loop:<br>    - &quot;{{ dvp_zone_dir }}&quot;<br>    - &quot;{{ dtp_zone_dir }}&quot;<br>  become: true<br><br>- name: Copy generated devops.local.az zone files to the target<br>  ansible.builtin.copy:<br>    src: &quot;{{ temp_dir.path }}/devops.local.az/&quot;<br>    dest: &quot;{{ dvp_zone_dir }}/&quot;<br>    owner: bind<br>    group: bind<br>    mode: &#39;0644&#39;<br>  become: true<br>  notify: Reload bind9<br><br>- name: Copy generated data.local.az zone files to the target<br>  ansible.builtin.copy:<br>    src: &quot;{{ temp_dir.path }}/data.local.az/&quot;<br>    dest: &quot;{{ dtp_zone_dir }}/&quot;<br>    owner: bind<br>    group: bind<br>    mode: &#39;0644&#39;<br>  become: true<br>  notify: Reload bind9<br><br>- name: Copy generated named.conf.local to the target<br>  ansible.builtin.copy:<br>    src: &quot;{{ temp_dir.path }}/named.conf.local&quot;<br>    dest: /etc/bind/named.conf.local<br>    owner: root<br>    group: bind<br>    mode: &#39;0644&#39;<br>  become: true<br>  notify: Reload bind9<br><br>- name: Find all DVP and DTP zone files for syntax check<br>  ansible.builtin.find:<br>    paths:<br>      - &quot;{{ dvp_zone_dir }}&quot;<br>      - &quot;{{ dtp_zone_dir }}&quot;<br>    patterns: &quot;*.zone&quot;<br>  register: zone_files_to_check<br><br>- name: Check syntax of all zone files<br>  ansible.builtin.command: &gt;<br>    named-checkzone {{ item.path | basename | regex_replace(&#39;\\.zone$&#39;, &#39;&#39;) }} {{ item.path }}<br>  loop: &quot;{{ zone_files_to_check.files }}&quot;<br>  register: check_zone_result<br>  changed_when: false<br>  failed_when: check_zone_result.rc != 0<br><br>- name: Clean up temporary directory<br>  ansible.builtin.file:<br>    path: &quot;{{ temp_dir.path }}&quot;<br>    state: absent<br>  delegate_to: localhost<br>  ignore_errors: true</pre><h3>4. Pipelines</h3><p>The deployment process is fully automated through GitLab CI/CD. The flow works like this:</p><ol><li>A change is made in the YAML file.</li><li>Commit → Merge Request → Approval.</li><li>The pipeline runs automatically (or manually).</li><li>Updates are applied to BIND9.</li></ol><p>Pipeline configuration is handled in:</p><p><strong>.gitlab-ci.yml:</strong></p><pre>stages:<br>  - deploy<br>  - config<br><br>.bind9-deploy:<br>  image: $CI_REGISTRY_HOST/devops/image/ansible:latest<br>  script:<br>    # Step 1: Prepare role files<br>    - mkdir -p ./deploy/roles/$CI_ANSIBLE_ROLE_NAME/files<br>    - cp ./scripts/*.py ./deploy/roles/$CI_ANSIBLE_ROLE_NAME/files/<br>    - cp ./zones/*.yaml ./deploy/roles/$CI_ANSIBLE_ROLE_NAME/files/<br><br>    # Step 2: Move to deploy directory<br>    - cd deploy<br><br>    # Step 3: Run the playbook<br>    - ansible-playbook main.yml \<br>        -i inventory.yml \<br>        --extra-vars &quot;ansible_become_pass=$CI_ANSIBLE_PASSWORD ansible_password=$CI_ANSIBLE_PASSWORD&quot;<br>  when: manual<br><br>bind9-install:<br>  stage: deploy<br>  variables:<br>    CI_ANSIBLE_GROUP_NAME: bind9<br>    CI_ANSIBLE_ROLE_NAME: bind9-install<br>  extends: .bind9-deploy<br>  tags:<br>    - runner<br><br>bind9-update-zones:<br>  stage: config<br>  variables:<br>    CI_ANSIBLE_GROUP_NAME: bind9<br>    CI_ANSIBLE_ROLE_NAME: bind9-update-zones<br>  extends: .bind9-deploy<br>  tags:<br>    - runner</pre><h3>5. Synchronization with Domain Controllers</h3><p>BIND9 is used only for managing DNS records. Domain Controllers (DCs) still work as resolvers.</p><p>The synchronization process works as follows:</p><ul><li>On Windows DNS, a secondary zone is created with BIND9 as the master.</li><li>BIND9 keeps those zones as master zones.</li><li>With rndc reload, any changes are automatically pushed to the DCs.</li></ul><h3>BIND9 File Structure</h3><p>After the script runs, the actual file structure on BIND9 looks like this:</p><pre>/etc/bind/<br>├── named.conf<br>├── named.conf.default-zones<br>├── named.conf.local<br>├── named.conf.options<br>├── zones.rfc1918<br>└── zones/<br>    ├── data.local.az/<br>    │   ├── 1.2.10.in-addr.arpa.zone<br>    │   ├── 2.2.10.in-addr.arpa.zone<br>    │   ├── 3.2.10.in-addr.arpa.zone<br>    │   ├── 4.2.10.in-addr.arpa.zone<br>    │   └── data.local.az.zone<br>    └── devops.local.az/<br>        ├── 1.1.10.in-addr.arpa.zone<br>        ├── 2.1.10.in-addr.arpa.zone<br>        ├── 3.1.10.in-addr.arpa.zone<br>        └── devops.local.az.zone</pre><h3>Results and Benefits</h3><p>With this approach:</p><ul><li>We eliminated manual changes.</li><li>Every update is fully tracked with an audit trail.</li><li>Changes are safely applied through merge request reviews.</li><li>Zones and records are now managed in Git with simple YAML files.</li><li>DNS management is now clean and structured, avoiding forgotten or duplicate records.</li></ul><p>In the end, DNS management was integrated into the GitOps culture, bringing major improvements in security, control, and auditing.</p><h3>Additional Notes</h3><p>A separate architecture document, including proposed design, challenges, benefits, and workflow diagrams, was prepared and shared by <a href="https://www.linkedin.com/in/eminbayramzadeh/"><strong>Emin Bayramzade</strong></a>. Readers interested in the full technical background can refer to that post <a href="https://www.linkedin.com/posts/eminbayramzadeh_secure-dns-automation-with-bind-and-zone-activity-7375784453928853504--3-K?utm_source=share&amp;utm_medium=member_desktop&amp;rcm=ACoAABuY848B-Noqv90mbyFEveRbAK57kQKlSBA">https://www.linkedin.com/posts/eminbayramzadeh_secure-dns-automation-with-bind-and-zone-activity-7375784453928853504--3-K?utm_source=share&amp;utm_medium=member_desktop&amp;rcm=ACoAABuY848B-Noqv90mbyFEveRbAK57kQKlSBA</a>.</p><p><a href="https://www.linkedin.com/in/tural-jabbarli/"><strong>Tural Jabbarli</strong></a> was a main contributor to the project, taking on much of the implementation work.</p><p>The main purpose of this article is to share our approach. In reality, our setup and pipelines are more complex, but here it’s shown in a simplified way. The key point is the approach itself, which you can adapt to your own environment as needed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=730e3942c437" width="1" height="1" alt=""><hr><p><a href="https://medium.com/opsuniverse/automated-dns-zone-management-with-gitops-730e3942c437">Automated DNS Zone Management with GitOps</a> was originally published in <a href="https://medium.com/opsuniverse">OpsUniverse</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>