Idempotent random port in Ansible

r a v
2 min readMay 18, 2020

--

If the title looks a bit weird, please bear with me a bit longer and read on. The very good Wikipedia states:

Idempotence is the property of certain operations in mathematics and computer science whereby they can be applied multiple times without changing the result beyond the initial application.

As we’re well aware Ansible is idempotent or rather it’s actions are idempotent. Not long ago, I was given a home test for an interview. One of the scenarios was an interesting one which brings us to the title of this post. Here’s the scenario as mentioned.

Your organisation must provide a single web server to host development code for all web developers. You are tasked with writing a playbook to configure this development web server.
The development web server must satisfy several requirements:
The development server configuration matches the production server configuration. The production server is configured using an Ansible role, developed by the organisation's infrastructure team.
Each developer is given a directory on the development server to host code and content. Each developer’s content is accessed using an assigned, nonstandard port.
SELinux is set to enforcing and targeted.

Your playbook will:
Use a role to configure directories and ports for each developer on the web server. You must write this role.
This role has a dependency on a role written by the organisation to configure Apache. You should define the dependency using version v4 of the organisational role. The ULL of the dependency’s
repository is: git@internaltest.example.com:infra/ apache
Write one simple playbook to manage the SELINUX in enforcing mode on all the machine.

The interesting bit was “Each developer’s content is accessed using an assigned, nonstandard port.” So how do we assign a nonstandard port that’s unique to individual developers. Well, you can generate a random number and assign it; But then if we run the playbook again it will change.

So we need a random number that does not change. This excellent SO answer and the related Ansible documentation helped.

The complete playbook along with TestInfra tests to verify the playbook can be found at https://bitbucket.org/kottapar/setup_dev

It has a well-written guide too :-)Feel free to clone and give it a try.

But if you want the TL;DR then here’s how I defined the variable in the roles defaults.

# Generate an idempotent random port number for the dev_user in the range 1024–32767dev_port: “{{ 32767 | random(1024, seed=dev_user) }}”

I’m generating a random port value between 1024 and 32767 and seeding it from the dev_user value. This is the developer’s username that’s entered when the playbook is ran. If the playbook is ran a second time, the corresponding port number for the developer will not change.

Hope this helps. Please leave a comment or clap if you liked this or found this useful.

--

--