@@ -43,7 +43,9 @@ def update_prometheus_config():
4343
4444 # Get the machine's IP address
4545 try :
46- ipv4_address = subprocess .run (['hostname' , '-I' ], capture_output = True , text = True , check = True ).stdout .split ()[0 ]
46+ ipv4_address = subprocess .run (
47+ ['hostname' , '-I' ], capture_output = True , text = True , check = True
48+ ).stdout .split ()[0 ]
4749 except subprocess .CalledProcessError as e :
4850 print (f"Error getting IP address: { e } " )
4951 return False
@@ -54,29 +56,28 @@ def update_prometheus_config():
5456 except Exception as e :
5557 print (f"Error loading YAML config: { e } " )
5658 return False
57-
58- # Fetch the 'localhost' job
59- localhost_job = next ((job for job in config .get ('scrape_configs' , []) if job .get ('job_name' ) == 'localhost' ), None )
6059
61- if localhost_job :
62- # Update the IP address for the 'localhost' job target
63- localhost_job ['static_configs' ][0 ]['targets' ][0 ] = f'{ ipv4_address } :5050'
64-
65- # Create a new OrderedDict to maintain the correct order
66- updated_job = OrderedDict ()
67- updated_job ['job_name' ] = localhost_job ['job_name' ]
68- updated_job ['scrape_interval' ] = localhost_job .get ('scrape_interval' , '10s' )
69- updated_job ['static_configs' ] = localhost_job ['static_configs' ]
70-
71- # Add basic_auth last to maintain order
72- if 'basic_auth' in localhost_job :
73- updated_job ['basic_auth' ] = localhost_job ['basic_auth' ]
60+ for job in config .get ('scrape_configs' , []):
61+ if job ['job_name' ] == 'localhost' :
62+ # Update the target for 'localhost' job
63+ job ['static_configs' ][0 ]['targets' ][0 ] = f'{ ipv4_address } :5050'
64+
65+ # Create a new OrderedDict to ensure the correct order
66+ updated_job = OrderedDict ()
67+ updated_job ['job_name' ] = job ['job_name' ]
68+ updated_job ['scrape_interval' ] = job .get ('scrape_interval' , '10s' )
69+ updated_job ['static_configs' ] = job ['static_configs' ]
70+
71+ # Add basic_auth at the end if it exists
72+ if 'basic_auth' in job :
73+ updated_job ['basic_auth' ] = job ['basic_auth' ]
7474
7575 # Replace the old job with the updated one
76- for index , job in enumerate (config ['scrape_configs' ]):
77- if job ['job_name' ] == 'localhost' :
76+ for index , j in enumerate (config ['scrape_configs' ]):
77+ if j ['job_name' ] == 'localhost' :
7878 config ['scrape_configs' ][index ] = updated_job
79- break
79+ else :
80+ config ['scrape_configs' ][index ] = OrderedDict (j )
8081
8182 # Save the updated config
8283 try :
0 commit comments