问题
I have a very simple sandbox I'm trying to get to work so I can use it in a bigger application:
ec2_client = boto3.client(
'ec2',
aws_access_key_id=ACCESS_KEY,
aws_secret_access_key=SECRET_KEY)
response = ec2_client.describe_instances()
print(response)
and it results in...
{
'Reservations': [],
'ResponseMetadata': {
'RequestId': '2c28e8aa-da6d-4ca4-8ea7-f672518cac9f',
'HTTPStatusCode': 200,
'HTTPHeaders': {
'content-type': 'text/xml;charset=UTF-8',
'transfer-encoding': 'chunked',
'vary': 'Accept-Encoding',
'date': 'Thu, 07 Dec 2017 16:44:30 GMT',
'server': 'AmazonEC2'
},
'RetryAttempts': 0}
}
But the problem is no matter how many times I run this Reservations
is ALWAYS empty :(.
In AWS consonle I can CLEARLLY see an instance is running...
I tried starting more instances, restarting the instances I had running. I put my initial script in a loop and ran it on repeat while I did this looking for any sign of the Reservations array actually having data.
I double checked that my aws ACCESS_KEY and SECRET_KEY are both correct and pointing to the correct account. They are.
I have no clue why this is. Its so simple and should be working. I'm new to AWS so any help is appreciated.
回答1:
Seems that you forgot to add the region.
Set the region when creating your client
ec2_client = boto3.client(
'ec2',
aws_access_key_id=ACCESS_KEY,
aws_secret_access_key=SECRET_KEY,
region_name=REGION_NAME
)
response = ec2_client.describe_instances()
print(response)
If your EC2 instances are in Oregon, you can do region_name='us-west-2'
Hard coding credentials is not recommended. You can configure your profiles using the awscli
and then reference it in your code.
session = boto3.Session(profile_name='dev')
# Any clients created from this session will use credentials
# from the [dev] section of ~/.aws/credentials.
ec2_client = session.client('ec2')
You can read more about Boto3 credentials Boto3 Credentials
回答2:
The problem is that somehow boto3 was using a region that my instance was not running in. The solution was to specify the region when initializing the client:
ec2_client = boto3.client(
'ec2',
region_name='us-east-2',
aws_access_key_id=ACCESS_KEY,
aws_secret_access_key=SECRET_KEY)
All credit to @kichik for telling me where to look!
来源:https://stackoverflow.com/questions/47700089/boto3-ec2-describe-instances-always-returns-empty