Module uri - Image to base64 String for JSON object

Hi community,

maybe one of you have an nice idea how to solve my problem.

I want to transfer a logo (jpg) over the ansible tower api “api/v2/settings/ui/”.

`

  • name: Import over API
    uri:
    url: “{{ api_url }}”
    user: “{{ username }}”
    password: “{{ password }}”
    method: PATCH
    body: “{{ lookup(‘template’, ‘logo.j2’) }}”
    force_basic_auth: yes
    body_format: json
    status_code: “200,201”
    validate_certs: no
    `

The template “logo.j2” looks like this:

{ "CUSTOM_LOGO": "data:image/jpeg;base64,/9j/4AAQSkZ.......AKKKKAP/2Q==" }

To get the base64 string I uploaded the image with the Ansible-Tower GUI and call the API GET method. An alternative is to use this website: https://www.base64-image.de/

My goal is to encode the image with ansible or with a jinja2 filter like this:

`
{
“CUSTOM_LOGO”: “{{ lookup(‘file’, ‘image.jpg’) | b64encode }}”
}

`

Thanks for your support.

Alexander

This list for Ansible only and not Tower.
For help with Tower contact RedHat support.

Hi Kai,

its not an Ansible Tower question. Is general Ansible.

I want to encode a jpg image to base64 to use this image in a JSON object.

This JSON object I want to transfer as body with the Ansible module uri.

Thanks,

Alexander

Hi Kai,

its not an Ansible Tower question. Is general Ansible.

I'm sorry, probably read it to fast and jumped to conclusions.

I want to encode a jpg image to base64 to use this image in a JSON object.
This JSON object I want to transfer as body with the Ansible module uri.

The b64decode in Ansible can only handle plain text/ascii, for binary date it gives corrupt result so my hunch that b64encode does the same and you need to use base64 command with command/shell module.

Hi,

here is my solution:

`

  • name: Get base64 string
    shell: “/usr/bin/base64 {{ role_path }}/files/{{ ansible_tower_logo_filename }} | tr -d ‘\n’”
    delegate_to: 127.0.0.1
    register: base64_string

  • name: debug base64 string
    debug:
    var: base64_string
    verbosity: 3

  • name: Show template
    debug:
    msg: “{{ lookup(‘template’, ‘ui.j2’) | to_nice_json }}”
    verbosity: 2

  • name: Import over API
    uri:
    url: “{{ api_url }}”
    user: “{{ ansible_tower_inventory_admin_username }}”
    password: “{{ ansible_tower_inventory_admin_password }}”
    method: PATCH
    body: “{{ lookup(‘template’, ‘ui.j2’) }}”
    force_basic_auth: yes
    body_format: json
    status_code: “200,201”
    validate_certs: no
    `

Here the content of the file ui.j2:

{ "CUSTOM_LOGO": "data:image/jpeg;base64,/{{ base64_string.stdout }}", "CUSTOM_LOGIN_INFO": "{{ ansible_tower_login_info_message | default('') }}" }

Thanks for your help
Alexander