متقدم
البحث فيأدلة «كيف»
طريقة البحث
  • اكتب المهمة بكلماتك (find port، open firewall، disk full) أو الصق رسالة الخطأ بين علامتي تنصيص.
  • اختر «الإجابة السريعة» لترى الأوامر فقط، أو مجالًا لتبقى في مجال واحد.
  • "كلمتان" تجد العبارة بالضبط.
  • الكلمات العادية تجد الأسماء والنصوص والأمثلة.
  • ↑ ↓ للتنقل · Enter للفتح · Esc للإغلاق · / للبحث
جرّب:

كيف 165IaC · Ansible

How to use facts and conditions in Ansible

One playbook should work on RHEL and Ubuntu, on VMs and bare metal, in dev and prod. Ansible facts tell you about each host (OS, version, memory, IPs), and conditions (when:) run tasks only where they fit. This how-to reads facts, branches on the OS family, loads per-OS variables, reacts to command results, and speeds up runs that do not need facts.

  • 5 الدروس
  • 1 الأوامر

هذا الجزء لم يُترجم بعد. أنت ترى النص الإنجليزي.

$ مستخدم عادي# بصلاحية root (أو مع sudo)

165.1

The quick answer

ansible web1 -i inventory.ini -m ansible.builtin.setup -a 'filter=ansible_distribution*'
tasks/main.yml (part)
- name: Open HTTP on RHEL (firewalld)
  ansible.posix.firewalld:
    service: http
    permanent: true
    immediate: true
    state: enabled
  when: ansible_facts['os_family'] == "RedHat"
 
- name: Open HTTP on Ubuntu (UFW)
  community.general.ufw:
    rule: allow
    port: "80"
    proto: tcp
  when: ansible_facts['os_family'] == "Debian"

الأوامر في هذا الدرس

165.2

Step by step

  1. Facts you use most:
FactExample value
ansible_facts['os_family']RedHat, Debian
ansible_facts['distribution'] / ['distribution_major_version']RedHat / 9, Ubuntu / 24
ansible_facts['memtotal_mb']7821
ansible_facts['processor_vcpus']4
ansible_facts['default_ipv4']['address']10.0.1.11
ansible_facts['virtualization_type']kvm, VMware
  1. **Per-OS variables instead of many when:** — one vars file per family:
vars/RedHat.yml
chrony_service: chronyd
firewall: firewalld
vars/Debian.yml
chrony_service: chrony
firewall: ufw
tasks/main.yml (part)
- name: Load OS-specific variables
  ansible.builtin.include_vars: "{{ ansible_facts['os_family'] }}.yml"
  1. Conditions — combine with and/or, lists mean AND:
tasks/main.yml (part)
- name: Tune for big servers only
  ansible.posix.sysctl:
    name: vm.swappiness
    value: "10"
  when:
    - ansible_facts['memtotal_mb'] > 16000
    - env == "prod"
  1. React to a command result — register, then decide; tell Ansible what "changed" and "failed" mean:
tasks/main.yml (part)
- name: Is the app already migrated?
  ansible.builtin.command: /opt/shop/bin/migrate --status
  register: mig
  changed_when: false
  failed_when: mig.rc not in [0, 3]
 
- name: Run migrations
  ansible.builtin.command: /opt/shop/bin/migrate --apply
  when: mig.rc == 3
  1. Speed: facts take time on every host. Turn them off for plays that do not need them, or collect only a subset:
site.yml (part)
- hosts: all
  gather_facts: false

(Or gather_subset: [min]; fact caching in ansible.cfg for big inventories.)

  1. Test the logic with --check --diff and -v; ansible HOST -m setup shows what a host really reports.

الأوامر في هذا الدرس

165.3

Check that it worked

A run on a RHEL and an Ubuntu host each executes only the tasks for its OS (others show skipping), and a second run shows changed=0.

165.4

Common problems

ProblemCauseFix
'ansible_facts' is undefined / missing factgather_facts: false in that play.Turn facts on, or run setup in a task first.
Condition always falseWrong case/value (Redhat vs RedHat).Print the fact with setup; copy the exact value.
Comparing a version as text"10" < "9" as strings.ansible_facts['distribution_major_version'] | int >= 9.
Task always changedcommand without changed_when.changed_when: false for checks.
include_vars file not foundNo file for that OS family.Add the file, or a default with first_found.
Old style ansible_distribution vs ansible_facts[...]Both work.Prefer ansible_facts['...'] (clear and future-proof).

165.5

Go further

1Why load per-OS vars files instead of writing when: on every task?

The tasks stay the same; only the values (package and service names) change per OS.

2Why use changed_when: false on a check command?

A read-only check should never report a change.

الأوامر في هذا الدرس

كل الأوامر في هذا الفصل