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
  Re Try loop for "net use..." failures tester_V 10 446 Mar-02-2024, 08:15 AM
Last Post: tester_V
  File loop curiously skipping files - FIXED mbk34 10 683 Feb-10-2024, 07:08 AM
Last Post: buran
  Optimise multiply for loop in Python KenBCN 4 427 Feb-06-2024, 06:48 PM
Last Post: Gribouillis
  Basic binary search algorithm - using a while loop Drone4four 1 306 Jan-22-2024, 06:34 PM
Last Post: deanhystad
  loop through csv format from weburl in python maddyad82 3 358 Jan-17-2024, 10:08 PM
Last Post: deanhystad
  Variable definitions inside loop / could be better? gugarciap 2 373 Jan-09-2024, 11:11 PM
Last Post: deanhystad
  UART & I2C slow down a loop trix 4 544 Dec-28-2023, 05:14 PM
Last Post: trix
  Need an alternative to brute force optimization loop jmbonni 5 1,106 Dec-07-2023, 12:28 PM
Last Post: RockBlok
  Which GUI can have indefinite loop ? jst 20 1,577 Nov-16-2023, 10:23 PM
Last Post: jst
  How to create a variable only for use inside the scope of a while loop? Radical 10 1,524 Nov-07-2023, 09:49 AM
Last Post: buran

Forum Jump:

User Panel Messages

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