python 3 using for loops and typecasting

Question:

How can I get 2nd for loop the full aws ec2 instance id? It converts it to string it seems.

I am using Python 3.9.

1st loop gives output as expected:

i-0dccf1ede229ce1
i-0285506fee62051

2nd loop gives

i
-
0
d
c
...
INSTANCE_ID = ['i-0dccf1ede229ce1','i-0285506fee62051']
for i in INSTANCE_ID:
  print (i)

vs.

for i in INSTANCE_ID:
  for j in i:
    print (j)

Actual boto3 script is as below

#!/usr/bin/env python3

import boto3


AWS_REGION = "us-east-1"
AWS_PROFILE = "xxxx"
session=boto3.session.Session(profile_name=AWS_PROFILE)
EC2_RESOURCE = session.resource('ec2', region_name=AWS_REGION)
INSTANCE_ID = ['i-0dccf1ede229ce1','i-0285506fee62051']

TAGS = [
    {
        'Key': 'STATE',
        'Value': 'LIVE'
    }
]



for instance_id in INSTANCE_ID:
    for ec2_id in     instance_id:
      print (ec2_id) ## here is the issue 
      
      filter = EC2_RESOURCE.instances.filter(InstanceIds={ec2_id})
      filter.create_tags(Tags=TAGS)
Asked By: Kiran Kumar

||

Answers:

Thank you all. Still its not clear why 2nd loop what it does.

So i modified the code with 1 loop & indeed worked

@silvio & everyone thanks

#!/usr/bin/env python3
import boto3
AWS_REGION = "us-east-1"
AWS_PROFILE = "xxx"
session=boto3.session.Session(profile_name=AWS_PROFILE)
EC2_RESOURCE = session.resource('ec2', region_name=AWS_REGION)
INSTANCE_ID = ['i-0dccf1ede229ce1','i-0285506fee62051']
TAGS = [
    {
        'Key': 'STATE',
        'Value': 'LIVE'
    }
]

for instance_id in INSTANCE_ID:
  print ( instance_id )
  instances  = EC2_RESOURCE.instances.filter(InstanceIds=[instance_id])
  instances.create_tags(Tags=TAGS)
  
Answered By: Kiran Kumar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.