Ansible - Read a file, extract specific line, extract a column and assign to variable

Viewed 1607

I need some help with extracting a specific line from a file and then extracting a column, assign it to a variable and then use that variable in the next task.

I have the file with this format on the confluent broker server

Save the key. It cannot be retrieved later.
+------------+----------------------------------------------+
| Enc Key | omykeyvaluecontinuousstringgoeshereandmakelong= |
+------------+----------------------------------------------+

I am trying to write Ansible task that will read the third line and then extract the key into a variable which I need to export as an environment variable in the task. In the next task I will be executing a confluent command as a shell command.

I tried something like below, but it doesn't work - I get error

vars:
    ansible_ssh_extra_args: "-o StrictHostKeyChecking=no"
    ansible_host_key_checking: false
    contents: "{{ lookup('file', '/etc/kafka/info.txt') }}"
    contents2: "{{ lookup('file', '/etc/kafka/info.txt').splitlines() }}"

- name: set fact
  set_fact:
    extract_key: "{{ contents.split('\n')[2] }}"

- name: Display output
  debug: msg="{{ extract_key }}"

And then extract the key value from extract_key variable

How can I achieve this?

Thank you

2 Answers

The task below does the job

    - set_fact:
        extract_key: "{{ contents.split('\n').2.split('|').2|trim }}"

gives

  extract_key: omykeyvaluecontinuousstringgoeshereandmakelong=

You can use this filter if only text lines are fixed:

- name: capturing Key
  shell: echo {{ contents }} | head -3 | tail -1 | sed 's/|/\n/g' | sed -n 3p
  register: extract_key

- name: Display output
  debug: msg="{{ extract_key.stdout }}"

This returns omykeyvaluecontinuousstringgoeshereandmakelong=

Related