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
  Increase the speed of a python loop over a pandas dataframe mcva 0 118 Jan-21-2022, 06:24 PM
Last Post: mcva
  How to make for loop display on 1 Line Extra 3 156 Jan-12-2022, 09:29 PM
Last Post: Extra
  Unable to Loop Over Date gdbengo 2 147 Jan-09-2022, 05:11 PM
Last Post: menator01
  How to use += after breaking for loop? Frankduc 2 253 Dec-31-2021, 01:23 PM
Last Post: Frankduc
Question How can I merge several images via loop using the information of a dataframe? noahverner1995 1 207 Dec-31-2021, 05:03 AM
Last Post: noahverner1995
  menu while loop 3lnyn0 12 1,130 Dec-28-2021, 08:04 PM
Last Post: BashBedlam
  For Loop and Use of Brackets to Modify Dictionary in Tic-Tac-Toe Game new_coder_231013 7 300 Dec-28-2021, 11:32 AM
Last Post: new_coder_231013
  Loop reading csv file problem faustineaiden 1 274 Dec-11-2021, 08:40 AM
Last Post: ibreeden
  How to Loop This Code Michael1 2 252 Dec-09-2021, 08:12 PM
Last Post: deanhystad
  for loop in dataframe in pandas Paulman 7 457 Dec-02-2021, 12:15 AM
Last Post: bowlofred

Forum Jump:

User Panel Messages

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