Generate unique identifier?

Hi All,

I was wondering if ansible has a way to generate a unique identifier?

Thanks, Mike.

depends on how unique you need it to be, you can create one easily with MAC address, date/time facts and random filter​

Hello!

I was wondering if ansible has a way to generate a unique identifier?

I don’t think Ansible itself has that capability built in. Luckily, you can easily do this yourself. As another response said, it also depends on how unique you want it to be. Just the other day I had to solve that problem as well. I settled for fine-grained time stamp plus random characters, which in my case was guaranteed to be unique enough. For the random characters I ended up taking a recipe I had found somewhere (sorry, can’t find the URL anymore) on how to create a random string, combined it in the shell with the datetime output and phrased this as an Ansible task. Like so:

  • name: Create a unique ID
    shell: echo “date +"%Y%m%d%H%M%S"-$(cat /dev/urandom | tr -cd [:alpha:] | tr ‘[:upper:]’ ‘[:lower:]’ | head -c 4)”
    register: my_unique_id

This takes a datetime stamp and attaches some random letters. You can drop the “date” output and just go with random letters, for example. The “head -c 4” in the end determines how many random letters there will be appended. Just take that echo line and paste it into the shell, experiment around with different variations until you get the ID you want.

Later on in your playbook, you can then refer to the unique ID like so:

  • name: Create a directory named after my unique ID
    file: path=/tmp/{{ my_unique_id.stdout }} state=directory

Juergen

Hi Mike,

From: ansible-project@googlegroups.com [mailto:ansible-project@googlegroups.com] On Behalf Of Mike Trienis
Sent: Saturday, 3 May 2014 7:02 AM

Hi All,

I was wondering if ansible has a way to generate a unique identifier?

Assuming that you are running ansible from a linux system you could always install uuidgen (part of libuuid). On debian-derived systems this then becomes, in ansible-speak (hand-typed - probably will not work as-is :slight_smile: ):

- name: install uuid runtime package on local
  local_action: apt pkg=uuid-runtime state=latest

- name: generate a uuid for something
  local_action: shell uuidgen
  register: my_uuid

# later in the play use my_uuid.stdout as a variable

Hope this is helpful.

Cheers,

Andrew

Thanks for all the responses, they were all very helpful.

If you're on linux you can just use the 'mktemp' utility, which is part of
coreutils.

Though, I guess it’s not idempotent all by itself… You’d still have to store the output in a register, etc…

“Though, I guess it’s not idempotent all by itself”

Easily dealt with :slight_smile:

  • shell: foo

changed_when: False

Running commands that don’t change anything is perfectly fine in the config management world, rather, the concern should be changing things that don’t need to be changed :slight_smile: