user4613285
user4613285

Reputation:

Ansible variable manipulation within vars

I want to construct the password (ansible_ssh_pass) within the vars section of my playbook from a string passed as an input (pass_var). The problem here is that the actual password should be the first 6 characters from the variable (pass_var). I am not sure how to achieve it. Here is my playbook

- hosts: all
  user: "{{username}}"
  become: yes
  gather_facts: False
  vars:
     ansible_ssh_pass: <someway to decode string (base64 -d) and get first 6 characters>

I'm running the playbook as:

ansible-playbook test.yml --extra-vars "pass_var=${pass_val} username=${user}"

I also need to do some shell manipulations. For example, my string will be base64 encoded, so I need to decode it as well. Something like: echo ${pass_var} | base64 -d | rev | cut -c1-6

Upvotes: 0

Views: 350

Answers (1)

larsks
larsks

Reputation: 311238

You can use Python-style string slicing in Ansible, so you can just write:

vars:
  ansible_ssh_pass: "{{ pass_var[:6] }}"

For example, the following command:

ansible localhost -e pass_var=1234567890 -m debug -a 'msg={{pass_var[:6]}}'

Will output:

localhost | SUCCESS => {
    "msg": "123456"
}

If your initial string is base64 encoded, you can use Ansible's b64_decode filter:

ansible_pass: "{{ (pass_var|b64decode)[:6] }}"

And if for some weird reason you need to reverse it, there is a reverse filter:

ansible_pass: "{{ ((pass_var|b64decode)|reverse)[:6] }}"

If we modify my earlier example, we get:

ansible localhost -e pass_var="MTIzNDU2Nzg5MA==" -m debug -a 'msg={{((pass_var|b64decode)|reverse)[:6]}}'

Which produces:

localhost | SUCCESS => {
    "msg": "098765"
}

Upvotes: 1

Related Questions