Ansible: Generating password with constraints
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,
password_length
: Set the number of characters required in the given password. Here, we are setting to 12.password_specs
: Set required constraints for password being generated. Here, we are setting four constraints —ascii_lowercase
fora-z
,ascii_uppercase
forA-Z
,digits
for0-9
andpunctuation
for including special characters !”#$%&\’()*+,-./:;<=>?@[\\]^_`{|}~. Password lookup plugin uses Pythonstring
lib, so you can also specify constraints form same library such as —ascii_letters
,ascii_lowercase
,ascii_uppercase
,digits
,hexdigits
,octdigits
,printable
,punctuation
,whitespace
.- In the first task of the above playbook, we are setting some Ansible facts such as
password_spec_str
andremaining_password_length
. - 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.
- 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.