1

I need to restrict a variable vm_name, in my playbook, to 15 characters, [0-9], [a-z], [A-Z], -_, no special characters like #$%*&.
How can I achieve this?

- name: Set Vars conditions
  hosts: localhost
  vars:
    vm_name: "abcdefgh12_12-0"
  tasks:
  - name: Print vm_name
    debug: 
       msg: "{{ vm_name }}"

I found you can use |int but I didn't find an option to block special characters or how to fail the task if it doesn't meet the criteria.

β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
southwind
  • 29
  • 7

2 Answers2

1

You can use the filter regex_findall to fit your condition, and accompany it with slicing, to limit the length of the string.

Then, to reduce the string to the acceptable pattern, you could do:

- set_fact:
    vm_name: "{{ (vm_name | regex_findall('[A-Za-z0-9-_]'))[:15] | join }}"
  vars:
    vm_name: )a&bc"d#efgh12_12-0(22

Which gives something like

ok: [localhost] => changed=false 
  ansible_facts:
    vm_name: abcdefgh12_12-0

Note: the above output have been generated running the playbook with the option -v, which, amongst other useful information, shows the result of a set_fact task.

Or, if you want to fail:

- assert:
    ## By testing the length before and after the regex filtering
    ## and the slicing, we assert if the filtering did alter the 
    ## string length, and so, the fact that the original string
    ## did contain invalid character or was too long
    that: "(
        vm_name | regex_findall('[A-Za-z0-9-_]')
      )[:15] | join | length == vm_name | length"
  vars:
    vm_name: abcdefgh12_12-0
β.εηοιτ.βε
  • 33,893
  • 13
  • 69
  • 83
0

Declare the regex of a valid password and remove other characters

  vm_name_regex: '[^-\w]'
  vm_name_valid: "{{ (vm_name|regex_replace(vm_name_regex, ''))[:15] }}"

Example of a complete playbook for testing

shell> cat pb.yml 
- hosts: localhost

  vars:

    vm_name: ')a&bc"d#efgh12_12-0(22'
    
    vm_name_regex: '[^-\w]'
    vm_name_valid: "{{ (vm_name|regex_replace(vm_name_regex, ''))[:15] }}"

  tasks:

    - debug:
        var: vm_name_valid

gives

shell> ansible-playbook pb.yml 

PLAY [localhost] ******************************************************************************

TASK [debug] **********************************************************************************
ok: [localhost] => 
  vm_name_valid: abcdefgh12_12-0

PLAY RECAP ************************************************************************************
localhost: ok=1    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 
Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63