mercredi 19 août 2020

Python: dynamic json with string interpolation

I created a class of functions that provision some cloud infrastructure.

response = self.ecs_client.register_task_definition(
containerDefinitions=[
                {
                    "name": "redis-283C462837EF23AA",
                    "image": "redis:3.2.7",
                    "cpu": 1,
                    "memory": 512,
                    "essential": True,
                },
...

This is a very long json, I show just the beginning.

Then I refactored the code to use a parameter instead of the hard coded hash, memory and cpu.

response = self.ecs_client.register_task_definition(
containerDefinitions=[
                {
                    "name": f"redis-{git_hash}",
                    "image": "redis:3.2.7",
                    "cpu": {num_cpu},
                    "memory": {memory_size},
                    "essential": True,
                },
...

I read the values of git_hash, num_cpu and memory_size from a config file prior to this code.

Now, I also want to read to entire json from a file.

The problem is that if I save {num_cpu} etc. in a file, the string interpolation won't work.

How can I extract the json from my logic and still use string interpolation or variables?

Aucun commentaire:

Enregistrer un commentaire