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
On Wed, 16 Sep 2020 at 21:14, [email protected]
<[email protected]> wrote:
>
> 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
>
> --
> You received this message because you are subscribed to the Google Groups
> "Ansible Project" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/ansible-project/f40ff918-de62-4049-a075-a61ff787140dn%40googlegroups.com.
--
Dick Visser
Trust & Identity Service Operations Manager
GÉANT
--
You received this message because you are subscribed to the Google Groups
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/ansible-project/CAL8fbwO9Gjsuo0XQyAsCMP5uwoUiism0cXNo-0JZAwgXiMNL7A%40mail.gmail.com.