Reputation: 772
I am new to python and boto3.
I need to get the below details using python, I was using bash to get these details.
#!/bin/bash
aws ec2 describe-instances --query "Reservations[*].Instances[*].[Tags[?Key=='Name']|[0].Value,InstanceId,InstanceType,Platform,State.Name,PrivateIpAddress,PublicIpAddress,Placement.AvailabilityZone]" --output text --region me-south-1 >> aws_ec2_details_me_south_1.xlsx
aws elbv2 describe-load-balancers --query "LoadBalancers[*].[LoadBalancerArn,DNSName,LoadBalancerName,Type,Scheme,State.Code]" --output text --region me-south-1 >> aws_elb_details_me_south_1.xlsx
aws autoscaling describe-auto-scaling-groups --query "AutoScalingGroups[*].[AutoScalingGroupName,AutoScalingGroupARN,MinSize,MaxSize,DesiredCapacity,DefaultCooldown]" --output text --region me-south-1 >> aws_autoscaling_me_south_1.xlsx
aws ec2 describe-addresses --query "Addresses[*].[Tags[?Key=='Name']|[0].Value,PublicIp,PrivateIpAddress]" --output text --region me-south-1 >> aws_eip_list_me_south_1.xlsx
aws rds describe-db-instances --query "DBInstances[*].[DBInstanceIdentifier,DBInstanceClass,Engine,EngineVersion,DBInstanceStatus,MasterUsername,Endpoint.Address,MultiAZ,AllocatedStorage,PreferredBackupWindow,BackupRetentionPeriod,StorageEncrypted]" --output text --region me-south-1 >> aws_rds_details_me_south_1.xlsx
I had done some sample python script here,
import boto3
session = boto3.Session(profile_name='default',region_name='me-south-1')
ec2_des = session.client('ec2')
resp = ec2_des.describe_instances(
Filters = [ {
'Name' : 'instance-state-name',
'Values' : [ 'running' ]
} ]
)
for i in resp:
print i(instance-id)
print (i.image-id)
Getting error
Traceback (most recent call last):
File "t4.py", line 11, in <module>
print (i.instance-id)
AttributeError: 'str' object has no attribute 'instance'
Please help me to complete this, with understanding
We have an 80+ AWS account, The main agenda is to run the script to fetch the data from 80+ accounts in a single shot.
Upvotes: 1
Views: 6747
Reputation: 888
Sample code to fetch details of single EC2 instance and write output to CSV file.
import boto3
import csv
session = boto3.Session(profile_name='default', region_name='us-east-1')
ec2 = session.client('ec2')
result = []
response = ec2.describe_instances(
InstanceIds=[
'i-xxxxxxxxxxxxxxxxx'
]).get('Reservations')
for item in response:
for each in item['Instances']:
result.append({
'ImageId': each['ImageId'],
'InstanceType': each['InstanceType'],
'PublicIp': each['PublicIpAddress'],
'PrivateIp': each['PrivateIpAddress']
})
#The result type will be list of dictionary.
# print(result) [{'ImageId': 'ami-08c5e20f0xxxxxxxx', 'InstanceType': 't2.micro', 'PublicIp': '10.200.101.11', 'PrivateIp': '172.31.33.95'}]
# Write to csv file.
header = ['ImageId', 'InstanceType', 'PublicIp', 'PrivateIp']
with open('ec2-details.csv', 'w') as file:
writer = csv.DictWriter(file, fieldnames=header)
writer.writeheader()
writer.writerows(result)
Hope it will help you to proceed further.
You can use below code to loop through multiple AWS accounts using switch role.
import boto3
from botocore.exceptions import ClientError
# master account
session = boto3.Session(profile_name='default', region_name='eu-central-1')
iam = session.resource('iam')
accounts = [111111111111, 222222222222, 333333333333]
def assume_role(account: str) -> dict:
sts_client = session.client('sts')
try:
response = sts_client.assume_role(RoleArn=f'arn:aws:iam::{account}:<role-name>',
RoleSessionName=f'dev-{account}-session'
)
temp_credentials = response['Credentials']
except ClientError as ex:
print('Client Error', str(ex))
except Exception as e:
print(e)
return temp_credentials
def list_users(session_arg: dict, acct: int) -> dict:
iam_user = session.client('iam',
aws_access_key_id=session_arg['AccessKeyId'],
aws_secret_access_key=session_arg['SecretAccessKey'],
aws_session_token=session_arg['SessionToken']
)
# listing users
response = iam_user.list_users()
return response
if __name__ == '__main__':
try:
for acct in accounts:
sessionCredentials = assume_role(acct)
user_info = list_users(sessionCredentials, acct)
print(user_info)
except Exception as e:
print(e)
Upvotes: 2
Reputation: 526
The describe_instances
method actually returns a dictionnary, for which you can't use a dot "." to access values.
By taking a look at the method's documentation here and scrolling down a little bit, you will see a Returns part with the Response Syntax.
Based on this, if you want to print the instance-id and the image-id using the response of describe_instances
, you could use this code :
for r in resp['Reservations']:
for i in r['Instances']:
print(f" instance id : {i['InstanceId']}")
print(f" image id : {i['ImageId']}")
instance id : i-xxxxxxxxxxxxxxxxx
image id : ami-xxxxxxxxxxxxxxxxx
instance id : i-xxxxxxxxxxxxxxxxx
image id : ami-xxxxxxxxxxxxxxxxx
...
Upvotes: 1