Python Forum
For Loop, execute one time for every loop iteration
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
For Loop, execute one time for every loop iteration
#1
Hi,

i'm new to python. I created a script to iterate through JSON file to find field email address, and remove part after @. This value is username for EC2 instance which will be created using terraform.For every user number of instances will be prompted interactively. (Terraform will be invoked from python script). Everything works fine when only one email is specified in JSON,but if more than one user is specified, code will be execured only once, I need when one iteration is finishes, run again for new user (ask for number of instances), create machine then run for as many users found in JSON file

Here is my code:

#!/bin/python
import json
from pprint import pprint
from python_terraform import *




def myfunc(int):

  tf = Terraform(working_dir='/home/ja/terraform-course/demo-2b', variables={'count':enter,'INSTANCE_USERNAME':user})
  tf.plan(no_color=IsFlagged, refresh=False, capture_output=True)
  approve = {"auto-approve": True}
  print(tf.plan())
  print(tf.apply(**approve))
  return



json_data=open('./my.json')
data = json.load(json_data)

json_data.close()

for i in range (0, len (data['customers'])):
    #print data['customers'][i]['email']
    k=data['customers'][i]['email']
    #print(k.split('@')[0])
    user=k.split('@')[0]
    if (i) !=0:
       continue
    #print(user)
    enter = int(input('Enter number of instances: '))
    myfunc(enter)
Reply
#2
Do you have a short example json file for which the issue occurs?
Reply
#3
Solved after few days:

JSON:

Output:
{ "squadName": "Super hero squad", "homeTown": "Metro City", "formed": 2016, "secretBase": "Super tower", "active": true, "customers": [ { "name": "Molecule Man", "age": 29, "email": "[email protected]", "instances": 1, "powers": [ "Radiation resistance", "Turning tiny", "Radiation blast" ] }, { "name": "Madame Uppercut", "age": 39, "email": "[email protected]", "instances": 1, "powers": [ "Million tonne punch", "Damage resistance", "Superhuman reflexes" ] }, { "name": "Eternal Flame", "age": 1000000, "email": "[email protected]", "instances": 1, "powers": [ "Immortality", "Heat Immunity", "Inferno", "Teleportation", "Interdimensional travel" ] } ] }
script:
#!/bin/python
import sys
import json
import os.path
import shutil
from os import mkdir
from pprint import pprint
from python_terraform import *

#open JSON file
json_data=open('./my.json')
data = json.load(json_data)

json_data.close()


#Function which will create instances,parameters are username and count of instances fetched from JSON file

def myfunc():

  tf = Terraform(working_dir=final_path, variables={'count':count,'INSTANCE_USERNAME':user})
  tf.plan(no_color=IsFlagged, refresh=True, capture_output=False)
  approve = {"auto-approve": True}
  print(tf.init(reconfigure=True))
  print(tf.plan())
  print(tf.apply(**approve))
  return






# sweep through JSON file and store username and number of instances into user and count variables
for i in range (0, len (data['customers'])):
    #print data['customers'][i]['email']
    k=data['customers'][i]['email']
    #print(k.split('@')[0])
    user=k.split('@')[0]
    #print(user)
    count=data['customers'][i]['instances']
    #print(count)
    #enter = int(input('Enter number of instances: '))
    
    #define "root" directory
    start_path="/home/ja/terraform-course/demo-2b/"

    

    #in order to avoid instance recreation,folder for each user needs to be created
    
    
    #define subdirectories named by user and create it it folder doesn't exist
    final_path=os.path.join(start_path,user)
    if not os.path.exists(final_path):
       os.makedirs(final_path)

    
    #copy terraform files to each newly created folder for user 

    shutil.copy2('./vars.tf', final_path)
    shutil.copy2('./sg.tf', final_path)
    shutil.copy2('./windows.tf', final_path)
    shutil.copy2('./provider.tf', final_path)
    shutil.copy2('./test.txt', final_path)
    shutil.copy2('./output.tf', final_path)


    #for each user new security group needs to be created.Name of SG will be username
    final=os.path.join(final_path,'sg.tf')
    final1=os.path.join(final_path,'windows.tf')
    
    #replace current name (allow-all) with variable username in sg.tf and windows.tf files
    with open(final, 'r') as file :
      filedata = file.read()
    filedata = filedata.replace('allow-all', user)
    with open(final, 'w') as file:
      file.write(filedata)
    with open(final1, 'r') as file :
      filedata = file.read()
    filedata = filedata.replace('allow-all', user)
    with open(final1, 'w') as file:
      file.write(filedata)

    #call function for running terraform
    myfunc()


    #in each user folder open terraform.tfstate file and extract public IP to variable ip
    

    final2=os.path.join(final_path,'terraform.tfstate')
    json_data=open(final2)
    data1 = json.load(json_data)
    json_data.close()

    
    #write Public IP,username and password to /home/ja/terraform-course/demo-2b/<username>.txt file

    filename="/home/ja/terraform-course/demo-2b/"+user+".txt"
    print(filename)
    for i in range (0, len (data1['modules'])):
     ip=','.join(data1['modules'][i]['outputs']['id']['value'])    
    sys.stdout = open(filename,'wt')
    print("Username is:"+" "+ user+".Password is Passw0rd01234.IP addrress is:"+ip)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  in c# create a loop counting from 0 to 5, consecutively Frankd 19 2,038 Apr-01-2025, 12:46 PM
Last Post: Frankd
  really new to python want to know how to do a loop pentopdmj 6 1,529 Mar-09-2025, 12:59 PM
Last Post: snippsat
  knowing for loop position in a list medic5678 4 661 Jan-31-2025, 04:19 PM
Last Post: perfringo
  Run this once instead of a loop, do I need the 'calibration' steps? duckredbeard 2 708 Jan-28-2025, 04:55 PM
Last Post: duckredbeard
  Error loop with Chatgpt sportak12 0 484 Jan-14-2025, 12:04 PM
Last Post: sportak12
  How to convert while loop to for loop in my code? tatahuft 4 788 Dec-21-2024, 07:59 AM
Last Post: snippsat
  How to get keep information in a loop ginod 4 857 Dec-11-2024, 01:32 AM
Last Post: deanhystad
  Regarding The For Loop Hudjefa 5 1,436 Nov-15-2024, 01:02 PM
Last Post: deanhystad
  For Loop beginner agoldav 2 704 Nov-05-2024, 12:51 AM
Last Post: agoldav
  A question about 'Event loop is closed' fc5igm 3 5,007 Oct-01-2024, 09:12 AM
Last Post: skdaro

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020