<?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[Stories by Harutyun Dermenjyan on Medium]]></title>
        <description><![CDATA[Stories by Harutyun Dermenjyan on Medium]]></description>
        <link>https://medium.com/@h.dermenjyan?source=rss-c5089d7be23b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*l2CcO6B1X7jhOlUBGs29Dg.jpeg</url>
            <title>Stories by Harutyun Dermenjyan on Medium</title>
            <link>https://medium.com/@h.dermenjyan?source=rss-c5089d7be23b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 09:34:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@h.dermenjyan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Automating BIND9 DNS Management: From Manual Configs to Infrastructure as Code]]></title>
            <link>https://blog.devgenius.io/automating-bind9-dns-management-from-manual-configs-to-infrastructure-as-code-84292214b5a5?source=rss-c5089d7be23b------2</link>
            <guid isPermaLink="false">https://medium.com/p/84292214b5a5</guid>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[dns]]></category>
            <dc:creator><![CDATA[Harutyun Dermenjyan]]></dc:creator>
            <pubDate>Fri, 13 Feb 2026 21:00:17 GMT</pubDate>
            <atom:updated>2026-02-17T09:29:23.359Z</atom:updated>
            <content:encoded><![CDATA[<h3>Automating BIND9: A DNS Management Stack with Ansible, REST API, and Terraform</h3><p>Managing BIND9 at scale — without an API, dynamic automation, or Infrastructure as Code — can get tedious. Editing zone files by hand, running rndc reload, hoping you didn’t fat-finger an IP address. The more servers and records you manage, the more it adds up.</p><p>That’s why this open-source stack has been built to turn BIND9 into a fully automated, API-driven DNS platform. No more SSH-ing into servers. No more manual zone file edits. Just Ansible, a REST API, and Terraform.</p><p>Here’s how it all fits together.</p><h3>The Problem</h3><p>Most organizations running on-premise infrastructure still rely on BIND9 for internal DNS. It’s battle-tested, performant, and ubiquitous. But managing it? That’s stuck in the 2000s:</p><ul><li><strong>Zone files are hand-edited</strong> on the server</li><li><strong>Changes require SSH access</strong> and root privileges</li><li><strong>No audit trail</strong> for who changed what</li><li><strong>No automation</strong> — every record is a manual operation</li><li><strong>Scaling means more manual work</strong> — add a server, copy configs, hope they match</li><li><strong>No Infrastructure as Code</strong> — DNS changes aren’t version-controlled or reviewable</li></ul><p>What if BIND9 had a REST API? What if you could manage zones and records with Terraform? What if Ansible handled the server setup and Terraform handled the DNS content?</p><p>That’s exactly what this stack provides.</p><h3>The Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m06neN2-vFs83EUuQ6e5oQ.png" /></figure><p><strong>Three open-source components, one goal:</strong></p><ol><li><a href="https://github.com/harutyundermenjyan/ansible-bind9-api"><strong>ansible-bind9-api</strong></a> — An Ansible role that deploys BIND9 and the REST API on any Ubuntu server</li><li><a href="https://github.com/harutyundermenjyan/bind9-api"><strong>bind9-api</strong></a> — A Python/FastAPI REST API that gives BIND9 a modern HTTP interface (deployed automatically by the Ansible role above, or manually using the <a href="https://github.com/harutyundermenjyan/bind9-api">API docs</a>)</li><li><a href="https://github.com/harutyundermenjyan/terraform-provider-bind9"><strong>terraform-provider-bind9</strong></a> — A Terraform/OpenTofu provider for managing DNS zones, records, and ACLs as code</li></ol><p>Ansible handles the one-time deployment of both BIND9 and the API. Once deployed, the API and Terraform provider work together as the runtime stack for day-to-day DNS management.</p><h3>The REST API for BIND9</h3><p><strong>Repository:</strong> <a href="https://github.com/harutyundermenjyan/bind9-api">github.com/harutyundermenjyan/bind9-api</a></p><p>BIND9 is powerful but has no API. You interact with it through rndc, nsupdate, and zone files. The bind9-api changes that by providing a RESTful HTTP interface on top of BIND9.</p><h3>What it does</h3><ul><li><strong>Zone Management</strong> — Create, list, delete zones via HTTP</li><li><strong>Record Management</strong> — Full CRUD for A, AAAA, CNAME, MX, TXT, SRV, CAA, NS, PTR, and more</li><li><strong>ACL Management</strong> — Create and manage access control lists programmatically</li><li><strong>DNSSEC Support</strong> — Key generation, zone signing, DS record retrieval</li><li><strong>Server Management</strong> — Health checks, statistics, version info</li><li><strong>Prometheus Metrics</strong> — Built-in /metrics endpoint for monitoring and alerting</li><li><strong>Interactive API Docs</strong> — Swagger UI at /docs and ReDoc at /redoc for exploring and testing every endpoint directly in the browser</li><li><strong>NZD Management</strong> — Clean up BIND9 internal databases for zone recovery</li></ul><h3>How it works</h3><p>The API runs as a systemd service alongside BIND9. It uses rndc for zone operations and nsupdate for record management - the same tools you’d use manually, but wrapped in a clean REST interface.</p><pre># Create a zone<br>curl -X POST -H &quot;X-API-Key: $KEY&quot; \<br>  http://dns-server:8080/zones \<br>  -d &#39;{&quot;name&quot;: &quot;example.com&quot;, &quot;zone_type&quot;: &quot;primary&quot;}&#39;<br><br># Add a record<br>curl -X POST -H &quot;X-API-Key: $KEY&quot; \<br>  http://dns-server:8080/zones/example.com/records \<br>  -d &#39;{&quot;name&quot;: &quot;www&quot;, &quot;type&quot;: &quot;A&quot;, &quot;ttl&quot;: 3600, &quot;records&quot;: [&quot;10.0.1.5&quot;]}&#39;<br><br># List all records<br>curl -H &quot;X-API-Key: $KEY&quot; \<br>  http://dns-server:8080/zones/example.com/records</pre><p>The API includes interactive Swagger UI at /docs — explore every endpoint, test requests, and see responses directly in the browser. ReDoc documentation is also available at /redoc.</p><h3>Security</h3><ul><li>API key authentication on every request</li><li>HTTPS support for encrypted communication (TLS)</li><li>Runs as the bind user (least privilege)</li><li>AppArmor integration on Ubuntu</li><li>API key auto-generated during deployment</li><li>No external database dependencies — uses BIND9’s native storage</li><li>Version disclosure disabled by default</li></ul><h3>Deployment: The Ansible Role</h3><p><strong>Repository:</strong> <a href="https://github.com/harutyundermenjyan/ansible-bind9-api">github.com/harutyundermenjyan/ansible-bind9-api</a></p><p>Setting up BIND9 with the REST API involves a lot of steps: installing packages, generating keys, configuring AppArmor, setting up systemd services, managing permissions. The Ansible role handles all of this.</p><h3>Installation</h3><pre># requirements.yml<br>roles:<br>  - name: bind9_api<br>    src: https://github.com/harutyundermenjyan/ansible-bind9-api.git<br>    version: v1.0.4<br>    scm: git</pre><pre>ansible-galaxy install -r requirements.yml</pre><h3>Usage</h3><pre># playbook.yml<br>- hosts: dns_servers<br>  become: true<br>  roles:<br>    - bind9_api</pre><p>That’s it. One command deploys everything:</p><ul><li>Installs BIND9 and all dependencies</li><li>Generates RNDC and TSIG/DDNS keys securely</li><li>Deploys all BIND9 configuration files</li><li>Configures AppArmor for security hardening</li><li>Hardens directory permissions (no world access)</li><li>Clones and installs the REST API with Python virtual environment</li><li>Sets up systemd services for both BIND9 and the API</li><li>Configures firewall rules (UFW)</li><li>Auto-generates a secure API key (preserved across re-runs)</li><li>Configures sudoers for safe service management</li><li>Validates the entire deployment with health checks and DNS resolution tests</li></ul><h3>Non-Destructive Re-runs</h3><p>This was a critical design decision. The role is fully idempotent and <strong>never destroys existing resources</strong>:</p><ul><li>Re-running the role won’t delete your zones or records</li><li>ACL files managed by Terraform are preserved</li><li>Existing API keys are preserved</li><li>Only missing components are added</li></ul><p>This means Ansible manages the <strong>infrastructure</strong> (BIND9 installation, config, API deployment) while Terraform manages the <strong>content</strong> (zones, records, ACLs). They don’t step on each other.</p><h3>Customization</h3><p>Everything is configurable via variables:</p><pre># group_vars/dns_servers.yml<br>bind9_api_port: 8080<br>bind9_api_repo: &quot;https://github.com/harutyundermenjyan/bind9-api.git&quot;<br>bind9_api_version: &quot;main&quot;<br><br>bind9_options:<br>  allow_query:<br>    - &quot;any&quot;<br>  allow_recursion:<br>    - &quot;localhost&quot;<br>    - &quot;10.0.0.0/8&quot;<br>  dnssec_validation: &quot;auto&quot;</pre><h3>The Terraform Provider</h3><p><strong>Repository:</strong> <a href="https://github.com/harutyundermenjyan/terraform-provider-bind9">github.com/harutyundermenjyan/terraform-provider-bind9</a><br> <strong>Registry:</strong> <a href="https://search.opentofu.org/provider/harutyundermenjyan/bind9/latest">search.opentofu.org/provider/harutyundermenjyan/bind9</a></p><p>This is where Infrastructure as Code meets DNS. The Terraform provider communicates with the bind9-api to manage your DNS resources declaratively.</p><h3>Provider Configuration</h3><p>The provider supports API key and username/password authentication, plus environment variables for CI/CD:</p><pre>terraform {<br>  required_providers {<br>    bind9 = {<br>      source  = &quot;harutyundermenjyan/bind9&quot;<br>      version = &quot;&gt;= 1.0.4&quot;<br>    }<br>  }<br>}<br><br>provider &quot;bind9&quot; {<br>  endpoint = &quot;https://dns.example.com:8080&quot;<br>  api_key  = var.bind9_api_key<br>  # Also supports: username, password, insecure, timeout<br>  # Environment variables: BIND9_ENDPOINT, BIND9_API_KEY<br>}</pre><h3>Managing DNS as Code</h3><pre># Create an ACL with TSIG key support<br>resource &quot;bind9_acl&quot; &quot;internal&quot; {<br>  name = &quot;internal&quot;<br>  entries = [<br>    &quot;localhost&quot;,<br>    &quot;localnets&quot;,<br>    &quot;10.0.0.0/8&quot;,<br>    &quot;172.16.0.0/12&quot;,<br>    &quot;192.168.0.0/16&quot;,<br>  ]<br>  comment = &quot;Internal networks&quot;<br>}<br><br>resource &quot;bind9_acl&quot; &quot;ddns_clients&quot; {<br>  name = &quot;ddns-clients&quot;<br>  entries = [<br>    &quot;10.0.0.0/8&quot;,<br>    &quot;key \&quot;ddns-key\&quot;&quot;,<br>  ]<br>  comment = &quot;Dynamic DNS update clients&quot;<br>}<br><br># Create a zone with full SOA and access control<br>resource &quot;bind9_zone&quot; &quot;example&quot; {<br>  name = &quot;example.com&quot;<br>  type = &quot;master&quot;<br>  soa_mname   = &quot;ns1.example.com&quot;<br>  soa_rname   = &quot;hostmaster.example.com&quot;<br>  default_ttl = 3600<br>  nameservers = [<br>    &quot;ns1.example.com&quot;,<br>    &quot;ns2.example.com&quot;,<br>  ]<br>  allow_query    = [&quot;internal&quot;]<br>  allow_transfer = [&quot;internal&quot;]<br>  allow_update   = [&quot;ddns-clients&quot;]<br>  notify         = true<br>}<br><br># A record (multiple IPs)<br>resource &quot;bind9_record&quot; &quot;web&quot; {<br>  zone    = bind9_zone.example.name<br>  name    = &quot;www&quot;<br>  type    = &quot;A&quot;<br>  ttl     = 300<br>  records = [&quot;10.0.1.5&quot;, &quot;10.0.1.6&quot;]<br>}<br><br># MX record<br>resource &quot;bind9_record&quot; &quot;mail&quot; {<br>  zone    = bind9_zone.example.name<br>  name    = &quot;@&quot;<br>  type    = &quot;MX&quot;<br>  ttl     = 3600<br>  records = [&quot;10 mail.example.com.&quot;, &quot;20 mail2.example.com.&quot;]<br>}<br><br># TXT record (SPF)<br>resource &quot;bind9_record&quot; &quot;spf&quot; {<br>  zone    = bind9_zone.example.name<br>  name    = &quot;@&quot;<br>  type    = &quot;TXT&quot;<br>  ttl     = 3600<br>  records = [&quot;v=spf1 include:_spf.google.com ~all&quot;]<br>}<br><br># SRV record<br>resource &quot;bind9_record&quot; &quot;sip&quot; {<br>  zone    = bind9_zone.example.name<br>  name    = &quot;_sip._tcp&quot;<br>  type    = &quot;SRV&quot;<br>  ttl     = 3600<br>  records = [&quot;10 60 5060 sip.example.com.&quot;]<br>}<br><br># CAA record<br>resource &quot;bind9_record&quot; &quot;caa&quot; {<br>  zone    = bind9_zone.example.name<br>  name    = &quot;@&quot;<br>  type    = &quot;CAA&quot;<br>  ttl     = 3600<br>  records = [&quot;0 issue \&quot;letsencrypt.org\&quot;&quot;]<br>}<br><br># CNAME record<br>resource &quot;bind9_record&quot; &quot;alias&quot; {<br>  zone    = bind9_zone.example.name<br>  name    = &quot;blog&quot;<br>  type    = &quot;CNAME&quot;<br>  ttl     = 3600<br>  records = [&quot;www.example.com.&quot;]<br>}</pre><h3>Supported Record Types</h3><p>A, AAAA, CNAME, MX, TXT, NS, PTR, SOA, SRV, CAA, NAPTR, HTTPS, SVCB, TLSA, SSHFP, DNSKEY, DS, LOC, HINFO, RP, DNAME, URI.</p><h3>Multi-Server Support</h3><p>The stack is designed for multi-server environments from the ground up. Use provider aliases to manage multiple DNS servers from a single configuration:</p><pre># Provider per server<br>provider &quot;bind9&quot; {<br>  alias    = &quot;dns1&quot;<br>  endpoint = &quot;http://dns1:8080&quot;<br>  api_key  = var.dns1_api_key<br>}<br><br>provider &quot;bind9&quot; {<br>  alias    = &quot;dns2&quot;<br>  endpoint = &quot;http://dns2:8080&quot;<br>  api_key  = var.dns2_api_key<br>}<br><br># Define records once<br>locals {<br>  records = {<br>    www = {<br>      zone    = &quot;example.com&quot;<br>      name    = &quot;www&quot;<br>      type    = &quot;A&quot;<br>      ttl     = 300<br>      records = [&quot;10.0.1.50&quot;, &quot;10.0.1.51&quot;]<br>    }<br>    mail = {<br>      zone    = &quot;example.com&quot;<br>      name    = &quot;@&quot;<br>      type    = &quot;MX&quot;<br>      ttl     = 3600<br>      records = [&quot;10 mail.example.com.&quot;]<br>    }<br>  }<br>}<br><br># Deploy same zone to both servers<br>resource &quot;bind9_zone&quot; &quot;dns1&quot; {<br>  provider = bind9.dns1<br>  name     = &quot;example.com&quot;<br>  type     = &quot;master&quot;<br>}<br><br>resource &quot;bind9_zone&quot; &quot;dns2&quot; {<br>  provider = bind9.dns2<br>  name     = &quot;example.com&quot;<br>  type     = &quot;master&quot;<br>}<br><br># Deploy same records to both servers<br>resource &quot;bind9_record&quot; &quot;dns1&quot; {<br>  for_each = local.records<br>  provider = bind9.dns1<br>  zone     = each.value.zone<br>  name     = each.value.name<br>  type     = each.value.type<br>  ttl      = each.value.ttl<br>  records  = each.value.records<br>}<br><br>resource &quot;bind9_record&quot; &quot;dns2&quot; {<br>  for_each = local.records<br>  provider = bind9.dns2<br>  zone     = each.value.zone<br>  name     = each.value.name<br>  type     = each.value.type<br>  ttl      = each.value.ttl<br>  records  = each.value.records<br>}</pre><p>Define records once in locals, deploy to every server. Add a third server? Add another provider alias and resource block. tofu apply brings it in sync.</p><p>For larger setups, the included <strong>Configuration Generator</strong> simplifies this further with server targeting:</p><pre>servers: []              # Deploy to ALL servers<br>servers: [&quot;dns1&quot;]        # Only on dns1<br>servers: [&quot;dns2&quot;, &quot;dns3&quot;] # Only on dns2 and dns3</pre><p>Define zones, records, and ACLs in a simple YAML config and generate all the Terraform files automatically. More on this below.</p><h3>Data Sources</h3><p>Query existing DNS data for use in other resources:</p><pre>data &quot;bind9_zone&quot; &quot;existing&quot; {<br>  name = &quot;example.com&quot;<br>}<br><br>data &quot;bind9_record&quot; &quot;lookup&quot; {<br>  zone = &quot;example.com&quot;<br>  name = &quot;www&quot;<br>  type = &quot;A&quot;<br>}</pre><h3>Features</h3><ul><li><strong>Resources</strong> — Zones, Records, ACLs with full CRUD operations</li><li><strong>Data Sources</strong> — Query existing zones and records for use in other resources</li><li><strong>22 Record Types</strong> — A, AAAA, CNAME, MX, TXT, SRV, CAA, NAPTR, HTTPS, SVCB, TLSA, SSHFP, DNSKEY, DS, LOC, HINFO, RP, DNAME, URI, NS, PTR, SOA</li><li><strong>Dual Authentication</strong> — API key or username/password, plus environment variables (BIND9_ENDPOINT, BIND9_API_KEY) for CI/CD pipelines</li><li><strong>Import</strong> — Import existing resources into Terraform state with tofu import</li><li><strong>Drift Detection</strong> — Automatically detects when server state differs from Terraform state during plan</li><li><strong>DNSSEC</strong> — Key management and zone signing</li><li><strong>Multi-Server</strong> — Manage N servers from a single configuration using provider aliases</li><li><strong>Convenience Attributes</strong> — Computed fields like address, target, priority, weight for easy access to parsed record data</li><li><strong>Published on OpenTofu Registry</strong> — Install with a single tofu init, no manual setup needed</li></ul><h3>Bonus: Terraform Configuration Generator</h3><p>Don’t want to write Terraform files by hand? The provider includes a configuration generator that creates a complete, ready-to-use Terraform project from a simple YAML config.</p><p><strong>Repository:</strong> <a href="https://github.com/harutyundermenjyan/terraform-provider-bind9/tree/main/examples/generator">examples/generator</a></p><p>Define everything in config.yaml - servers, zones, records, ACLs - and the generator produces all the .tf files:</p><pre># config.yaml - define your DNS infrastructure<br>servers:<br>  - name: dns1<br>    endpoint: &quot;http://dns1.example.com:8080&quot;<br>    api_key: &quot;your-api-key-1&quot;<br>    enabled: true<br><br>  - name: dns2<br>    endpoint: &quot;http://dns2.example.com:8080&quot;<br>    api_key: &quot;your-api-key-2&quot;<br>    enabled: true<br>  # Add as many servers as needed<br><br>zones:<br>  - name: example.com<br>    servers: []          # Deploy to ALL servers<br>records:<br>  - zone: example.com<br>    name: www<br>    type: A<br>    ttl: 300<br>    records: [&quot;10.0.1.50&quot;, &quot;10.0.1.51&quot;]<br>    servers: []              # Deploy to ALL servers<br><br>  - zone: example.com<br>    name: &quot;@&quot;<br>    type: MX<br>    ttl: 3600<br>    records: [&quot;10 mail.example.com.&quot;]<br>    servers: [&quot;dns1&quot;]        # Only on dns1<br><br>  - zone: example.com<br>    name: backup<br>    type: A<br>    ttl: 300<br>    records: [&quot;10.0.1.99&quot;]<br>    servers: [&quot;dns2&quot;, &quot;dns3&quot;] # Only on dns2 and dns3</pre><p>Run the generator:</p><pre>pip install pyyaml<br>python generate.py</pre><p>It produces a complete Terraform project:</p><pre>generated/<br>├── versions.tf       # Provider requirements<br>├── variables.tf      # Server variable definitions<br>├── terraform.tfvars  # Server credentials (gitignored)<br>├── acls.tf           # ACL definitions<br>├── zones.tf          # Zone definitions with SOA defaults<br>├── records.tf        # All record definitions<br>├── servers.tf        # Provider aliases and resources per server<br>└── .gitignore</pre><p>The key design: every resource supports servers: [] for targeting. Empty means all servers, or specify which ones. Adding a third server is just one more entry in config.yaml and a re-run of the generator.</p><h3>Putting It All Together</h3><p>Here’s the complete workflow from zero to a fully managed DNS setup.</p><h3>Step 1: Deploy with Ansible</h3><pre># inventory.yml<br>all:<br>  children:<br>    dns_servers:<br>      hosts:<br>        dns1:<br>          ansible_host: 10.0.1.10<br>        dns2:<br>          ansible_host: 10.0.1.11</pre><pre>ansible-galaxy install -r requirements.yml<br>ansible-playbook -i inventory.yml site.yml</pre><p>Two servers deployed, BIND9 running, API ready. Each server now has an auto-generated API key stored at /opt/bind9-api/.env.</p><h3>Step 1.5: Retrieve API Credentials</h3><p>After Ansible deployment, retrieve the API keys from each server for Terraform:</p><pre># Get API key from each server<br>ssh user@dns1 &quot;grep BIND9_API_AUTH_STATIC_API_KEY /opt/bind9-api/.env&quot;<br>ssh user@dns2 &quot;grep BIND9_API_AUTH_STATIC_API_KEY /opt/bind9-api/.env&quot;</pre><p>These keys go into your Terraform configuration — either in terraform.tfvars, config.yaml (for the generator), or a secrets manager like HashiCorp Vault.</p><h3>Step 2: Generate Terraform Configs</h3><pre>cd examples/generator<br>vim config.yaml        # Define your servers, zones, records<br>python generate.py     # Generate Terraform files</pre><h3>Step 3: Review Credentials</h3><p>Before applying, review terraform.tfvars — it contains your server endpoints and API keys:</p><pre># generated/terraform.tfvars<br>servers = {<br>  &quot;dns1&quot; = {<br>    endpoint = &quot;http://dns1:8080&quot;<br>    api_key  = &quot;key-retrieved-from-step-1.5&quot;<br>    enabled  = true<br>  }<br>  &quot;dns2&quot; = {<br>    endpoint = &quot;http://dns2:8080&quot;<br>    api_key  = &quot;key-retrieved-from-step-1.5&quot;<br>    enabled  = true<br>  }<br>}</pre><p>This file is gitignored by default — never commit API keys to version control.</p><h3>Step 4: Deploy DNS</h3><pre>cd generated<br>tofu init<br>tofu plan              # Preview changes<br>tofu apply             # Apply to all servers</pre><h3>Step 5: Day 2 Operations</h3><p>For adding, updating, or removing records on the same servers, edit the .tf files directly:</p><pre># Add or modify records<br>vim records.tf<br>tofu plan    # Preview changes<br>tofu apply   # Apply</pre><p>If servers or credentials change, update config.yaml and re-generate:</p><pre>vim config.yaml<br>python generate.py<br>cd generated &amp;&amp; tofu apply</pre><p>All changes are tracked in git — git log provides a full audit trail of every DNS change.</p><h3>Importing Existing Resources</h3><p>If resources already exist on the server (e.g., from a previous deployment), import them into Terraform state:</p><pre># Import an ACL<br>tofu import &#39;bind9_acl.dns1[&quot;internal&quot;]&#39; internal<br><br># Import a zone<br>tofu import &#39;bind9_zone.dns1[&quot;example_com&quot;]&#39; example.com<br><br># Import a record<br>tofu import &#39;bind9_record.dns1[&quot;example_com/www_A&quot;]&#39; example.com/www/A</pre><p>After importing, tofu plan will show no changes — Terraform now tracks the existing resources.</p><h3>Under the Hood: Where Everything Lives on the Server</h3><p>After deployment, here’s what’s on each DNS server and where to find things:</p><p><strong>BIND9 Configuration</strong> — managed by Ansible:</p><pre>/etc/bind/<br>├── named.conf            # Main config (includes other files)<br>├── named.conf.options    # Global options (listeners, recursion, logging)<br>├── named.conf.local      # Local zone includes and DDNS key<br>├── named.conf.acls       # ACLs (managed by API/Terraform after initial deploy)<br>├── rndc.key              # RNDC control key<br>└── keys/<br>    └── ddns-key.key      # TSIG key for dynamic DNS updates</pre><p><strong>DNS Zone Data</strong> — managed by Terraform via the API:</p><pre>/var/lib/bind/<br>├── db.example.com        # Zone file (base records snapshot)<br>└── db.example.com.jnl    # Journal (recent dynamic updates)</pre><p>BIND9 loads zone files into memory at startup. All queries are served from memory. The journal (*.jnl) stores changes made via the API since the last snapshot. BIND9 periodically merges the journal into the zone file, or you can force it with rndc sync.</p><p><strong>Dynamic Zone Definitions:</strong></p><pre>/var/cache/bind/<br>└── _default.nzd          # NZD database (which dynamic zones exist)</pre><p>Zones created via the API (and Terraform) are stored here. This is how BIND9 remembers which zones exist across restarts.</p><p><strong>REST API:</strong></p><pre>/opt/bind9-api/<br>├── .env                  # API credentials (API key, config)<br>├── app/                  # API source code<br>├── venv/                 # Python virtual environment<br>└── requirements.txt</pre><p><strong>Useful commands on the server:</strong></p><pre># Check BIND9 status<br>systemctl status named<br><br># Check API status<br>systemctl status bind9-api<br><br># List all zones<br>rndc zonestatus example.com<br><br># Dump all zone data to file<br>rndc dumpdb -zones<br><br># View actual records (from memory)<br>dig @127.0.0.1 example.com AXFR<br><br># Force journal merge into zone file<br>rndc sync example.com<br><br># Check API health<br>curl -H &quot;X-API-Key: $KEY&quot; http://localhost:8080/health</pre><h3>Get Started</h3><p>All projects are open-source and ready to use:</p><ul><li><strong>Ansible Role</strong> — <a href="https://github.com/harutyundermenjyan/ansible-bind9-api">ansible-bind9-api</a> — Deploys BIND9 + REST API</li><li><strong>REST API</strong> — <a href="https://github.com/harutyundermenjyan/bind9-api">bind9-api</a> — HTTP interface for BIND9</li><li><strong>Terraform Provider</strong> — <a href="https://github.com/harutyundermenjyan/terraform-provider-bind9">terraform-provider-bind9</a> — DNS as Code</li><li><strong>Config Generator</strong> — <a href="https://github.com/harutyundermenjyan/terraform-provider-bind9/tree/main/examples/generator">examples/generator</a> — Generate Terraform from YAML</li><li><strong>OpenTofu Registry</strong> — <a href="https://search.opentofu.org/provider/harutyundermenjyan/bind9/latest">harutyundermenjyan/bind9</a> — Provider registry</li></ul><p>Contributions, feedback, and stars are welcome.</p><p><em>These components were built to solve a specific need. Sharing them here in case they’re useful.</em> 🙂</p><p><strong>A note on AI:</strong> This project was built with the help of AI as a coding partner. The architecture and design decisions came from real-world needs, while AI helped accelerate the implementation, iterate faster, and catch edge cases. AI is a tool, and like any tool, what matters is how you use it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84292214b5a5" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/automating-bind9-dns-management-from-manual-configs-to-infrastructure-as-code-84292214b5a5">Automating BIND9 DNS Management: From Manual Configs to Infrastructure as Code</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stateful High Availability and Load Balancing using Keepalived with ipvsadm: Dual Master and Backup…]]></title>
            <link>https://medium.com/picsart-engineering/stateful-high-availability-and-load-balancing-using-keepalived-with-ipvsadm-dual-master-and-backup-243c113a8447?source=rss-c5089d7be23b------2</link>
            <guid isPermaLink="false">https://medium.com/p/243c113a8447</guid>
            <category><![CDATA[high-availability]]></category>
            <category><![CDATA[dns]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[lv]]></category>
            <category><![CDATA[load-balancer]]></category>
            <dc:creator><![CDATA[Harutyun Dermenjyan]]></dc:creator>
            <pubDate>Tue, 12 Dec 2023 10:07:42 GMT</pubDate>
            <atom:updated>2023-12-13T09:57:49.966Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stateful High Availability and Load Balancing using Keepalived with ipvsadm: Dual Master and Backup Configuration with LVS TCP State Synchronization</h3><h4>High Availability, Load Balancing and TCP State Synchronization</h4><blockquote>While I aim to maintain a practical and technical focus on real use cases, I’d like to provide some general insight into High Availability (HA), Load Balancing (LB), and Linux Virtual Server (LVS) as they are pertinent to this topic.</blockquote><p><strong>High Availability</strong> (HA) refers to systems that are designed to be reliable, operational, and available for use over long periods without any downtime or with minimal downtime. The goal is to ensure that services remain available and operational to the highest extent possible. Here are some key aspects of High Availability:</p><ol><li>Fault Tolerance: <br>High Availability systems can withstand failures without experiencing downtime. This is often achieved through redundancy, where critical system components are duplicated to ensure that a failure in one does not result in system downtime.</li><li>Failover: <br>In the event of a failure, traffic or operations are automatically rerouted to standby or backup systems to maintain service continuity.</li><li>Recovery: <br>High Availability systems have mechanisms for rapid recovery from failures to restore normal operations.</li><li>Maintenance: <br>These systems are designed to allow for maintenance, updates, and repairs without disrupting service availability.</li><li>Monitoring and Detection:<br>Continuous monitoring to detect and respond to failures promptly.</li><li>Load Balancing:<br>Distributing workloads across multiple servers or systems to ensure that no single point becomes a bottleneck, contributing to high availability.</li><li>Scalability:<br>The ability to increase capacity by connecting multiple hardware or software entities to work as a single logical unit.</li></ol><p>High Availability can be measured using metrics like uptime, which is often expressed as a percentage, with higher values like 99.9% (“three nines”) or 99.999% (“five nines”) indicating more reliable and available systems.</p><p>By incorporating these principles, organizations can ensure that their services remain reliable and available to users, which is crucial for maintaining trust and meeting service level agreements (SLAs).</p><p><strong>Load Balancing </strong>refers to the process of distributing network traffic across several servers to ensure that no single server becomes a bottleneck. This improves responsiveness and availability of applications and websites. Here are some key aspects of Load Balancing:</p><ol><li>Distribution of Traffic:<br>Load Balancing helps in efficiently distributing incoming network traffic across a group of servers, ensuring that no single server becomes overwhelmed with too much traffic. This is crucial for maintaining high performance and reliability.</li><li>Redundancy and Reliability:<br>By spreading the load, this process helps in mitigating the risk of server failures. If one server fails, the traffic is redirected to the remaining operational servers without any downtime.</li><li>Scalability:<br>As traffic grows, more servers can be added to the load balancing pool to handle the increased load, making load balancing a key component for scaling applications.</li><li>Performance Optimization:<br>Load Balancers can distribute traffic based on various factors, such as server performance or the type of content being served, ensuring that resources are utilized efficiently.</li><li>Session Persistence:<br>In scenarios where session persistence is crucial, Load Balancers can be configured to direct all requests from a particular client to the same server for as long as the session remains active.</li><li>Health Checks:<br>Load Balancers continuously monitor the health of servers, ensuring that traffic is not sent to servers that are unavailable or underperforming.</li><li>Algorithm-Based Distribution:<br>Load Balancers use various algorithms like Round Robin, Least Connections, or IP Hash to decide which server should handle a particular request.</li><li>Security:<br>They can also provide additional security by hiding the structure of the network and the servers within from the outside world.</li></ol><p>Load Balancing is a fundamental concept in ensuring that networks and applications can handle varying loads while providing a seamless user experience. It’s a crucial part of modern IT infrastructure, particularly for high traffic websites and critical business applications.</p><p><strong>Linux Virtual Server</strong> (LVS) is a scalable and high-performance server built on a Linux system. It’s often used for load balancing TCP/IP traffic among multiple servers. One of its features is TCP state synchronization, which is essential for maintaining a consistent and reliable service, especially in a high availability environment.</p><p>Here’s a breakdown of LVS TCP state synchronization:</p><ol><li>State Synchronization:<br>State synchronization allows multiple load balancers to share information about the current state of TCP connections. This is crucial for ensuring that all load balancers have a consistent view of the network, enabling them to make intelligent routing decisions.</li><li>Failover Capabilities:<br>In a scenario where one of the load balancers fails, TCP state synchronization enables another load balancer to take over without losing existing connections. This failover capability is a key aspect of maintaining high availability and ensuring uninterrupted service.</li><li>Connection Persistence:<br>By synchronizing the state of TCP connections, LVS ensures that client connections are not dropped or lost during failovers. Clients can continue to interact with the application without experiencing disruptions.</li><li>Clustered Environment:<br>In a clustered environment, having synchronized TCP states among all nodes ensures that traffic is evenly distributed and that no single node becomes a bottleneck. This also allows for more effective load distribution and better utilization of resources.</li><li>Real-time Synchronization:<br>The synchronization process occurs in real time or near real time, ensuring that all load balancers have the most current information about the state of TCP connections.</li><li>Reduced Downtime:<br>By ensuring that other load balancers can seamlessly take over in the event of a failure, TCP state synchronization significantly reduces the potential downtime and enhances the reliability of the system.</li></ol><p>LVS TCP state synchronization is an indispensable feature for environments requiring high availability and seamless failover capabilities. By maintaining a synchronized state of TCP connections among load balancers, LVS ensures that the system can effectively handle client requests, even in the face of individual node failures, thereby promoting a reliable and consistent user experience.</p><p>To ensure uninterrupted operation of your production services, let’s proceed by integrating the aforementioned three elements of High Availability (HA), Load Balancing (LB), and Linux Virtual Server (LVS) to work together.</p><p>To enhance the scalability and distribution of our HA/LB LVS, we will forego the standard master-backup solution and instead adopt a dual master and backup approach.</p><p>To emulate this setup and also to keep it simple for learning purposes, we will utilize 2 HA/LB and backend servers, also referred to as Real Servers (RS). If you wish to scale your HA/LB layer later, it will be easy to add more dual master and backup configurations as needed.</p><p>Let’s first illustrate our objectives on the following diagram:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*gHDd5uQHVuuyGqkyHcGnUw.jpeg" /></figure><p>As depicted in the diagram, you can observe that the connection between clients and Real Servers passes through the LB/HA nodes, but only in a one-way direction since the Real Servers respond to clients directly bypassing the HA/LB nodes. <em>To enable a functional setup, it’s essential to configure the Keepalived VRRP Virtual IP addresses (VIP) on the Real Servers as well, </em><strong><em>along with setting the ARP notification and response levels for all Real Servers (in our case RS1 through RS2), restricted within the network</em></strong><em>. </em>We will explore this further in an example later on<em>.</em></p><blockquote>Now, let’s proceed with the Keepalived and ipvsadm LVS configurations.</blockquote><p>Let’s assume we have the following nodes:</p><ul><li><strong>HA/LB nodes:</strong><br><strong>ha_lb_01</strong><br>- 172.16.0.10/24 static IP<br>- 10.0.0.10/24 VRRP VIP floating IP<br><strong>ha_lb_02</strong><br>- 172.16.0.11/24 static IP<br>- 10.0.0.11/24 VRRP VIP floating IP</li><li><strong>Backend/Real Servers: <br>rs1<br></strong>- 172.16.0.100/24 <br><strong>rs2</strong><br>- 172.16.0.101/24</li></ul><p>By inserting the line lvs_sync_daemon $IFACE $VRRP_NAME id $ID_Number in the global_defs section of the Keepalived configuration, Keepalived can directly manage LVS with ipvsadm.</p><pre>global_defs {<br>    lvs_sync_daemon $IFACE $VRRP_NAME id $ID_Number <br>    ...<br>    ...<br>    ...<br>    }</pre><p>However, in this scenario, we would end up with a single master and backup, which doesn’t align with our objective of having a dual master and backup setup.<br>Therefore, we will bypass the addition of lvs_sync_daemon in the global_defs section of Keepalived; instead, we will configure that part using custom notify scripts.</p><ul><li><strong>In ha_lb_01:<br></strong>apt -y install keepalived<br>cd /etc/keepalived<br>vi keepalived.conf — use your preferred editor</li></ul><pre>global_defs {<br>    router_id ha_lb_lvs # Replace the part on the right with your preferred name.<br>    enable_script_security<br>    script_user root<br>    }<br><br>vrrp_instance VI_1 { # vrrp protocol<br>    state MASTER # MASTER server of lvs<br>    interface ens18 # Replace with your interface<br>    virtual_router_id 50 # Virtual routing<br>    priority 100 # The masters should be assigned the highest priority.<br>    advert_int 1 # VRRP Advert interval in seconds<br>    authentication { # Verification (This authentication section is optional)<br>    auth_type PASS  <br>    auth_pass 1111 # Replace this with your preferred one.<br>    }<br>    virtual_ipaddress { <br>        10.0.0.10/24<br>    }<br>    notify &quot;/etc/keepalived/notify.sh&quot;<br>}<br><br>vrrp_instance VI_2 {<br>    state BACKUP<br>    interface ens18 # Replace with your interface<br>    virtual_router_id 51<br>    priority 90<br>    advert_int 1<br>    authentication { # Verification (This authentication section is optional)<br>        auth_type PASS<br>        auth_pass 2222 # Replace this with your preferred one.<br>    }<br>    virtual_ipaddress {<br>        10.0.0.11/24<br>    }<br>    notify &quot;/etc/keepalived/notify.sh&quot;<br>}<br><br>virtual_server 10.0.0.10 80 {<br>    delay_loop 6 # Real Server Check Interval<br>    lb_algo lc # Scheduling: Least-Connection<br>    lb_kind DR # The forwarding type: DR - Director Routing<br>    protocol TCP # Service protocol<br>    real_server 172.16.0.100 80 { # Backend/Real Server address<br>        weight 1<br>        HTTP_GET { # Application layer detection<br>            url {<br>              path / # Define the URL to monitor<br>              status_code 200 # The response code used to determine that the above detection mechanism is in a healthy state<br>            }<br>            connect_timeout 3 # Timeout duration of connection request<br>            retry 2 # retry count<br>            delay_before_retry 2 # Delay before retrying<br>        }<br>    }<br>    real_server 172.16.0.101 80 {<br>        weight 2<br>        HTTP_GET {<br>            url {<br>                path /<br>                status_code 200<br>            }<br>            connect_timeout 3<br>            retry 2<br>            delay_before_retry 2<br>        }<br>    }<br>}<br><br>virtual_server 10.0.0.11 80 {<br>    delay_loop 6<br>    lb_algo lc<br>    lb_kind DR<br>    protocol TCP<br>    real_server 172.16.0.100 80 {<br>        weight 1<br>        HTTP_GET {<br>            url {<br>              path /<br>              status_code 200<br>            }<br>            connect_timeout 3<br>            retry 2<br>            delay_before_retry 2<br>        }<br>    }<br>    real_server 172.16.0.101 80 {<br>        weight 2<br>        HTTP_GET {<br>            url {<br>                path /<br>                status_code 200<br>            }<br>            connect_timeout 3<br>            retry 2<br>            delay_before_retry 2<br>        }<br>    }<br>}</pre><ul><li>The notify script on <strong>ha_lb_01</strong> <br>notify.sh</li></ul><pre>#!/bin/bash<br>         <br>TYPE=$1<br>NAME=$2<br>ENDSTATE=$3<br>IFACE=ens18 # Replace with your interface<br><br>case $ENDSTATE in<br>    &quot;BACKUP&quot;) # Perform action for transition to BACKUP state<br>       ipvsadm --start-daemon backup --syncid 2 --mcast-interface=$IFACE<br>              exit 0<br>              ;;<br>    &quot;FAULT&quot;)  # Perform action for transition to FAULT state<br>              exit 0<br>              ;;<br>    &quot;STOP&quot;)  # Perform action for transition to STOP state<br>       ipvsadm --stop-daemon master<br>       ipvsadm --stop-daemon backup<br>              exit 0<br>              ;;<br>    &quot;MASTER&quot;) # Perform action for transition to MASTER state<br>       ipvsadm --start-daemon master --syncid 1 --mcast-interface=$IFACE<br>              exit 0<br>              ;;<br>    *)        echo &quot;Unknown state ${ENDSTATE}&quot;<br>              exit 1<br>              ;;<br>esac</pre><ul><li>service keepalived restart</li><li><strong>In ha_lb_02:<br></strong>apt -y install keepalived<br>cd /etc/keepalived<br>vi keepalived.conf — use your preferred editor</li></ul><pre>global_defs {<br>    router_id ha_lb_lvs<br>    enable_script_security<br>    script_user root<br>}<br><br>vrrp_instance VI_1 {<br>    state BACKUP<br>    interface ens18 # Replace with your interface<br>    virtual_router_id 50<br>    priority 90<br>    advert_int 1<br>    authentication { # Verification (This authentication section is optional)<br>        auth_type PASS<br>        auth_pass 1111 # Replace this with your preferred one.<br>    }<br>    virtual_ipaddress {<br>       10.0.0.10/24<br>    }<br>    notify &quot;/etc/keepalived/notify.sh&quot;<br>}<br><br>vrrp_instance VI_2 {<br>    state MASTER<br>    interface ens18 # Replace with your interface<br>    virtual_router_id 51<br>    priority 100<br>    advert_int 1<br>    authentication { # Verification (This authentication section is optional)<br>        auth_type PASS<br>        auth_pass 2222 # Replace this with your preferred one.<br>    }<br>    virtual_ipaddress {<br>        10.0.0.11/24<br>    }<br>    notify &quot;/etc/keepalived/notify.sh&quot;<br>}<br><br>virtual_server 10.0.0.10 80 {<br>    delay_loop 6 <br>    lb_algo lc <br>    lb_kind DR <br>    protocol TCP <br>    real_server 172.16.0.100 80 { <br>        weight 1<br>        HTTP_GET { <br>            url {<br>              path / <br>              status_code 200 <br>            }<br>            connect_timeout 3 <br>            retry 2 <br>            delay_before_retry 2 <br>        }<br>    }<br>    real_server 172.16.0.101 80 {<br>        weight 2<br>        HTTP_GET {<br>            url {<br>                path /<br>                status_code 200<br>            }<br>            connect_timeout 3<br>            retry 2<br>            delay_before_retry 2<br>        }<br>    }<br>}<br><br>virtual_server 10.0.0.11 80 {<br>    delay_loop 6<br>    lb_algo lc<br>    lb_kind DR<br>    protocol TCP<br>    real_server 172.16.0.100 80 {<br>        weight 1<br>        HTTP_GET {<br>            url {<br>              path /<br>              status_code 200<br>            }<br>            connect_timeout 3<br>            retry 2<br>            delay_before_retry 2<br>        }<br>    }<br>    real_server 172.16.0.101 80 {<br>        weight 2<br>        HTTP_GET {<br>            url {<br>                path /<br>                status_code 200<br>            }<br>            connect_timeout 3<br>            retry 2<br>            delay_before_retry 2<br>        }<br>    }<br>}</pre><ul><li>The notify script on <strong>ha_lb_02</strong> <br>notify.sh</li></ul><pre>#!/bin/bash<br><br>TYPE=$1<br>NAME=$2<br>ENDSTATE=$3<br>IFACE=ens18 # Replace with your interface<br><br>case $ENDSTATE in<br>    &quot;BACKUP&quot;) # Perform action for transition to BACKUP state<br>       ipvsadm --start-daemon backup --syncid 1 --mcast-interface=$IFACE<br>              exit 0<br>              ;;<br>    &quot;FAULT&quot;)  # Perform action for transition to FAULT state<br>              exit 0<br>              ;;<br>    &quot;STOP&quot;)  # Perform action for transition to STOP state<br>       ipvsadm --stop-daemon master<br>       ipvsadm --stop-daemon backup<br>              exit 0<br>              ;;<br>    &quot;MASTER&quot;) # Perform action for transition to MASTER state<br>       ipvsadm --start-daemon master --syncid 2 --mcast-interface=$IFACE<br>              exit 0<br>              ;;<br>    *)        echo &quot;Unknown state ${ENDSTATE}&quot;<br>              exit 1<br>              ;;<br>esac</pre><ul><li>service keepalived restart</li></ul><p>You may notice in the notify scripts that the ID of syncid is different in 2 servers to prevent conflicts between the two masters, ensuring that one master serves as a backup for the other and vice versa.<br>If everything is configured correctly, executing the command ipvsadm -l --daemon will yield the following output:</p><ul><li><strong>ha_lb_01</strong></li></ul><pre>root@ha_lb_01:/etc/keepalived# ipvsadm -l --daemon                                       <br>master sync daemon (mcast=ens18, syncid=1, maxlen=1472, group=224.0.0.81, port=8848, ttl=1)<br>backup sync daemon (mcast=ens18, syncid=2, maxlen=1472, group=224.0.0.81, port=8848, ttl=1)</pre><ul><li><strong>ha_lb_02</strong></li></ul><pre>root@ha_lb_02:/etc/keepalived# ipvsadm -l --daemon                                        <br>master sync daemon (mcast=ens18, syncid=2, maxlen=1472, group=224.0.0.81, port=8848, ttl=1) <br>backup sync daemon (mcast=ens18, syncid=1, maxlen=1472, group=224.0.0.81, port=8848, ttl=1) </pre><p>Now is the time to prepare our backend/Real Servers to operate in a unidirectional manner. As mentioned earlier, the connection initiates from the clients to the HA/LB nodes, which then forwards it to the Backend/Real Server. The Real Server responds directly to the clients, bypassing the HA/LB nodes:</p><p>As I mentioned earlier <em>it&#39;s essential to configure the Keepalived VRRP Virtual IP addresses (VIP) on the Real Servers as well, along with setting the ARP notification and response levels for all Real Servers (in our case RS1 through RS2), restricted within the network. We will explore this further in an example later on.</em></p><ul><li>Wee need to setup the following on both <strong>rs1</strong>, <strong>172.16.0.100 and </strong><strong>rs2 , 172.16.0.101</strong></li></ul><pre>echo 1 &gt; /proc/sys/net/ipv4/conf/all/arp_ignore<br>echo 1 &gt; /proc/sys/net/ipv4/conf/lo/arp_ignore<br>echo 2 &gt; /proc/sys/net/ipv4/conf/all/arp_announce<br>echo 2 &gt; /proc/sys/net/ipv4/conf/lo/arp_announce</pre><pre>ip a a 10.0.0.10/32 dev lo # or # ip a a 10.0.0.10/32 dev ens18 # Replace ens18 with your interface<br>ip a a 10.0.0.11/32 dev lo # or # ip a a 10.0.0.10/32 dev ens18 # Replace ens18 with your interface</pre><p>And voila, everything is ready for the stateful High Availability and Load Balancing to operate.</p><p>From here on, scaling the HA/LB nodes will be straightforward. I’ll only share an image of the scenario to provide context and insight for further scale of the HA/LB layer, should the need arise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Avx8fh0rWMXSfWbpARHicg.jpeg" /></figure><p>Short Reference Guide for ipvsadm Command Line:</p><ul><li>IPVS connection entries:<br>ipvsadm -L -n -c</li><li>List the virtual server table<br>ipvsadm -L -n</li><li>Daemon information output<br>ipvsadm -l --daemon</li></ul><p>For more information, refer to the man page for ipvsadm by executing man ipvsadm.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=243c113a8447" width="1" height="1" alt=""><hr><p><a href="https://medium.com/picsart-engineering/stateful-high-availability-and-load-balancing-using-keepalived-with-ipvsadm-dual-master-and-backup-243c113a8447">Stateful High Availability and Load Balancing using Keepalived with ipvsadm: Dual Master and Backup…</a> was originally published in <a href="https://medium.com/picsart-engineering">Picsart Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating installation of HA RKE2 Kubernetes cluster with Ansible]]></title>
            <link>https://blog.devgenius.io/automating-installation-of-ha-rke2-kubernetes-cluster-with-ansible-2456cc95d970?source=rss-c5089d7be23b------2</link>
            <guid isPermaLink="false">https://medium.com/p/2456cc95d970</guid>
            <category><![CDATA[kube-vip]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[rancher-labs]]></category>
            <category><![CDATA[ansible]]></category>
            <category><![CDATA[rke2]]></category>
            <dc:creator><![CDATA[Harutyun Dermenjyan]]></dc:creator>
            <pubDate>Tue, 04 Jan 2022 20:34:56 GMT</pubDate>
            <atom:updated>2022-09-11T13:13:56.255Z</atom:updated>
            <content:encoded><![CDATA[<h4>Creating Ansible manifests and installing a high availability (HA) RKE2 cluster with kube-vip.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*5W0xsO11iqd8GWn6hr-NcQ.gif" /></figure><p>Although there are different ways to install a Kubernetes cluster especially the managed ones within cloud platforms, still there are cases when we need to have it on bare metal in a DC. Thus depending on your needs, some installation-related questions may arise including how to automate the process making it flexible and re-deployable?</p><p>We will use <a href="https://docs.rke2.io/">RKE2</a> for provisioning and managing the Kubernetes cluster, <a href="https://kube-vip.chipzoller.dev/">kube-vip</a> for HA failover solution and <a href="https://www.ansible.com/">Ansible</a> for automating the installation process making it flexible and re-deployable.</p><p>Before to start I’d like briefly to prompt the sequence of steps and files we are going to create and apply with Ansible for getting ready our HA RKE2 cluster with kube-vip.</p><pre>.<br>├── <strong>inventory_file</strong> # Hostnames of master and agent nodes (<strong>1</strong>)<br>├── <strong>env_vars.yaml</strong> # The environment variables (<strong>2</strong>)<br>├── <strong>rke2-install-server.yml</strong> # The first master node (<strong>3</strong>)<br>├── <strong>kube-vip.yaml</strong> # For kube-vip installation (<strong>4</strong>)<br>└── <strong>token.enc</strong> # Encrypted TOKEN (<strong>5</strong>)<br>├── <strong>rke2-add-server.yaml</strong> # For additional master nodes (<strong>6</strong>)<br>├── <strong>rke2-add-agent-node.yaml</strong> # For adding the agent nodes (<strong>7</strong>)<br><br>0 directories, 7 files</pre><p>To have a HA <a href="https://docs.rke2.io/">RKE2</a> cluster, we need to:</p><ul><li>At least 3 master nodes</li><li>Failover solution with floating IP address between ControlPlane nodes<br><strong>*</strong> DNS record pointed to that floating IP address<br><strong>*</strong> <a href="https://kube-vip.chipzoller.dev/docs"><strong>kube-vip</strong></a><strong>. </strong>For<strong> </strong>the HA failover solution, I’ll choose the <a href="https://kube-vip.chipzoller.dev/docs"><strong>kube-vip</strong></a> which in contrast to other similar tools natively supports the watch of the ControlPlane health (<em>Control plane load balancing</em>) along with many other useful <a href="https://kube-vip.chipzoller.dev/docs/about/features">features</a></li><li>3 worker nodes for addons and other workloads in the cluster.</li></ul><blockquote>Let’s move forward with the <a href="https://www.ansible.com/"><em>Ansible</em></a><em> manifests.</em></blockquote><p>In our example the content of Ansible <strong>$Inventory_File </strong>(replace this with your inventory file) is</p><ul><li><strong>./inventory_file</strong></li></ul><pre>all:<br>  hosts:<br>    example-host1: # master node<br>    example-host2: # master node<br>    example-host3: # master node<br>    example-host4: # agent node<br>    example-host5: # agent node<br>    example-host6: # agent node</pre><p>To avoid reusing the values, let’s create the environment variables file for later use in the ansible manifests:</p><ul><li><strong>./env_vars.yaml</strong></li></ul><pre>##################################################<br>##################################################<br>###               RKE2 Configs                 ###<br>##################################################<br>##################################################<br><br>WATCHDIR: &quot;/var/lib/rancher/rke2/server/manifests&quot;<br>CONFDIR: &quot;/etc/rancher/rke2&quot;<br>CONFFILE: &quot;{{ CONFDIR }}/config.yaml&quot;<br>SERVER_FAILOVER_IP: &quot;w.x.y.z&quot; <strong># Replace with your failover floating IP address.</strong><br>SERVER_ADDRESS_SHORT: &quot;example-hostname&quot; <strong># Hostname pointed to failover floating IP (</strong>w.x.y.z<strong>), change with yours.</strong><br>SERVER_ADDRESS_FQDN: &quot;example-hostname.somedomain.tld&quot; <strong># FQDN pointed to failover floating IP (</strong>w.x.y.z<strong>), change with yours.</strong><br><br>##################################################<br>##################################################<br>###               RKE2 Version                 ###<br>##################################################<br>##################################################<br><br>INSTALL_RKE2_VERSION: &quot;v1.22.4+rke2r2&quot; <strong># Change with your preferred version.</strong><br><br>##################################################<br>##################################################<br>###                kube-vip                    ###<br>##################################################<br>##################################################<br><br>INTERFACE: &quot;ens192&quot; <strong># Change with yor IFACE</strong><br>VIP: &quot;{{ SERVER_FAILOVER_IP }}&quot;<br>CONTAINER_RUNTIME_ENDPOINT: &quot;unix:///run/k3s/containerd/containerd.sock&quot;<br>CONTAINERD_ADDRESS: &quot;/run/k3s/containerd/containerd.sock&quot;<br>KUBE_VIP_IMAGE: &quot;docker.io/plndr/kube-vip&quot;<br>KUBE_VIP_IMAGE_TAG: &quot;latest&quot;</pre><p>In the beginning, we need to install the first master node. Let’s create the ansible manifest for that.</p><ul><li><strong>./rke2-install-server.yaml</strong></li></ul><pre>- name: Install rke2 first server instance<br>  hosts: example-host1<br>  become: true<br>  vars_files:<br>    - env_vars.yaml <br><br>  tasks:<br>  - name: create directories if they don&#39;t exist<br>    file:<br>      path: &quot;{{ item }}&quot;<br>      state: directory<br>      owner: root<br>      group: root<br>      mode: 0755<br>      recurse: yes<br>    loop:<br>      - &quot;{{ CONFDIR }}&quot;<br>      - &quot;{{ WATCHDIR }}&quot;<br><br>  - name: get hostname short<br>    shell: |<br>      hostname -s<br>    register: hostname_short<br>  - name: hostname fqdn<br>    shell: |<br>      hostname -f<br>    register: hostname_fqdn<br><br>  - name: Print hostname fqdn and short<br>    debug:<br>      msg:<br>      - &quot;hostname short &#39;{{ hostname_short.stdout }}&#39;&quot;<br>      - &quot;hostname fqdn: &#39;{{ hostname_fqdn.stdout }}&#39;&quot;<br><br>  - name: Creating the config.yaml<br>    copy:<br>      dest: &quot;{{ CONFFILE }}&quot;<br>      content: |<br>        tls-san:<br>          - &quot;{{ hostname_short.stdout }}&quot;<br>          - &quot;{{ hostname_fqdn.stdout }}&quot;<br>          - &quot;{{ SERVER_ADDRESS_SHORT }}&quot;<br>          - &quot;{{ SERVER_ADDRESS_FQDN }}&quot;<br>          - &quot;{{ SERVER_FAILOVER_IP }}&quot;<br>        <br>        cni: &quot;canal&quot; # optional<br>    notify: &quot;rke2-server service restart&quot;<br><br>  - name: Creating the CoreDNS config file<br>    copy:<br>      dest: &quot;{{ WATCHDIR }}/rke2-coredns-config.yaml&quot;<br>      content: |<br>        apiVersion: helm.cattle.io/v1<br>        kind: HelmChartConfig<br>        metadata:<br>          creationTimestamp: null<br>          name: rke2-coredns<br>          namespace: kube-system<br>        spec:<br>          valuesContent: |-<br>            nodelocal:<br>              enabled: true <strong># Change this to false or remove this (<em>Creating the CoreDNS config file</em>) section altogether if you don’t want to install <em>NodeLocal DNSCache</em></strong><br>          bootstrap: true<br><br>  - name: Installing rke2 server<br>    shell: |<br>      curl -sfL https://get.rke2.io | INSTALL_RKE2_CHANNEL=stable INSTALL_RKE2_VERSION=&quot;{{ INSTALL_RKE2_VERSION }}&quot; sh -<br>    notify: &quot;rke2-server service start&quot;<br><br>  handlers:<br>    - name: Make sure a service unit is running<br>      systemd:<br>        state: started<br>        name: rke2-server<br>      listen: &quot;rke2-server service start&quot;<br><br>    - name: Make sure a service unit is restarted<br>      systemd:<br>        state: restarted<br>        name: rke2-server<br>      listen: &quot;rke2-server service restart&quot;</pre><p><strong>The ansible command to create the first master node.</strong></p><pre><strong>ansible-playbook -u $USERNAME -i $Inventory_File -l example-host1 ./rke2-install-server.yaml</strong></pre><p>The first master node is ready.</p><p>You can get the kubectl config in the <strong><em>/etc/rancher/rke2/rke2.yaml</em></strong> file, by default the server address is 127.0.0.1 change it with the hostname you have set in place of example-host1 to have access remotely. Later, after the kube-vip is installed we will change it with our HA floating IP address or hostname.</p><p>It is time to install <a href="https://kube-vip.chipzoller.dev/docs">kube-vip</a> before installing the 2nd and 3rd master and other agent nodes.</p><p><em>Let’s create the ansible manifest file for the </em><strong><em>kube-vip</em></strong><em> installation</em></p><ul><li><strong>./kube-vip.yaml</strong></li></ul><pre>- name: Install kube-vip<br>  hosts: example-host1<br>  become: true<br>  vars_files:<br>    - env_vars.yaml  <br><br>  tasks:<br>  - name: Download kube-vip RBAC file<br>    get_url:<br>      url: https://kube-vip.io/manifests/rbac.yaml<br>      dest: &quot;{{ WATCHDIR }}/kube-vip-rbac.yaml&quot;<br>      owner: root<br>      group: root<br>      mode: 0644<br><br>  - name: Deploying kube-vip<br>    shell: |<br>      ctr --namespace k8s.io image pull &quot;{{ KUBE_VIP_IMAGE }}&quot;:&quot;{{ KUBE_VIP_IMAGE_TAG }}&quot;<br>      ctr --namespace k8s.io run --rm --net-host &quot;{{ KUBE_VIP_IMAGE }}&quot;:&quot;{{ KUBE_VIP_IMAGE_TAG }}&quot; vip /kube-vip \<br>      manifest daemonset \<br>      --arp \<br>      --interface &quot;{{ INTERFACE }}&quot; \<br>      --address &quot;{{ VIP }}&quot; \<br>      --controlplane \<br>      --leaderElection \<br>      --taint \<br>      --services \<br>      --inCluster | tee &quot;{{ WATCHDIR }}/kube-vip.yaml&quot;</pre><p><strong>The ansible command to install kube-vip:</strong></p><pre><strong>ansible-playbook -u $USERNAME -i $Inventory_File -l example-host1 ./kube-vip.yaml</strong></pre><p>After this step, the floating IP address is brought up on the first master node example-host1 by kube-vip daemonset, as the <em>RKE2 watches all files in the </em><strong><em>/var/lib/rancher/rke2/server/manifests</em></strong> (it’s<strong> </strong>defined<strong> </strong>as<strong> WATCHDIR </strong>in our ansible variables file) directory and installs them to the cluster, so no need to do the same thing on other nodes added later.</p><p>To see whether is the kube-vip pod and IP is running/ready or not you can use the following <a href="https://kubernetes.io/docs/reference/kubectl/cheatsheet/"><strong>kubectl</strong></a> command:</p><pre><strong>kubectl -n kube-system logs $(kubectl -n kube-system get po |grep kube-vip-ds|awk &#39;{print $1}&#39;)</strong></pre><p>We will use this floating IP address or hostname<em> example-hostname.somedomain.tld</em> pointed to that IP address as our server address in the <strong><em>/etc/rancher/rke2/config.yaml</em></strong> file for joining other master or agent nodes to the cluster.</p><p>Now it is time for joining our additional master and agent nodes to the cluster.<br>For joining them we need to get the token in the <strong><em>/var/lib/rancher/rke2/server/node-token</em></strong> file in the <em>example-host1</em> server later for putting it in the <strong><em>/etc/rancher/rke2/config.yaml</em></strong> file of additional joining nodes with the ansible.<br>As the content of the <strong>token</strong> file is sensitive we need to keep and use it encrypted within the ansible directory and manifests. <br>Below are the steps for keeping and using it securely in our ansible manifest as an environment variable.</p><p><strong>Encrypting the TOKEN:</strong></p><pre><strong>ssh example-host1 &#39;cat /var/lib/rancher/rke2/server/node-token&#39;</strong></pre><pre>Copy the output.</pre><pre><strong>cat &gt; ./token.enc &lt;&lt; \EOF</strong><br>TOKEN: <em>PASTE_HERE_THE_TOKEN::STRING_IN_THE:node-token_FILE</em><br><strong>EOF</strong></pre><pre><strong>ansible-vault encrypt ./token.enc</strong></pre><pre>New Vault password:<br>Confirm New Vault password:<br>Encryption successful</pre><p>Now, after we have the token encrypted let’s create the ansible manifest for adding the 2 additional master nodes example-host2 and example-host3:</p><ul><li><strong>./rke2-add-server.yaml</strong></li></ul><pre>- name: install rke2 server<br>  hosts: ~example-host[2-3]<br>  become: true<br>  vars_files:<br>    - env_vars.yaml<br>    - token.enc  # <em>The encrypted TOKEN file, later it is decrypted in the command-line with the </em><strong><em>--ask-vault-pass </em></strong><em>option.</em><br><br>  tasks:<br>  - name: create directories if they don&#39;t exist<br>    file:<br>      path: &quot;{{ item }}&quot;<br>      state: directory<br>      owner: root<br>      group: root<br>      mode: 0755<br>      recurse: yes<br>    loop:<br>      - &quot;{{ CONFDIR }}&quot;<br>      - &quot;{{ WATCHDIR }}&quot;<br><br>  - name: get hostname short<br>    shell: |<br>      hostname -s<br>    register: hostname_short<br>  - name: hostname fqdn<br>    shell: |<br>      hostname -f<br>    register: hostname_fqdn<br><br>  - name: Print hostname fqdn and short<br>    debug:<br>      msg:<br>      - &quot;hostname short &#39;{{ hostname_short.stdout }}&#39;&quot;<br>      - &quot;hostname fqdn: &#39;{{ hostname_fqdn.stdout }}&#39;&quot;<br><br>  - name: Creating the config.yaml<br>    copy:<br>      dest: &quot;{{ CONFFILE }}&quot;<br>      content: |<br>        token: {{ TOKEN }}<br>        server: https://{{ SERVER_ADDRESS_FQDN }}:9345<br>        tls-san:<br>          - &quot;{{ hostname_short.stdout }}&quot;<br>          - &quot;{{ hostname_fqdn.stdout }}&quot;<br>          - &quot;{{ SERVER_ADDRESS_SHORT }}&quot;<br>          - &quot;{{ SERVER_ADDRESS_FQDN }}&quot;<br>          - &quot;{{ SERVER_FAILOVER_IP }}&quot;<br>    notify: &quot;rke2-server service restart&quot;<br><br>  - name: Installing rke2 server<br>    shell: |<br>      curl -sfL https://get.rke2.io | INSTALL_RKE2_CHANNEL=stable INSTALL_RKE2_VERSION=&quot;{{ INSTALL_RKE2_VERSION }}&quot; sh -<br>    notify: &quot;rke2-server service start&quot;<br><br>  handlers:<br>  - name: Make sure a service unit is running<br>    systemd:<br>      state: started<br>      name: rke2-server<br>    listen: &quot;rke2-server service start&quot;<br><br>  - name: Make sure a service unit is restarted<br>    ansible.builtin.systemd:<br>      state: restarted<br>      name: rke2-server<br>    listen: &quot;rke2-server service restart&quot;</pre><p><strong>Please note</strong>, in the commands below the master nodes are added one after the other as if you bring up 2 master nodes at the same time the second one is likely to fail. The reason for that is because there are too many learner etcd members in the cluster.<br>In the case of adding agent nodes, we can add all of them at the same time without a problem.</p><p><strong>The ansible command:</strong></p><pre><strong>ansible-playbook -u $USERNAME -i $Inventor_File ./rke2-add-server.yaml -l example-host2 --ask-vault-pass</strong></pre><pre>Vault password:</pre><pre><strong>ansible-playbook -u $USERNAME -i $Inventor_File ./rke2-add-server.yaml -l example-host3 --ask-vault-pass</strong></pre><pre>Vault password:</pre><p>For the Vault password: enter the same password you have set above when encrypting the content of<strong><em> </em></strong>the<strong><em> token.enc</em></strong> file.</p><p>Finally, let’s add the 3 agent nodes to the cluster as I already mentioned above we can add all of them at the same time.</p><ul><li><strong>./rke2-add-agent-node.yaml</strong></li></ul><pre>- name: install rke2 agent node<br>  hosts: all:!~example-host[1-3] # Including all hosts and excluding the master nodes.<br>  become: true<br>  vars_files:<br>    - env_vars.yaml<br>    - token.enc  # <em>The encrypted TOKEN file, later it is decrypted in the command-line with the </em><strong><em>--ask-vault-pass </em></strong><em>option.</em><br><br>  tasks:<br>  - name: create directories if they don&#39;t exist<br>    file:<br>      path: &quot;{{ item }}&quot;<br>      state: directory<br>      owner: root<br>      group: root<br>      mode: 0755<br>      recurse: yes<br>    loop:<br>      - &quot;{{ CONFDIR }}&quot;<br><br>  - name: get hostname short<br>    shell: |<br>      hostname -s<br>    register: hostname_short<br>  - name: hostname fqdn<br>    shell: |<br>      hostname -f<br>    register: hostname_fqdn<br><br>  - name: Print hostname fqdn and short<br>    debug:<br>      msg:<br>      - &quot;hostname short &#39;{{ hostname_short.stdout }}&#39;&quot;<br>      - &quot;hostname fqdn: &#39;{{ hostname_fqdn.stdout }}&#39;&quot;<br><br>  - name: Creating the config.yaml<br>    copy:<br>      dest: &quot;{{ CONFFILE }}&quot;<br>      content: |<br>        token: {{ TOKEN }}<br>        server: https://{{ SERVER_ADDRESS_FQDN }}:9345<br>        <br>  - name: Installing rke2 agent<br>    shell: |<br>      curl -sfL https://get.rke2.io | INSTALL_RKE2_CHANNEL=stable INSTALL_RKE2_VERSION=&quot;{{ INSTALL_RKE2_VERSION }}&quot; sh -<br>    notify: &quot;rke2-agent service start&quot;<br><br>  handlers:<br>  - name: Make sure a service unit is running<br>    systemd:<br>      state: started<br>      name: rke2-agent<br>    listen: &quot;rke2-agent service start&quot;<br><br>  - name: Make sure a service unit is restarted<br>    ansible.builtin.systemd:<br>      state: restarted<br>      name: rke2-agent<br>    listen: &quot;rke2-agent service restart&quot;</pre><p><strong>Next, type the command:</strong></p><pre><strong>ansible-playbook -u $USERNAME -i $Inventor_File ./rke2-add-agent-node.yaml --ask-vault-pass</strong></pre><pre>Vault password:</pre><p>Our HA RKE2 cluster is ready with 3 master and 3 agent nodes with failover floating IP between ControlPlan nodes through kube-vip along with NodeLocal DNSCache enabled.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2456cc95d970" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/automating-installation-of-ha-rke2-kubernetes-cluster-with-ansible-2456cc95d970">Automating installation of HA RKE2 Kubernetes cluster with Ansible</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>