Generate group_var file from Ansible playbook

Hello,

I need to use an Ansible playbook to dynamically generate Ansible group_var type file. Here is my inventory file:

[group1]
server1.example.com
server2.example.com

[group2]
server3.example.com
server4.example.com

The generated mygroupvars file is expected to be:

group1_var: xyzabcdefghi
group2_var: abcejrje2ljree

The random string is produced by dd command like below:

dd if=/dev/urandom count=1 2>/dev/null | uuencode -m - | sed -ne 2p | cut -c -20 | perl -p -i -e ‘s/\+/x/g’ | perl -p -i -e ‘s/\//L/g’

uuencode is from sharutils package on CentOS 7

Here is my playbook:

  • name: dummy
    hosts: localhost
    gather_facts: no

tasks:

  • name: create file
    file:
    dest: mygroupvars
    state: touch
    delegate_to: localhost

  • name: Generate random string
    shell: “dd if=/dev/urandom count=1 2>/dev/null | uuencode -m - | sed -ne 2p | cut -c -20 | perl -p -i -e ‘s/+/x/g’ | perl -p -i -e ‘s///L/g’”
    register: op

  • name: debug
    debug:
    msg: “{{ op }}”

  • name: append
    lineinfile:
    dest: mygroupvars
    line: “{{ op.stdout_lines }}”
    insertafter: EOF
    delegate_to: localhost

This playbook only generates one random string, and writes it to mygroupvars file. I need to loop through inventory file, based on number of groups in inventory file, generate the same number of random string matching number of groups, and write them all to mygroupvars file using the group_var file format. It is key/value pair. The key contains group name with suffix _var. The values come from random string generated.

How can I accomplish it?

Thank you!

  • Xinhuan

Try this single task instead (I used some slightly simpler logic for
random generation):

- name: dummy
  hosts: localhost
  gather_facts: no

  tasks:

    - name: Populate random values for each group
      copy:
        content: |
          {% for group in (groups.keys() | difference(['all', 'ungrouped'])) %}
          {{ group }}_var: {{ lookup('pipe', 'dd if=/dev/urandom
bs=256 count=2 2>/dev/null | LC_ALL=C tr -cd "[:alnum:]" | head -c
${1-64}') }}
          {% endfor %}
        dest: mygroupvars