💻
Cheet Sheets
  • 🦁Başlarken
  • 🟧DevOps Pre-Requisite
    • ❤️Why Linux? | Linux Basics #1
    • 💛Vi Editor | Linux Basics #2
    • 💙Basics Commands | Linux Basics #3
    • 🧡Package Managers | Linux Basics #4
    • 💚Services | Linux Basics #5
    • 💛Networking Basics
    • 🤎DNS Basics
    • 🩶Applications Basics
    • 🟨Java introduction
    • 🟩NodeJS Introduction
    • 🟦Python Introduction
    • 🟪GIT Introduction
    • 🟧Apache Web Server Introduction
    • ⬛Apache Tomcat
    • 🟫Python Flask
    • 🟥Node.js Express App
    • 🟨Databases
    • 🟩MySQL
    • 🟪MongoDB
    • 🟨SSL & TLS
    • 🟦YAML & JSON - JSON Path
    • ⬛Labs Resources
  • 🍎Kubernetes
    • 🍏Kubernetes: Nedir ?
    • 🍒Bileşenler
    • 🍵Kubectl ve Versiyon
    • ❤️Pod
    • 🏷️Label ve Selector
    • 🔎Annotation
    • 📲Namespaces
    • 📦Deployments
    • 🔁ReplicaSet
    • 🔙Rollout & Rollback
    • 🌐Networking - 1
    • 🌏Service
    • 🛠️Liveness Probe & Readiness Probe
    • 🥐Resource Limits
    • 💰Environment Variables
    • 📃Ephemeral Volumes
    • 🔑Secrets
    • 🌂ConfigMap
    • 🖥️Node Affinity
    • 🔌Pod Affinity
    • ✍️Taint and Toleration
    • 🔦DaemonSet
    • 🧀PV/PVC
    • 🌜Storage Class
    • 🗿StatefulSet
    • 🕹️Job & Cronjob
    • 🔐Authentication
    • 📏Role-based access control (RBAC)
    • 🈷️Service Account
    • 📈Ingress
    • 📂ImagePullPolicy & ImageSecret
    • 📖Static Pods
    • 🌐Network Policy
    • 🫐Helm Nedir?
    • 📽️Prometheus Stack - Monitoring
    • 💼EFK Stack - Monitoring
    • 🥳CRD & Operator
  • 🧑‍⚕️GIT & GITHUB
    • 👉Girizgah
    • 🌴Branch
    • 🤝Merge
    • 🤔Conflict - Rebase
    • 🇸🇴Alias
    • 🛑Gitignore
    • 🥢Diff
    • ◀️Checkout
    • 🔦Stash
    • 👉Other
  • ☁️AWS
    • 🪣S3
    • 🚙EC2
    • ⚖️ELB
    • 🤝Auto Scaling
    • 🗄️EFS
    • 🔐VPC
    • 🎆CloudFront
    • ❤️Route53
    • 🦈RDS
    • 🏢ElastiCache
    • 🔭CloudWatch
    • 👀CloudTrail
    • 📃CloudFormation
    • 🔕SNS
    • 📬SQS
    • 🎇SWF
    • 📧SES
    • 📦Kinesis
    • 📐AWSConfig
    • 👩‍🏭OpsWork
    • 🚀Lambda - Api Gateway
    • 📌ECS - EKS
    • 🔑KMS
    • 📂Directory Service
    • 🏐Snowball
    • 💾Storage Gateway
    • 💽Volume Gateway
    • 📼Tape Gateway
    • 🏠Organizations
    • 🔙Backup-Transfer-CloudShell
    • 🆔IAM
    • 📀DataSync
    • 🗃️FSx
    • 🎒Aurora Serverless
    • 🌐Global Accelerator
    • 💪HPC
    • 🎰Outposts
    • 🗼Others
  • 👨‍🔬Ansible
    • 👉Girizhah
    • 📔YAML
    • ⚙️Komponentler
    • 🎒Inventory
    • 🏑ad-hoc
    • ▶️Playbook
  • 👨‍⚕️PROMETHEUS
    • 📈Terminoloji
    • 🦯Ubuntu 20.04 Prometheus Kurulum
    • 🗒️prometheus.yml dosyasına ilk bakış:
    • 🧭promQL up query
    • 📇Exporters
    • 🔦promQL Data Types
    • 🦯Selectors & Matchers
    • 🔢Binary Operators
    • 💀ignoring and on
    • ✍️Aggregation Operators
    • 🧠Functions
    • 🖊️Alıştırma
    • 💻Client Libraries
    • 🐍Examining the data of our Python application
    • 🐐Examining the data of our GO application
    • ⏺️Recording Rules
    • 💡rate functions
    • ⏰Alerting
    • ⌚Alert Routing
    • ⏰Slack integration with Prometheus
    • 🤯PagerDuty integration with Prometheus
    • ◼️BlackBox exporter
    • 📍Push Gateway
    • 🪒Service Discovery
    • 🧊kube cadvisor with external prometheus
    • 👉aws with prometheus
    • ☁️CloudWatch Exporter
    • 👨‍🚒mysql exporter
    • 🛃Custom exporter with Python
    • ⚙️Prometheus with HTTP API
    • 🤖Prometheus Federation For Kubernetes
    • 📺Grafana
    • ⁉️Prometheus: Ne zaman kullanılmalı? Ne zaman kullanılmamalıdır?
  • 🍪Sheets
    • 🛳️Docker Sheets
    • 🐐Kube Sheets
  • 🔢12 Factor APP
    • 🏗️Introduction
    • 1️⃣Codebase
    • 2️⃣Dependencies
    • 3️⃣Concurrency
    • 4️⃣Processes
    • 5️⃣Backing Services
    • 6️⃣Config
    • 7️⃣Build, release, run
    • 8️⃣Port binding
    • 9️⃣Disposability
    • 🔟Dev/prod parity
    • 🕚Logs
    • 🕛Admin processes
  • ☁️Azure 104
    • 👨‍👨‍👧‍👧Azure Active Directory ( Entra ID )
    • 💰Subscriptions
    • 🌎Virtual Network (VNET)
    • 💻Virtual Machines
    • 🧑‍🌾Load Balancing
    • 🥍Network Advanced
    • 🪡Automating Deployment and Configuration
    • 💂Securing Storage
    • 📓Administering Azure Blobs and Azure Files
    • 🔧Managing Storage
    • 🎁App Service
    • 🛳️Azure Container
    • 🥇Backup And Recovery
    • 🪐Network Watcher
    • ⏰Resource Monitoring And Alerts
  • ⛅AZURE 305
    • 🆔identity and access management
    • 💼Desing Azure AD (Entra ID)
    • 👨‍💼Desing for Azure B2B
    • 🛃Desing for Azure B2C
    • 💳Design for MFA and Conditional Access
    • ⛑️Design for Identity Protection
    • 🚶Access Reviews
    • 🚦Managed identity Demostration
    • 🔐Key Vault Demostration
    • 👑Governance hierarchy
    • 💠Design for Management Groups
    • 🔑Desing for Subscriptions
    • 🍇Desing for resource groups
    • 📟Design for resource tags
    • 🚷Azure Policy & RBAC
    • 🫐Desing For Blueprints
    • 🪡Desing for Virtual Networks
    • 🛫Design for on-premises connectivity to Azure
    • 🔽Design for network connectivity
    • 📦Design for application delivery
    • 🥞Design for network security and application protection
    • 📕Choose a compute solution
    • 🌊Design for virtual machines
    • 🔋Azure Batch Demostration
    • 🛰️Design for Azure App Service
    • ⛲Design for Azure Container Instances
    • 🎢Design for Azure Kubernetes Service
    • 📠Azure Functions Demostration
    • 💪Azure Logic Apps Demostration
    • 🧑‍💼Design for data storage
    • 🎞️Design for Azure storage accounts
    • 🌟Choose the storage replication
    • 📹Azure blob storage - Lifecycle & immutable demo
    • 🥌Azure Files Demostration
    • 🕸️Design Azure disks
    • 🦼Design for storage security
    • 🔮Azure Table Storage And Cosmos DB Demostration
    • 🟧Azure SQL Solutions
    • 🎡Azure SQL Database - Purchasing models
    • 🕯️Database availability
    • 📜Data security strategy
    • 🧮Azure SQL Edge
    • 🚲Azure Data Factory
    • 🔅Azure Data Lake Storage
    • 🧘‍♂️Azure Databricks
    • 🎒Azure Synapse Analytics
    • 🅰️Azure Stream Analytics
    • 📼Data flow strategy
    • 🍥Cloud Adoption Framework
    • ☣️Azure Migration Framework
    • 🦿Assessing workloads
    • 🪡Migration tools
    • 🤖Azure Database migration
    • 👥Storage migration
    • 👜Azure Backup
    • ⏲️Azure Blob Backup and Recovery
    • 💈Azure files backup and recovery
    • 🎞️Azure VM backup and recovery
    • 🧺Azure SQL backup and recovery
    • ⏰Azure Site Recovery
    • 📩Differentiate event and message
    • ✈️Azure messaging solutions
    • 🚜Event Hub
    • 🥍Application optimization solution
    • 🎁Application lifecycle
    • 📺Azure Monitor
    • 🅱️Log Analytics
    • 👥Azure workbooks and Insights
    • 🚌Azure Data Explorer
  • Github Actions
    • Github Actions Nedir?
    • Workflow & Schedule Triggers
    • Single and Multiple Events
    • Manuel Events
    • Webhook Events
    • Conditional Keywords For Steps
    • Expressions - 1
    • Expressions - 2
    • Runners
    • Workflow Commands
    • Workflow Context
    • Dependent Jobs
    • Encrypted Secrets
    • Configuration Variables
    • Default & Custom Env Varb
    • Set Env Varb with Workflow Commands
    • Github Token Secret
    • Add Script to workflow
    • Push Package #1
    • Push Package #2 Docker
    • Service Containers
    • Routing workflow to runner
    • CodeQL Step
    • Caching Package and Dependency Files
    • Remove workflow Artifact
    • Workflow Status Badge
    • Env Protection
    • Job Matrix Configuration
    • Disable & Delete Workflows
    • Actions type for Action
    • Inputs and Outputs for actions
    • Action Versions
    • Files and Directories for Actions
    • Exit Codes
    • Reusable Workflow & Reuse Templates for Actions and Workflows
    • Configure Self Hosted Runners for Enterprise
  • Loki
    • What is Loki?
    • Architecture of Loki
    • Install Loki For Ubuntu
    • Install Promtail For Ubuntu
    • Querying Logs
    • Loki in Kubernetes
    • Deploying Loki in Kubernetes
    • Connecting to Grafana
    • Viewing Kubernetes logs
    • Promtail Customize & Pipeline
  • Ansible
    • Ansible Introduction
    • Introduction to Ansible Configuration Files
    • Ansible Inventory
    • Inventory Formats
    • Ansible Variables
    • Variable Types
    • Registering Variables and Variable Precedence
    • Variable Scoping
    • Magic Variables
    • Ansible Facts
    • Ansible Playbooks
    • Verifying Playbooks
    • Ansible lint
    • Ansible Conditionals
    • Ansible Conditionals based on facts, variables, re-use
    • Ansible Loops
    • Ansible Modules
    • Introduction to Ansible Plugins
    • Modules and Plugins Index
    • Introduction to Handlers
    • Ansible Roles
    • Ansible Collections
    • Introduction to Templating
    • Jinja2 Templates for Dynamic Configs
  • 🅰️Ansible Advanced
    • Playbook run options
Powered by GitBook
On this page
  • 1. Templating Nedir?
  • 2. Jinja2 Nedir, Ansible’da Nasıl Kullanılır?
  • 3. Basit Değişken Yerleştirme
  • 4. Filtreler ve Dönüşümler
  • 5. Koşullar ve Döngüler
  • 1. Dizini ve Dosyaları Hazırlama
  • 2. Jinja2 Şablonu (config_file.j2)
  • 3. Playbook Yapısı (playbook.yml)
  • 4. Çalıştırma ve Mantık
  • Özet

Was this helpful?

  1. Ansible

Introduction to Templating

1. Templating Nedir?

Templating (şablonlama), “içinde değişken yerler olan bir iskelet dosya” ile “bu değişkenlere atanacak gerçek değerleri” birleştirerek, istenen tam metin (ör. bir konfig dosyası, HTML sayfası, e-posta vs.) oluşturma işidir.

Örnek: CEO’nun herkese gönderdiği davetiye e-postası bir şablondur (Hi {{ employee_name }}...). E-posta gönderirken employee_name yerine “John”, “Mary” gibi farklı değerler konur.

2. Jinja2 Nedir, Ansible’da Nasıl Kullanılır?

  • Jinja2: Python tabanlı bir templating motorudur. Ansible, şablon dosyalarını (.j2 uzantılı) Jinja2 ile yorumlayarak değişkenleri yerleştirir.

  • Ansible Playbook’ta “template:” modülü ile Jinja2 şablonunu uzak sunucuya render edip kopyalayabilirsiniz. Bu sayede “dinamik” konfig dosyaları veya scriptler oluşturabilirsiniz.

3. Basit Değişken Yerleştirme

# my_template.j2 (örnek şablon)
The name is {{ my_name }}!

Playbook’ta:

- name: Simple Templating
  hosts: localhost
  vars:
    my_name: "Bond"
  tasks:
    - name: Render a template
      template:
        src: my_template.j2
        dest: /tmp/output.txt
  1. my_template.j2 içinde {{ my_name }} kullandık.

  2. Vars (my_name: "Bond") Ansible tarafından şablona yerleştirilir.

  3. Sonuç dosyada: The name is Bond!


4. Filtreler ve Dönüşümler

Jinja2’de | (pipe) ile çeşitli filtreler kullanabilirsiniz.

  1. Metin Dönüşümleri

    The name is {{ my_name | upper }} 
    • my_name değerini büyük harfe çevirir ("BOND").

    • Ayrıca lower, title, replace("Bond","Bourne") gibi filtreler de var.

  2. Varsayılan Değer

    Hello {{ first_name | default("James") }} {{ last_name }}
    • Eğer first_name tanımlı değilse "James" kullanır, aksi halde first_name’in değerini alır.

  3. Liste İşlemleri

    Minimum: {{ nums | min }}
    Maximum: {{ nums | max }}
    Unique:  {{ nums | unique }}
    • nums bir liste olduğunda, min, max, unique gibi filtrelerle listeyi işleyebilirsiniz.

5. Koşullar ve Döngüler

Jinja2, “{% ... %}” blok sözdizimiyle if, for gibi yapıların kullanımını sağlar.

  1. Döngü (for)

    {% for item in my_list %}
    - {{ item }}
    {% endfor %}
    • Bu, my_list içindeki elemanları tek tek yazar.

  2. Koşul (if)

    {% if number == 2 %}
    This is 2
    {% else %}
    Not 2
    {% endif %}
    • “number” değişkeni 2 ise “This is 2” yazar, değilse “Not 2”.

Örnek Geniş – Bir şablon:

# config_file.j2
[mysqld]
datadir={{ datadir }}
{% if innodb == true %}
innodb_buffer_pool_size=1G
{% endif %}

Varsayılan: innodb=true, datadir="/var/lib/mysql"

  • Render sonunda:

    [mysqld]
    datadir=/var/lib/mysql
    innodb_buffer_pool_size=1G

Bu senaryoda, bir veritabanı sunucusunda (db_servers) MySQL konfigürasyon dosyasını Jinja2 şablonuyla nasıl otomatik oluşturabileceğimizi göreceksiniz. Ardından dosya güncellenirse, MySQL servisini yeniden başlatacak bir handler tetikliyoruz.

1. Dizini ve Dosyaları Hazırlama

Projenizde (örneğin my-ansible-project/ klasörünüzde) bir playbook (örn. playbook.yml) ve bir templates klasörü oluşturabilirsiniz:

my-ansible-project/
├── playbook.yml
└── templates/
    └── config_file.j2
  • templates/config_file.j2: Jinja2 şablon dosyası (içinde değişken kullanabilirsiniz).

  • playbook.yml: Ansible Playbook, hangi hostlara ve nasıl uygulayacağınızı belirtiyorsunuz.


2. Jinja2 Şablonu (config_file.j2)

Örnek bir MySQL konfig dosyası şablonu:

[mysqld]
datadir={{ datadir }}

{% if innodb %}
innodb_buffer_pool_size=1G
{% endif %}

user=mysql
port=3306

# Bu sadece bir örnek, ihtiyacınıza göre satırlar ekleyebilirsiniz.

Açıklama:

  • {{ datadir }} ve {{ innodb }} gibi değerler, Playbook veya vars içindeki değişkenlere göre doldurulacak.

  • innodb değişkeni true ise innodb_buffer_pool_size=1G satırı yazılacak, yoksa atlanacak.


3. Playbook Yapısı (playbook.yml)

Örnek bir playbook:

- name: Templating Demo
  hosts: db_servers
  gather_facts: no
  vars:
    innodb: true
    datadir: "/var/lib/mysql"

  tasks:
    - name: Apply MySQL config from template
      template:
        src: config_file.j2
        dest: /etc/mysql/my.cnf
      notify: Restart MySQL

  handlers:
    - name: Restart MySQL
      service:
        name: mysql
        state: restarted
  1. hosts: db_servers

    • db_servers grubunda tanımlı sunuculara bu işlemleri uyguluyoruz.

  2. vars

    • innodb ve datadir değişkenlerini tanımlıyoruz. (Örneğin innodb: true dedik, bu şablonun if bloğunu etkinleştirecek.)

  3. tasks

    • template modülü:

      • src: config_file.j2: Ansible controller (bu makine) üzerindeki templates/ klasöründeki Jinja2 şablon dosyamız.

      • dest: /etc/mysql/my.cnf: Uzaktaki hedeften (db sunucusu) nereye kopyalanacağını gösterir.

    • notify: Restart MySQL => Bu görev bir değişiklik yaptığında (“changed”), aşağıdaki handlersbölümündeki “Restart MySQL” tetiklenecek.

  4. handlers

    • Restart MySQL: Bir “service” modülü ile MySQL servisini yeniden başlatır.

    • Sadece template görevinde gerçekten dosya içeriği değiştiyse (“changed” olarak raporlanırsa) handler tetiklenir.


4. Çalıştırma ve Mantık

ansible-playbook playbook.yml
  • Ansible, config_file.j2 dosyasını okumak için vars (innodb: true, datadir: "/var/lib/mysql") değerlerini şablona uygular.

  • Oluşan render edilmiş metin /etc/mysql/my.cnf olarak db sunucusuna kopyalanır.

    • Örnek final içerik:

      [mysqld]
      datadir=/var/lib/mysql
      innodb_buffer_pool_size=1G
      user=mysql
      port=3306
  • Eğer dosya içerik olarak önceki hâlinden farklıysa (gerçek bir değişiklik olduysa), “changed” olarak işaretlenir, dolayısıyla notify: Restart MySQL devreye girer.

  • Handler, MySQL servisini restarted duruma getirir.

Sistematik Faydası:

  • Şablonun içinde Jinja2 ile “if/for/default vs.” yazabilir, parametrelere göre konfig dosyalarını esnekçe oluşturabilirsiniz.

  • “dosya değişti mi?” kontrolleri ve “servis restart” tetikleme mantığı size ek kod yazmadan, Ansible’ın built-in “change detection” özelliğiyle otomatikleşir.


Özet

Bu örnekte, Ansible template modülü ile bir MySQL konfig dosyasını Jinja2 şablonundan oluşturup hedef sunucuya kopyaladık. Varsayılan ayarlarla ya da playbook içi vars’larla (innodb, datadir gibi) dinamik bir dosya yaratıp, eğer bir değişiklik olduysa MySQL’i otomatik yeniden başlattık.

Özellikle koşullar (if) ve değişkenler ({{ ... }}) sayesinde tek bir .j2 şablon dosyasını birçok farklı senaryoda kullanabilirsiniz. Bu, büyük yapılandırma yönetiminde kod tekrarını azaltır ve yönettiğiniz sistemlerde konsistensi ve kolay bakımı sağlar.

PreviousAnsible CollectionsNextJinja2 Templates for Dynamic Configs

Last updated 10 days ago

Was this helpful?