Home > Mobile >  Include variable name with the item value in ansible
Include variable name with the item value in ansible

Time:06-17

I'm trying to get input from CSV file and then add that as a dynamic inventory for a play, below is the ansible playbook:

---
- hosts: localhost
  vars:
    ansible_user: root
    ansible_password: "User@123"
    csv_file: "/var/lib/awx/projects/patching/server.csv"
  tasks:
    - read_csv:
        key: servername
        path: "{{ csv_file }}"
      register: list

    - debug:
        msg: "{{ item.value.servername }}"
      loop: "{{ list.dict|dict2items }}"
    - add_host:
        name: "{{ item.value.servername }}"
        ansible_user: "{{ ansible_user }}"
        ansible_password: "{{ ansible_password }}"
        groups: patching
      loop: "{{ list.dict|dict2items }}"
- name: test
  hosts: patching
  tasks:
    - shell: hostname
      register: hostname
    - debug: "{{ hostname }}"

This playbook works fine, but I would like make the parameter "key" in the read_csv module as a variable as below and incorporate it with the item value as below, it throws error "as The error was: 'dict object' has no attribute 'column'"

---
- hosts: localhost
  vars:
    ansible_user: root
    ansible_password: "user@123"
    csv_file: "/var/lib/awx/projects/patching/server.csv"
    column: servername
  tasks:
    - read_csv:
        key: "{{ column }}"
        path: "{{ csv_file }}"
      register: list

    - debug:
        msg: "{{ item.value.column }}"
      loop: "{{ list.dict|dict2items }}"
    - add_host:
        name: "{{ item.value.column }}"
        ansible_user: "{{ ansible_user }}"
        ansible_password: "{{ ansible_password }}"
        groups: patching
      loop: "{{ list.dict|dict2items }}"

- name: test
  hosts: patching
  tasks:
    - shell: hostname
      register: hostname
    - debug: "{{ hostname }}"

Need to understand how to incorporate the variable "column" to the item.value.servername change as item.value.column Below is the CSV file:

#cat server.csv 
servername,ip
172.17.92.60,172.17.92.60
172.17.92.38,172.17.92.38
172.17.92.39,172.17.92.39
172.17.92.70,172.17.92.70

CodePudding user response:

try this playbook:

 tasks:
    - read_csv:
        key: "{{ column }}"
        path: "{{ csv_file }}"
      register: list

    - debug:
        msg: "{{ item.value[column] }}"
      loop: "{{ list.dict|dict2items }}"
    - add_host:
        name: "{{ item.value[column] }}"
        ansible_user: "{{ ansible_user }}"
        ansible_password: "{{ ansible_password }}"
        groups: patching
      loop: "{{ list.dict|dict2items }}"
  • Related