Check if password matches condition

Viewed 47

I am getting user input for a password in my Ansible task. This user input is passed through command to 'password variable'. I want to check if given password matches below condition:

  • length greater than 8
  • password should contain only printable ASCII chars

I tried something like this :

- fail: msg="Password validation failed" 
  when: password | default('') | length <= 0 | chars = ascii_letters

This is not working.

If I am using fail module only for password non empty and length check, it is working.

- fail: msg="Password validation failed" 
  when: password | default('') | length <= 0 | chars = ascii_letters
1 Answers

To check if a string contains only ASCII character, the best would be to use a regular expression, which you can assert with the regex test.

As regex are pretty powerful, you could also bake your character limitation in it.

Here would be a task achieving this:

- name: Assert a string of 8+ ASCII char
  assert:
    that:
      - password is string
      - password is regex('^[\x00-\x7F]{8,}$')

And some results based on use cases:

  • errors if we do not send anything as --extra-vars
    fatal: [localhost]: FAILED! => changed=false 
      assertion: password is string
      evaluated_to: false
      msg: Assertion failed
    
  • errors if we pass a too short password: --extra-vars "password=1234567"
    fatal: [localhost]: FAILED! => changed=false 
      assertion: password is regex('^[\x00-\x7F]{8,}$')
      evaluated_to: false
      msg: Assertion failed
    
  • also errors in the regex if we pass a non-ASCII char: --extra-vars "password=1234567é"
    fatal: [localhost]: FAILED! => changed=false 
      assertion: password is regex('^[\x00-\x7F]{8,}$')
      evaluated_to: false
      msg: Assertion failed
    
  • pass the assertion with --extra-vars "password=12345678"
    ok: [localhost] => changed=false 
      msg: All assertions passed
    
Related