1

I imported data in Ansible from a csv file and wanted to convert the String from csv file to a raw in Ansible.

Ansible:

parent_region: "{{ parent_region }}" ansible will interpret this as "parent_region": "1933".

Is there a way to remove the curly braces and make ansible interpret the code as "parent_region": 1933 ???

any help is appreciated!

EDIT I need the variable to be raw since parent_region field in Netbox's netbox_region only accepts raw. Here is the official documention.

user13539846
  • 425
  • 2
  • 5
  • 13
  • If you are using a template you could try with `parent_region: {{ parent_region }}` – gary lopez Jul 16 '21 at 03:59
  • @garylopez Tried that aswell, but it gives out an error `ERROR! Syntax Error while loading YAML. found unacceptable key (unhashable type: 'AnsibleMapping') The offending line appears to be: # parent_region: "{{ parent_region }}" parent_region: {{ parent_region }} ^ here` – user13539846 Jul 16 '21 at 04:05
  • @VladimirBotka My bad, already changed the title. – user13539846 Jul 16 '21 at 05:17

2 Answers2

1

Use 7.3.2. Single-Quoted Style. Quoting:

| the “\” and “"” characters may be freely used.

For example, given the variable

parent_region: "1933"

the tasks below

    - set_fact:
        parent_region: 'r"{{ parent_region }}"'
    - debug:
        var: parent_region
    - debug:
        msg: "{{ parent_region|type_debug }}"

give (the quotes are part of the string)

  parent_region: r"1933"
  msg: str

The default type in Ansible (Python3) is a Unicode string, e.g.

    - set_fact:
        parent_region: "1933"
    - debug:
        var: parent_region
    - debug:
        msg: "{{ parent_region|type_debug }}"

give (the quotes are NOT part of the string)

  parent_region: '1933'
  msg: AnsibleUnicode

You can create a custom filter and choose the encoding, e.g.

shell> cat filter_plugins/python_encode.py

def python_encode(s, encoding):
    return s.encode(encoding)

class FilterModule(object):
    def filters(self):
        return {
            'python_encode': python_encode,
        }

then the tasks

    - set_fact:
        parent_region: "{{ parent_region|python_encode('raw_unicode_escape') }}"
    - debug:
        var: parent_region
    - debug:
        msg: "{{ parent_region|type_debug }}"

give

  parent_region: b'1933'
  msg: str

See Python str vs unicode types.

Vladimir Botka
  • 58,131
  • 4
  • 32
  • 63
0

You can convert the variable to an integer using the int filter:

parent_region: "{{ parent_region | int }}"
Matt P
  • 2,452
  • 1
  • 12
  • 15
  • I need the variable to be `raw`, so is there a filter as well to make it raw?. My bad for not specifying it, will edit the question. – user13539846 Jul 16 '21 at 04:26