Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Ansible variable from Unicode to ASCII

I'm getting the output of a command on the remote system and storing it in a variable. It is then used to fill in a file template which gets placed on the system.

- name: Retrieve Initiator Name
  command: /usr/sbin/iscsi-iname
  register: iscsiname

- name: Setup InitiatorName File
  template: src=initiatorname.iscsi.template dest=/etc/iscsi/initiatorname.iscsi

The initiatorname.iscsi.template file contains:

InitiatorName={{ iscsiname.stdout_lines }}

When I run it however, I get a file with the following:

InitiatorName=[u'iqn.2005-03.org.open-iscsi:2bb08ec8f94']

What I want:

InitiatorName=iqn.2005-03.org.open-iscsi:2bb08ec8f94

What am I doing wrong?

I realize I could write this to the file with an "echo "InitiatorName=$(/usr/sbin/iscsi-iname)" > /etc/iscsi/initiatorname.iscsi" but that seems like an un-Ansible way of doing it.

Thanks in advance.

like image 970
Wraezor Sharp Avatar asked Jan 28 '14 18:01

Wraezor Sharp


3 Answers

FWIW, if you really do have an array:

[u'string1', u'string2', u'string3']

And you want your template/whatever result to be NOT:

ABC=[u'string1', u'string2', u'string3']

But you prefer:

ABC=["string1", "string2", "string3"]

Then, this will do the trick:

ABC=["{{ iscsiname.stdout_lines | list | join("\", \"") }}"]

(extra backslashes due to my code being in a string originally.)

like image 61
Mark Chance Avatar answered Oct 14 '22 20:10

Mark Chance


Use a filter to avoid unicode strings:

InitiatorName = {{ iscsiname.stdout_lines | to_yaml }}

Ansible Playbook Filters

like image 41
indieman Avatar answered Oct 14 '22 21:10

indieman


To avoid the 80 symbol limit of PyYAML, just use the to_json filter instead:

InitiatorName = {{ iscsiname.stdout_lines | to_yaml }}

In my case, I'd like to create a python array from a comma seperated list. So a,b,c should become ["a", "b", "c"]. But without the 'u' prefix because I need string comparisations (without special chars) from WebSpher. Since they seems not to have the same encoding, comparisation fails. For this reason, I can't simply use var.split(',').

Since the strings contains no special chars, I just use to_json in combination with map(trim). This fixes the problem that a, b would become "a", " b".

restartApps = {{ apps.split(',') | map('trim') | list | to_json }}

Since JSON also knows arrays, I get the same result than python would generate, but without the u prefix.

like image 1
Lion Avatar answered Oct 14 '22 21:10

Lion