Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Please explain usage of "item" in Ansible

Tags:

ansible

I found some AWS Ansible code using word "{{ item.id }}" or {{ item.sg_name }}.

I do not understand how "item" command works.

like image 981
Sumonta Naskar Avatar asked Oct 13 '17 06:10

Sumonta Naskar


People also ask

How do you use items in Ansible?

NOTE: If an item has a nested list, Ansible will flatten it but not recursion. To use the with_items plugins, use the with_items keyword in a playbook and pass a list of items under it. You can then call each item within the specified list and perform the required operations.

How do you use variables in Ansible?

You can define these variables in your playbooks, in your inventory, in re-usable files or roles, or at the command line. You can also create variables during a playbook run by registering the return value or values of a task as a new variable.

Why loops are used in Ansible?

Ansible loop is used to repeat any task or a part of code multiple times in an Ansible-playbook. It includes the creation of multiple users using the user module, installing multiple packages using apt or yum module or changing permissions on several files or folders using the file module.

What are different types of variables in Ansible?

Variable Scopes Ansible has 3 main scopes: Global: this is set by config, environment variables and the command line. Play: each play and contained structures, vars entries, include_vars, role defaults and vars. Host: variables directly associated to a host, like inventory, facts or registered task outputs.


Video Answer


1 Answers

item is not a command, but a variable automatically created and populated by Ansible in tasks which use loops.

In the following example:

- debug:
    msg: "{{ item }}"
  with_items:
    - first
    - second

the task will be run twice: first time with the variable item set to first, the second time with second.

Further, if elements of the loop were dictionaries, you could refer to their keys using the dot notation as in your example:

- debug:
    msg: "{{ item.my_value }}"
  with_items:
    - ny_element: first
      my_value: 1
    - my_element: second
      my_value: 2
like image 146
techraf Avatar answered Oct 25 '22 09:10

techraf