Ansible: how to convert list into integer

General Tech Bugs & Fixes 2 years ago

0 3 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Bugs & Fixes related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (3)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

 

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.

 
profilepic.png
manpreet 2 years ago

Brackets create a list. "[[40]]" is a list of lists">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"

0 views   0 shares

profilepic.png
manpreet 2 years ago
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.


0 views   0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.