简体   繁体   中英

Ansible: how to convert list into integer

i have the following json output

"lc_facts": {
        "changed": false, 
        "failed": false, 
        "launch_configurations": [
            {
                "block_device_mappings": [
                    {
                        "device_name": "/dev/sda1", 
                        "ebs": {
                            "delete_on_termination": true, 
                            "volume_size": 40, 
                            "volume_type": "gp2"
                        }
                    }
                ]
            }
       ]
  }

The query below

- debug:
    msg: "{{ lc_facts.launch_configurations|json_query('[*].block_device_mappings[0].ebs.[volume_size]') | flatten }}"

gives

    "msg": [
    [40]
    ]

i want to convert into an integer so i can use this value. i tried everything, but all i want is to get number only without brackets. i also added |int in the end, but it gives me 0 value, which is weird.

please help, i am really in trouble.

Brackets create a list. "[[40]]" is a list of lists with one element "40". The play below

vars:
  var1: [[40]]
tasks:
  - debug: var=var1
  - debug: var=var1[0]
  - debug: var=var1[0][0]

gives:

"var1": [
    [
        40
    ]
]

"var1[0]": [
    40
]

"var1[0][0]": "40"

try taking the first element of the list with index [0]. Do it twice if the list is inside another list:

for msg = [40] use msg[0]

for msg = [[40]] use msg[0][0]

def dict_to_obj(obj, data):
    for d in data:
        if isinstance(data[d], dict):
            setattr(obj, str(d), obj.__class__())
            dict_to_obj(getattr(obj, str(d)), data[d])
        else:
            setattr(obj, str(d), data[d])
    return obj

class Empty:pass
obj = Empty()
obj = dict_to_obj(obj,Your_JSON_object)
#Now here you get all json attributes as objects e.g.
#to get volume_size : 
print(obj.lc_facts.launch_configurations.block_device_mappings.ebs.volume_size)
# but for this to work, you need to restructure your json nested key-value pairs like 
# this :-
"launch_configuration" : {....}
# instead of this :-
"launch configuration" : [ {....} ]

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM