Commit 71e69613 authored by onknows's avatar onknows
Browse files

guidelines coding

C2-1630 C2-1628 C2-1629
parent 1f6a9b90
Loading
Loading
Loading
Loading
Loading
+148 −0
Original line number Diff line number Diff line
---
categories: ["Guideline"]
tags: [ansible, loop, loop_control]
title: "Using Labels in Ansible Loops"
linkTitle: "Loop Label"
translate: false
weight: 4
description: >
  Use `loop_control.label` to keep Ansible loop output short and readable when a
  loop iterates over dictionaries or other large values.
---

{{< alert >}}
Use `loop_control.label` when the default loop output would print large or noisy
values, especially dictionaries. Choose a short label that identifies the loop
item clearly without echoing the full object.
{{< /alert >}}

## Problem

When an Ansible task loops over dictionaries or other structured values, the
default output often prints the entire loop item.

This makes task output harder to scan and review. It also adds noise to logs,
especially when the loop item contains nested data such as bindings, options, or
state details.

For operators, this kind of output can reduce confidence in the task run,
because technical and cluttered logging can look like a sign that something is
going wrong. It can also lower perceived implementation quality by making a
correct task look messy, unstructured, or insufficiently deliberate.

For example, output like this is technically correct but unnecessarily verbose:

```text
TASK [c2platform.mw.iis : Create website] *****************************************
ok: [c2d-iis1] => (item={'name': 'HelloWorld', 'physical_path':
'D:/inetpub/wwwroot/HelloWorld', 'application_pool': 'HelloWorld',
'bindings': {'add': [{'ip': '192.168.3.100', 'hostname': 'helloworld.c2platform.org',
'port': 80, 'protocol': 'http'}]}, 'state': 'started'})
```

In most cases, the operator only needs a short identifier such as the website
name and intended state.

## Context

Ansible supports `loop_control.label` to limit what is shown for each loop item
in task output.

This is especially useful when the loop iterates over dictionaries and the task
already accesses only a few fields, for example `item['name']` and
`item['state']`. In those cases, repeating the full dictionary in the log adds
little value.

`loop_control.label` improves readability, but it should stay simple. A label is
most useful when it highlights the field or fields that help an operator quickly
recognize what the task is processing.

This guideline complements [Using item and loop_var in Ansible Loops]({{< relref "/docs/guidelines/coding/item-loop-var" >}}). If a task uses a custom
`loop_control.loop_var`, use that same variable consistently inside `label`.

## Solution

1. Use `loop_control.label` when the default loop output would print large or
   distracting values.
2. Prefer a short, stable identifier such as a name, key, path, or name plus
   state.
3. Do not repeat the whole dictionary inside the label.
4. Keep the label focused on what helps operators read the task output quickly.
5. When the task uses a custom `loop_control.loop_var`, use that variable name
   in the label as well.
6. For simple loops over short scalar values, do not add `label` unless it
   improves the output.

### Benefits

- Makes task output easier to scan.
- Reduces log noise for loops over dictionaries and nested data.
- Helps operators identify the current loop item quickly.
- Keeps loop output focused on the fields that matter most.

## Examples and Implementation

### Use `label` to shorten output for dictionaries

```yaml
- name: Create website
  microsoft.iis.website:
    name: "{{ item['name'] }}"
    site_id: "{{ item['site_id'] | default(omit) }}"
    state: "{{ item['state'] | default(iis_websites_state) }}"
    physical_path: "{{ item['physical_path'] }}"
    application_pool: "{{ item['application_pool'] }}"
    bindings: "{{ item['website_bindings'] | default(omit) }}"
  loop: "{{ iis_websites }}"
  loop_control:
    label: >-
      {{ item['name'] }} →
      {{ item['state'] | default(iis_websites_state) }}
```

This keeps the task output focused on the website name and effective state.

Instead of logging the full dictionary, Ansible can now show a shorter result
such as:

```text
TASK [c2platform.mw.iis : Create website] *****************************************
ok: [c2d-iis1] => (item=HelloWorld → started)
```

### Keep labels short and meaningful

A label should identify the loop item, not restate every field.

```yaml
- name: Configure Apache vhost
  ansible.builtin.debug:
    msg: "Configuring {{ item['servername'] }}"
  loop: "{{ apache_vhosts }}"
  loop_control:
    label: "{{ item['servername'] }}"
```

Here the hostname is enough to recognize the current item.

### Avoid labels that stay too verbose

The following pattern is not recommended because it still logs too much data:

```yaml
- name: Create website
  microsoft.iis.website:
    name: "{{ item['name'] }}"
    state: "{{ item['state'] | default(iis_websites_state) }}"
  loop: "{{ iis_websites }}"
  loop_control:
    label: "{{ item }}"
```

This defeats the purpose of `label`, because it still renders the whole loop
item instead of a short identifier.

## Additional Information

- {{< extlink "https://docs.ansible.com/projects/ansible/latest/playbook_guide/playbooks_loops.html" "Loops  Ansible Community Documentation" >}}
+148 −0
Original line number Diff line number Diff line
---
categories: ["Richtlijn"]
tags: [ansible, loop, loop_control]
title: "Labels gebruiken in Ansible loops"
linkTitle: "Loop label"
weight: 4
description: >
  Gebruik `loop_control.label` om de Ansible loop output kort en leesbaar te houden wanneer een loop over dictionaries of andere grote waarden itereert.
---

{{< alert >}}
Gebruik `loop_control.label` wanneer de standaard loop output grote of rommelige
waarden zou afdrukken, vooral dictionaries. Kies een kort label dat het loop
item duidelijk identificeert zonder het volledige object weer te geven.
{{< /alert >}}

## Probleem

Wanneer een Ansible taak over dictionaries of andere gestructureerde waarden
loopt, drukt de standaard output vaak het volledige loop item af.

Dit maakt de taakoutput moeilijker scanbaar en te beoordelen. Het voegt ook ruis
toe aan logs, vooral wanneer het loop item geneste data bevat zoals bindings,
opties of statusdetails.

Voor operators kan dit soort output het vertrouwen in de taakrun verminderen,
omdat technische en rommelige logging kan lijken op een teken dat er iets
misgaat. Het kan ook de waargenomen implementatiekwaliteit verlagen door een
correcte taak rommelig, ongestructureerd of onvoldoende doordacht te laten
lijken.

Bijvoorbeeld, output zoals dit is technisch correct maar onnodig uitgebreid:

```text
TASK [c2platform.mw.iis : Create website] *****************************************
ok: [c2d-iis1] => (item={'name': 'HelloWorld', 'physical_path':
'D:/inetpub/wwwroot/HelloWorld', 'application_pool': 'HelloWorld',
'bindings': {'add': [{'ip': '192.168.3.100', 'hostname': 'helloworld.c2platform.org',
'port': 80, 'protocol': 'http'}]}, 'state': 'started'})
```

In de meeste gevallen heeft de operator alleen een korte identificatie nodig,
zoals de websitenaam en de beoogde status.

## Context

Ansible ondersteunt `loop_control.label` om te beperken wat voor elk loop item
in de taakoutput wordt getoond.

Dit is vooral nuttig wanneer de loop over dictionaries itereert en de taak
slechts een paar velden benadert, bijvoorbeeld `item['name']` en
`item['state']`. In die gevallen voegt het herhalen van de volledige dictionary
in de log weinig waarde toe.

`loop_control.label` verbetert de leesbaarheid, maar moet eenvoudig blijven. Een
label is het meest nuttig wanneer het de velden benadrukt die een operator
helpen om snel te herkennen wat de taak verwerkt.

Deze richtlijn vormt een aanvulling op [Item en loop_var gebruiken in Ansible
loops]({{< relref "/docs/guidelines/coding/item-loop-var" >}}). Als een taak een
aangepaste `loop_control.loop_var` gebruikt, gebruik diezelfde variabele
consistent binnen `label`.

## Oplossing

1. Gebruik `loop_control.label` wanneer de standaard loop output grote of
   afleidende waarden zou afdrukken.
2. Kies bij voorkeur een korte, stabiele identificatie zoals een naam, sleutel,
   pad of naam plus status.
3. Herhaal niet de hele dictionary binnen het label.
4. Houd het label gericht op wat operators helpt om de taakoutput snel te lezen.
5. Wanneer de taak een aangepaste `loop_control.loop_var` gebruikt, gebruik die
   variabelenaam ook in het label.
6. Voeg bij eenvoudige loops over korte scalaire waarden geen `label` toe,
   tenzij het de output verbetert.

### Voordelen

- Maakt taakoutput gemakkelijker scanbaar.
- Vermindert logruis bij loops over dictionaries en geneste data.
- Helpt operators het huidige loop item snel te identificeren.
- Houdt de loop output gericht op de velden die het belangrijkst zijn.

## Voorbeelden en implementatie

### Gebruik `label` om output voor dictionaries te verkorten

```yaml
- name: Create website
  microsoft.iis.website:
    name: "{{ item['name'] }}"
    site_id: "{{ item['site_id'] | default(omit) }}"
    state: "{{ item['state'] | default(iis_websites_state) }}"
    physical_path: "{{ item['physical_path'] }}"
    application_pool: "{{ item['application_pool'] }}"
    bindings: "{{ item['website_bindings'] | default(omit) }}"
  loop: "{{ iis_websites }}"
  loop_control:
    label: >-
      {{ item['name'] }} →
      {{ item['state'] | default(iis_websites_state) }}
```

Dit houdt de taakoutput gericht op de websitenaam en de effectieve status.

In plaats van de volledige dictionary te loggen, kan Ansible nu een korter
resultaat tonen zoals:

```text
TASK [c2platform.mw.iis : Create website] *****************************************
ok: [c2d-iis1] => (item=HelloWorld → started)
```

### Houd labels kort en betekenisvol

Een label moet het loop item identificeren, niet elk veld herhalen.

```yaml
- name: Configure Apache vhost
  ansible.builtin.debug:
    msg: "Configuring {{ item['servername'] }}"
  loop: "{{ apache_vhosts }}"
  loop_control:
    label: "{{ item['servername'] }}"
```

Hier is de hostnaam voldoende om het huidige item te herkennen.

### Vermijd labels die te uitgebreid blijven

Het volgende patroon wordt niet aanbevolen omdat het nog steeds te veel data logt:

```yaml
- name: Create website
  microsoft.iis.website:
    name: "{{ item['name'] }}"
    state: "{{ item['state'] | default(iis_websites_state) }}"
  loop: "{{ iis_websites }}"
  loop_control:
    label: "{{ item }}"
```

Dit ondermijnt het doel van `label`, omdat het nog steeds het hele loop item
weergeeft in plaats van een korte identificatie.

## Aanvullende informatie

- {{< extlink "https://docs.ansible.com/projects/ansible/latest/playbook_guide/playbooks_loops.html" "Loops  Ansible Community Documentation" >}}
 No newline at end of file