简体   繁体   中英

Boto3 different outputs

I am trying to get the instance id of ec2 that I created. But I get 2 different outputs, why? Please check the print outputs.

print (a) 
i-0ae514dcs36chb154
print (instance) 
ec2.Instance(id='i-0ae514dcs36chb154')
    ec=ec2.create_instances(
        ImageId=ami,
        InstanceType=type,
        MinCount=size,
        MaxCount=size,
        KeyName=keyname,
        SecurityGroupIds=[sg],
        TagSpecifications=[
            {
                'ResourceType': 'instance',
                'Tags': [
                    {
                        'Key': 'Name',
                        'Value': name,
                    },
                ],
            },
        ],
    )

    a= ec[0].id
    print (a) # Output: i-0ae514dcs36chb154
    instance = ec2.Instance(a)
    print (instance) # Output : ec2.Instance(id='i-0ae514dcs36chb154')

Thansks.

As seen here:

https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html#EC2.ServiceResource.create_instances

When you call create_instances() it returns a list of ec2.Instance() which is an object with an attribute id .

When you write,

a = ec[0].id  # Create a variable called "a" that points to the value of the "id" attribute of the first element in the list
print(a)  # print the id

When you write,

a = ec[0].id  # Create a variable called "a" that points to the value of the "id" attribute of the first element in the list
print(ec2.Instance(a))  # Create a new instance of ec2.Instance() with id equal to the value at a, then call the .__str__ method, and print

^ this is actually redundant.

Calling print(ec[0]) should yield ec2.Instance(id='i-0ae514dcs36chb154')

So, the reason they are different is that in the first you are printing the value of the attribute id of the ec2.Instance() object. In the second you are printing the ec2.Instance() object itself, which will call the private method __str__ on the ec2.Instance() object in order to produce a string to print.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM