# Loops और Conditionals — Ansible: Playbooks से Servers का Automation

Source: https://www.geekswithgeeks.com/hi/ansible/flow-loops-when

> Task को सूची पर loop से दोहराएँ और when से छोड़ें।

## loop और when

`loop:` सूची के हर item के लिए task एक बार चलाता है और मौजूदा मान को `item` के रूप में देता है। `when:` task तभी चलाता है जब शर्त सही हो; वरना नतीजा **skipping** होता है। शर्त बिना braces के लिखी Jinja2 expression होती है, जैसे `env == "production"` या `ansible_os_family == "Debian"`। शर्तों को `and`, `or` और `not` से जोड़ें।

## तय करें, दोहराएँ, प्रतिक्रिया दें

शर्तें, loops, handlers और tags playbooks को scripts बनाए बिना तर्क देते हैं।

![तीन साधन: when, loop, notify।](assets/figures/ansible/section-4-map.svg) — चित्र 4.1 — when, loop और notify।

## Loop और skip, चलाकर

मैंने `vars.yml` (पिछले खंड में दिखाई) अपने डिफ़ॉल्ट `env: staging` के साथ चलाई: loop तीन installs छापता है, और केवल-production वाला task छोड़ा जाता है।

```bash
ansible-playbook -i inventory.ini vars.yml
```

Output:

```
ok: [web1] => (item=git) => {
    "msg": "install git"
ok: [web1] => (item=curl) => {
    "msg": "install curl"
ok: [web1] => (item=nginx) => {
    "msg": "install nginx"
skipping: [web1]
```

## ज़रूरत से ज़्यादा script न बनाएँ

Playbook नेस्टेड शर्तों से भरी हो तो उसे roles में बाँटने या अंतर को variables से व्यक्त करने पर विचार करें। जटिल तर्क परखना और review करना कठिन है।

**Quiz:** `when:` शर्त ग़लत होने पर क्या नतीजा दिखता है?

- [ ] changed
- [x] skipping
- [ ] failed
- [ ] unreachable

*Answer:* skipping. जिस task की शर्त ग़लत हो वह उस host के लिए छोड़ा जाता है।
