Reputation: 61
I am creating a instance using boto3 and i want to print the public ip Address on response. please assist to complete this code but the code keep shows error can someone help to correct this code to show print public ipv4 address
import boto3
import json
AMI = 'AMI'
INSTANCE_TYPE = 'INSTANCE_TYPE'
KEY_NAME = 'KEY_NAME'
REGION = 'REGION'
SUBNET_ID = 'SUBNET_ID'
SECURITYGROUP_ID = 'SECURITYGROUP_ID'
def lambda_handler(event, context):
ec2 = boto3.client('ec2', region_name=event['REGION'])
instance = ec2.run_instances(
ImageId=event['AMI'],
InstanceType=event['INSTANCE_TYPE'],
KeyName=event['KEY_NAME'],
SubnetId=event['SUBNET_ID'],
SecurityGroupIds = ['my-sg'],
MaxCount=1,
MinCount=1,
InstanceInitiatedShutdownBehavior="terminate",
TagSpecifications=[
{
'ResourceType': 'instance',
'Tags': [
{
'Key': 'Name',
'Value': 'my-instance'
},
]
},
],
)
print ("New instance created:")
instance_id = instance['Instances'][0]['InstanceId']
print (instance_id)
for instance in instance:
IP = instance.public_ip_address
print(IP)
return instance_id**
error message shown like this
errorMessage": "'str' object has no attribute 'public_ip_address'",
Upvotes: 0
Views: 322
Reputation: 269530
The public IP address will not be provided after run_instances()
because it takes a while to assign to the instance.
You should repeatedly call describe_instances()
until a public IP address is provided. I would recommend waiting a few seconds between each call.
After calling:
response = describe_instances(InstanceIds=[instance_id])
you can check if a value is provided:
instance = response['Reservations'][0]['Instances'][0]
if 'PublicIpAddress' in instance:
public_ip = instance['PublicIpAddress']
Upvotes: 2