Ansible: Generating password with constraints

Abhijeet Kasurde
2 min readAug 11, 2020

--

If you want to create a password with constraints like at least one uppercase, one lowercase, one punctuation and one digits, you can use following playbook.

---- hosts: localhost
vars:
password_length: 12
password_specs:
- digits
- ascii_lowercase
- ascii_uppercase
- punctuation
tasks:
- name: House keeping stuff
set_fact:
remaining_password_length: "{{ password_length - password_specs | length }}"
password_spec_str: "{{ password_specs | join(',') }}"
- name: Generate password with required constraints
set_fact:
pwd_pool: "{{ pwd_pool | default([]) + [lookup('password', '/dev/null length=1 chars=' ~item)]}}"
loop: "{{ password_specs }}"
- name: Create required length of password
debug:
msg: "{{ pwd_pool | join('') + lookup('password', '/dev/null length=' ~ remaining_password_length ~ ' chars=' ~ password_spec_str )}}"

Here,

  1. password_length : Set the number of characters required in the given password. Here, we are setting to 12.
  2. password_specs : Set required constraints for password being generated. Here, we are setting four constraints — ascii_lowercase for a-z , ascii_uppercase for A-Z , digits for 0-9 and punctuation for including special characters !”#$%&\’()*+,-./:;<=>?@[\\]^_`{|}~. Password lookup plugin uses Python string lib, so you can also specify constraints form same library such as — ascii_letters, ascii_lowercase, ascii_uppercase, digits, hexdigits, octdigits, printable, punctuation, whitespace .
  3. In the first task of the above playbook, we are setting some Ansible facts such as password_spec_str and remaining_password_length .
  4. Second task of the playbook will generate password with the given constraints. Here, we specified four constraints so we will have a password with length four. This will make sure that we fulfill the given constraints for the generated password.
  5. Third task will fill the remaining characters in the given password. Since last task generated only four chars and required length of password is 12. We need to 8 characters.

And, you are done. Please let me know if you find this useful and implemented this in your playbook.

--

--