Ansible task to strip out data from a file

Viewed 206

A file has the following contents

com.dkr.container.id=a43019cc-d4a4-4acb-83dd-defd76443c6a
com.dkr.container.account=12HJB

I need to fetch a43019cc-d4a4-4acb-83dd-defd76443c6a and write it to a variable using an Ansible task. This value need to be passed to other tasks in the same Ansible file.

Can someone show me the required task to achieve this.

2 Answers

If your file is on the controller, you can use the file lookup to get its content.
If the file is on the node, you will have to use something like the slurp module.

Then, when you have the file content, you can use the regex_search filter to extract your required text.

  1. With the file on the controller:
    - set_fact:
         com_dkr_container_id: >-
           {{ 
             lookup('file', '/path/to/file') 
               | regex_search('com\.dkr\.container\.id=(.*)', '\1') 
               | first 
           }}
    
  2. With the file on the node(s):
    - slurp: 
         src: /path/to/file
       register: file_content
    
    - set_fact:
         com_dkr_container_id: >-
           {{ 
             file_content.content
               | b64decode
               | regex_search('com\.dkr\.container\.id=(.*)', '\1') 
               | first 
           }}
    

This is the job for the ini lookup plugin. See

shell> ansible-doc -t lookup ini

For example, given the file

shell> cat container.properties 
com.dkr.container.id=a43019cc-d4a4-4acb-83dd-defd76443c6a
com.dkr.container.account=12HJB

The playbook

- hosts: localhost
  tasks:
    - set_fact:
        id: "{{ lookup('ini', 'com.dkr.container.id
                type=properties
                file=container.properties') }}"
    - debug:
        var: id

gives

  id: a43019cc-d4a4-4acb-83dd-defd76443c6a

The lookup plugins work on the controller only. If the file is at the remote host fetch it, e.g. given the file

shell> ssh admin@test_11 cat container.properties
com.dkr.container.id=a43019cc-d4a4-4acb-83dd-defd76443c6a
com.dkr.container.account=12HJB

The playbook

- hosts: test_11
  tasks:
    - fetch:
        src: container.properties
        dest: /tmp/fetched
    - set_fact:
        id: "{{ lookup('ini', 'com.dkr.container.id
                type=properties
                file=/tmp/fetched/{{ inventory_hostname }}/container.properties') }}"
    - debug:
        var: id

gives the same result

  id: a43019cc-d4a4-4acb-83dd-defd76443c6a

The playbook above is idempotent. The file will be stored at the controller

shell> tree /tmp/fetched/
/tmp/fetched/
└── test_11
    └── container.properties
Related