💻
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
    • Facts
    • Configuration files
    • Install required packages
    • SSH keys to managed nodes
    • Adhoc Commands
    • Commands with shell scripts
    • Privilege Escalation
    • Frequently Asked Questions
    • Additional Modules
    • Variable Precedence
    • Variable Scope
    • Use variables to retrieve the results of running commands
    • Magic Variables
    • Jinja2 Basics
    • Jinja2 in Ansible
    • Templating use cases
Powered by GitBook
On this page
  • 1. Değişken (Variable) Nedir?
  • 2. Inventory Dosyasında Değişken Kullanımı
  • 3. Playbook’ta Değişken Tanımlama
  • 4. Daha Büyük Senaryolar: Varsayılan Değerleri Ayırma
  • Grup Değişkenleri (group_vars/web.yml)
  • 5. Değişkenleri Kullandığımız Tipik Örnekler

Was this helpful?

  1. Ansible

Ansible Variables

1. Değişken (Variable) Nedir?

Ansible’da değişkenler, her sunucuda veya her görevde farklı olması gereken değerleri saklar. Aynı Playbook ile 100 farklı sunucuda patch işlemi yapacaksanız, bu 100 sunucunun host ismi, kullanıcı adı, parola veya IP adresi gibi değişen bilgilerini değişkenler aracılığıyla yönetirsiniz. Playbook’u sadece bir kere yazar, değişen kısımları değişken tanımlarıyla (envanter veya var dosyaları) kontrol edersiniz.


2. Inventory Dosyasında Değişken Kullanımı

Daha önce inventory (envanter) dosyasında ansible_host, ansible_connection, ansible_ssh_pass vb. değişkenler gördük:

inventory.ini:

[web]
Web1 ansible_host=server1.company.com ansible_connection=ssh ansible_ssh_pass=P@ssW http_port=8081 snmp_port=161-162

[db]
db ansible_host=server2.company.com ansible_connection=winrm ansible_ssh_pass=P@s

Burada Web1 için:

  • ansible_host=server1.company.com

  • ansible_connection=ssh

  • ansible_ssh_pass=P@ssW

  • http_port=8081

  • snmp_port=161-162 gibi beş değişken tanımlamış olduk.

Not: Sadece Web1 satırında http_port ve snmp_port tanımladığımız için, bu değişkenler yalnızca Web1 adlı host için geçerli olur.

use_inventory_vars.yml:

- name: Demo Playbook using inventory variables
  hosts: web  # "web" grubunu hedefliyoruz
  gather_facts: no  # Örnek olarak hız için kapattık, isteğe bağlı

  tasks:
    - name: Show the http_port and snmp_port from inventory
      debug:
        msg: >
          HTTP Port is {{ http_port }}
          SNMP Port is {{ snmp_port }}

    - name: Use the http_port in a mock firewall task
      firewalld:
        port: "{{ http_port }}/tcp"
        permanent: true
        state: enabled

Açıklamalar

  1. hosts: web

    • Bu playbook, envanter dosyasında [web] grubunda tanımlı olan tüm hostlara uygulanır (yani Web1).

  2. Değişken Kullanımı: {{ http_port }}

    • {{ }} (Jinja2 templating) ile inventory.ini dosyasında “Web1” satırında tanımlanmış http_port ve snmp_port değerlerini çağırıyoruz.

    • Örneğin debug modülü, terminalde “HTTP Port is 8081, SNMP Port is 161-162” şeklinde bir mesaj basar.

  3. firewalld: Örneği

    • Burada “port: "{{ http_port }}/tcp"” diyerek, envanterden gelen http_port değerini (8081) kullanıyoruz.

    • Böylece portu sabit kodlamak yerine envanterde değiştirerek daha esnek yönetim sağlıyoruz.


3. Playbook’ta Değişken Tanımlama

Playbook içinde, vars anahtar kelimesiyle değişken tanımlayabilirsiniz:

- name: Add DNS server to resolv.conf
  hosts: localhost
  vars:
    dns_server: 10.1.250.10  # Burada değişken tanımladık
  tasks:
    - lineinfile:
        path: /etc/resolv.conf
        line: "nameserver {{ dns_server }}"  # Değişkeni kullanıyoruz
  1. Tanımlama: vars: altına anahtar: değer şeklinde yazarız.

  2. Kullanım: {{ ... }} (Jinja2 templating) ile değişkenin değerini yerleştiririz.

  3. Neden Faydalı? Değeri değiştirmek istediğimizde sadece vars: bölümünü güncelleriz; Playbook’un kod kısmına dokunmamız gerekmez.


4. Daha Büyük Senaryolar: Varsayılan Değerleri Ayırma

Özellikle port, IP blokları gibi makineye özgü değerleri envantere yazabilirsiniz. Büyük projelerde, her host veya her grup için değişkenler ayrı YAML dosyalarında saklanır (host_vars, group_vars dizinlerinde).

Proje dizininiz şu şekilde olabilir:

.
├── inventory.ini
├── host_vars
│   └── web1.yml
└── playbook.yml
  • inventory.ini: Sunucu(lar)ı tanımladığınız envanter dosyası.

  • host_vars/web1.yml: web1 adlı host’a özel değişkenlerin saklandığı dosya.

  • playbook.yml: Playbook’unuz.

Önemli Nokta: host_vars altındaki YAML dosyasının adı, envanterdeki host ismi ile birebir aynı olmalıdır (web1.yml↔ web1).

Inventory (inventory.ini)

[web]
web1 ansible_host=server1.company.com ansible_connection=ssh
  • [web] grubuna web1 adlı host dahil ediyoruz.

  • Host’a dair temel bağlantı bilgilerini (IP, SSH vb.) burada tutuyoruz.

Host-Specific Vars (host_vars/web1.yml)

http_port: 8081
snmp_port: 161-162
inter_ip_range: 192.0.2.0
  • web1 host’una özgü değişkenleri burada tanımladık (port bilgileri, IP range vb.).

  • Playbook, hosts: web (veya doğrudan hosts: web1) dendiğinde bu dosyadaki değişkenler otomatik yüklenecek.

Playbook (playbook.yml)

- name: Demo using host_vars
  hosts: web   # "web" grubuna ait tüm host’lar (web1) hedeflenir
  gather_facts: no

  tasks:
    - name: Display Host Vars
      debug:
        msg:
          - "HTTP Port is {{ http_port }}"
          - "SNMP Port is {{ snmp_port }}"
          - "Internal Range: {{ inter_ip_range }}"

Nasıl Çalışıyor?

  1. Ansible, hosts: web dediğimizde önce inventory.ini içindeki web grubunu bulur.

  2. web grubunda web1 adlı host olduğu için, Ansible “web1” ismini host_vars dizinine bakarak arar (host_vars/web1.yml).

  3. web1.yml dosyasındaki değişkenleri (ör. http_port) yükler.

  4. {{ http_port }} gibi ifadelere denk geldiğinde bu değerleri kullanır.

Playbook’u Çalıştırma

ansible-playbook -i inventory.ini playbook.yml
  • -i inventory.ini: Varsayılan envanter /etc/ansible/hosts değil, inventory.ini dosyamızı kullandığımızı belirtir.

  • Ansible, web1.yml içindeki değişkenlerle playbook.yml içindeki {{ http_port }} vb. yerleri doldurur ve işlemleri uygular.

Sonuç

  • Inventory’de yalnızca host isimlerini tanımlıyor, temel bağlantı ayarlarını tutuyoruz (IP, SSH vs.).

  • host_vars (veya group_vars) klasörlerinde, her host (veya grup) için ayrıntılı değişkenleri saklıyoruz.

  • Playbook, hosts: satırında eşleşen hostların host_vars dosyalarındaki değişkenleri otomatik olarak yüklüyor. Bu sayede değişken yönetimi daha düzenli ve ölçeklenebilir hâle geliyor.

Yukarıda host_vars kullanarak, bir host için değişkenleri kullanmayı gördük. Aynı şekilde, aşağıda, group_vars klasörünü kullanarak bir grup için ortak değişkenleri nasıl tanımlayabileceğinize dair basit bir örnek gösteriyorum. Bu yapı sayesinde, aynı gruba ait tüm makineler, ortak değişkenleri otomatik olarak yükleyebilir.

Klasör Yapısı

Proje dizininiz şu şekilde olabilir:

.
├── inventory.ini
├── group_vars
│   └── web.yml
└── playbook.yml
  • inventory.ini: Sunucu(lar)ı ve grupları tanımladığınız envanter dosyası.

  • group_vars/web.yml: web adlı grup için değişkenlerin saklandığı dosya.

  • playbook.yml: Playbook’unuz.

Önemli Nokta: group_vars altındaki YAML dosyasının adı, envanterdeki grup ismi ile birebir aynı olmalıdır (web.yml ↔ [web] grubu).

Inventory (inventory.ini)

[web]
web1 ansible_host=web01.example.com ansible_connection=ssh
web2 ansible_host=web02.example.com ansible_connection=ssh

[db]
db1 ansible_host=db01.example.com ansible_connection=ssh
  • [web] grubunda web1 ve web2 adlı iki host var.

  • [db] grubunda db1 adlı tek host bulunuyor.

Grup Değişkenleri (group_vars/web.yml)

http_port: 8081
snmp_port: 161-162
inter_ip_range: 192.0.2.0
  • Bu dosya, web grubuna ait ortak değişkenleri içeriyor.

  • http_port, snmp_port ve inter_ip_range bu gruba bağlı tüm makineler (web1 ve web2) tarafından otomatik yüklenecek.

Playbook (playbook.yml)

- name: Demo using group_vars
  hosts: web   # "web" grubuna ait tüm host’lar hedeflenir
  gather_facts: no

  tasks:
    - name: Display group_vars for the web group
      debug:
        msg:
          - "HTTP Port is {{ http_port }}"
          - "SNMP Port is {{ snmp_port }}"
          - "Internal Range: {{ inter_ip_range }}"

Nasıl Çalışır?

  1. hosts: web dediğimizde Ansible, envanterde [web] grubundaki tüm hostları (web1, web2) hedefler.

  2. Ansible aynı isimli group_vars/web.yml dosyasını otomatik olarak arayıp yükler.

  3. Bu dosyadaki değişkenler (http_port, snmp_port, inter_ip_range), playbook içinde her bir host için geçerli olur.

  4. {{ http_port }} gibi değişken çağrılarında bu değerler kullanılır.

Playbook’u Çalıştırma

ansible-playbook -i inventory.ini playbook.yml
  • -i inventory.ini: Varsayılan dışındaki envanter dosyasını işaret eder.

  • Ansible, [web] grubuna dahil olan hostlara gider ve group_vars/web.yml içindeki değişkenleri kullanır.

Sonuç

  • group_vars’ın avantajı, gruplara ait ortak değişkenleri tek bir yerde toplayarak bakım kolaylığı sağlamasıdır.

  • Yeni bir makine web grubuna eklendiğinde, group_vars/web.yml dosyasındaki değişkenleri otomatik olarak devralır.

  • Büyük ortamlarda, farklı gruplara (örneğin [db], [cache], [loadbalancer]) özel değişkenler için benzer şekilde group_vars/db.yml, group_vars/cache.yml gibi dosyalar oluşturulabilir.

Bu şekilde, group_vars klasörü üzerinden her gruba ait değişkenleri toplu ve düzenli halde yönetebilirsiniz.


5. Değişkenleri Kullandığımız Tipik Örnekler

5.1 DNS Eklemek

  • Tek satırda “DNS IP” sabit yazmak yerine, dns_server değişkenini vars: veya envanterde tanımlarsınız.

  • lineinfile modülü ile nameserver {{ dns_server }} satırını ekler veya değiştirirsiniz.

5.2 Firewall Ayarları

Aşağıdaki örnekte, port değerlerini envanter/var dosyasından çekiyoruz ve Jinja2 ile yerleştiriyoruz:

- name: Set Firewall Configurations
  hosts: web
  tasks:
    - firewalld:
        port: "{{ http_port }}/tcp"
        permanent: true
        state: disabled
    - firewalld:
        port: "{{ snmp_port }}/udp"
        permanent: true
        state: disabled
    - firewalld:
        source: "{{ inter_ip_range }}/24"
        zone: internal
        state: enabled
  • http_port, snmp_port, inter_ip_range gibi değişkenler ya inventory’de ya da web.yml dosyasında tanımlanmıştır.

  • Böylece snmp_port bir anda 161-162 yerine 10161-10162 olsaydı, sadece var dosyasını güncellemek yeter.


Özet

  • Envanter Dosyasında Değişken: alias ansible_host=... http_port=... gibi yazılır, her host veya grup bazında bilgi tutar.

  • Playbook’ta vars:: Daha küçük, hızlı tanımlamalar için idealdir.

  • Ayrı Dosyalar (host_vars / group_vars): Çok sayıda değişkeni düzenli saklamak için en iyi yöntem.

  • Kullanırken: {{ variable_name }} (Jinja2).

  • Faydası: Daha dinamik, esnek, tekrar kullanılabilir ve bakımı kolay Ansible kodu elde edersiniz.

Bu temelleri anladıktan sonra, vars_files, group_vars/host_vars gibi yaklaşımlarla çok daha düzenli ve ölçeklenebilir playbook’lar oluşturabilirsiniz.

PreviousInventory FormatsNextVariable Types

Last updated 1 month ago

Was this helpful?