user3511320
user3511320

Reputation: 129

Ansible Read csv file and encrypt passwords, output of command to file

I have a csv file containing ip addresses and passwords. These passwords need to be encrypted and written to a file.

This is what I have tried so far:

- name: Read csv file
  read_csv:
    path: files/ww.csv
    fieldnames: ip,password
    delimiter: ','
  register: routers
  delegate_to: localhost

- name: encrypt password
  command: "ansible-vault encrypt_string --vault-password-file password '{{ router.password }}' --name 'password'"
  loop: "{{ routers.list }}"
  loop_control:
    loop_var: router
  register: "output"
  delegate_to: localhost

- name: write file
  copy:
     content: "{{ output.stdout }}"
     dest: "/tmp/{{ router.ip }}.yaml"
  loop: "{{ routers.list }}"
  loop_control:
    loop_var: router
  delegate_to: localhost

I want to use output.stdout but I get the following error:

TASK [robustel : write file] *********************************************************************************************************************************
fatal: [10.41.1.161]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'stdout'\n\nThe error appears to be in '/ansible/roles/routers/tasks/create_var_files.yaml': line 20, column 3, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n- name: write file\n  ^ here\n"}

How can I solve this?

Upvotes: 0

Views: 261

Answers (1)

Zeitounator
Zeitounator

Reputation: 44808

You are registering a variable on a task with a loop. This changes the structure of the data as described in the documentation. Debugging output would have given you a clue.

output.results is a list where each element contains a stdout key (e.g. the first one being output.results.0.stdout). Moreover, each element also contains an item key containing the original element in the loop that was registered.

Modifying your last task like below should give you the expected result:

- name: write file
  copy:
    content: "{{ output_result.stdout }}"
    dest: "/tmp/{{ output_result.item.ip }}.yaml"
  loop: "{{ output.results }}"
  loop_control:
    loop_var: output_result
  delegate_to: localhost

Upvotes: 1

Related Questions