3

I need to generate a random 128-bit number and get it's binary representation, b64-encoded.

Sample:

vagrant@ubuntu1804:~$ consul keygen
TUlzi8BWwPQR1zyjR1TiAQ==

in it's b64 decoded form:

vagrant@ubuntu1804:~$ consul keygen | base64 -d|hexdump -C
00000000  46 b8 72 4b ce 9a 2a 14  09 7b 16 51 99 1b 39 e0  |F�rK�.*..{.Q..9�|
00000010

I can generate the large number with random filter:

{{ 340282366920938463463374607431768211456 | random }}

I know I can encode it with b64encode, but have no idea how to convert the number to the binary format.

Misko
  • 1,542
  • 2
  • 19
  • 31

1 Answers1

2

Instead of converting (which is impossible as you can't store/process binary using native Ansible data structures), write a simple filter plugin (filter_plugins/myfilters.py) which would generate the content you want:

import os
import base64


class FilterModule(object):
    def filters(self):
        return {
            'binary_random_b64_encoded': self.binary_random_b64_encoded
        }

    def binary_random_b64_encoded(self, size):
        return base64.b64encode(os.urandom(size)).decode('ascii')

and use it (with the requested size of the binary data):

- debug:
    msg: "{{ 16 | binary_random_b64_encoded }}"
techraf
  • 64,883
  • 27
  • 193
  • 198