Sobes.tech
Junior — Middle

What is the difference between using var and for keys in Ansible when writing a playbook?

sobes.tech AI

Answer from AI

In Ansible, the vars key is used to define variables that will be available in the playbook or in a specific task. These are static values that can be used for parameterization.

The with_items key (not for) is used to organize a loop — repeating a task for each element in a list.

Example of using vars:

- hosts: all
  vars:
    package_name: nginx
  tasks:
    - name: Install package
      apt:
        name: "{{ package_name }}"
        state: present

Example of using a loop with with_items:

- hosts: all
  tasks:
    - name: Install multiple packages
      apt:
        name: "{{ item }}"
        state: present
      with_items:
        - nginx
        - curl
        - git

Thus, vars sets values, and with_items allows repeating a task for each list element.