Count the number of EC2 instances cross-account - python-3.x

I need to create a python lambda function which check a set of conditions.
One of the is to count the number of running ec2 instances with a specific name from another aws account.
I searched stackoverflow and found something like this, but this should only count the instances from the same account/region.
def ec2(event, context):
ec2_resource = boto3.resource('ec2')
instances = [instance.state['Name'] for instance in ec2_resource.instances.all()]
ec2_running_instances = instances.count('running')
print(ec2_running_instances)

You can't do this directly from your account. You must assume IAM role that is created in the second account, with permissions to describe the instances. Please check: Delegate access across AWS accounts using IAM roles .
Once the role exists, you have to use boto3's assume_role to assume the role, get temporary aws credentials, and then create new boto3 session with that credentials.

Related

Connect to s3 using ARN role url using boto3 Python

I want to connect to the S3 using arn. but not sure how I can make a connection
I am looking for a code something like.
ARN = boto3.client('s3', 'arn:aws:iam::****:role/***')
Is there any way that I can make a connection using arn?
it runs on ECS
If so, then you do not have to explicitly assume the role in your application. Instead you should use (its a good practice) an IAM Role for Task. Thus if you can change arn:aws:iam::****:role/*** into a task role, boto3 will automatically assume it and you don't have to do anything in your python code.
But if you still need to assume some role in your ECS task, then your IAM Role for Task should have sts:AsumeRole permission to actually be able to assume arn:aws:iam::****:role/***. But the first option is better choice if you can use it.

is there a way to get name of IAM role attached to an EC2 instance with boto3?

I am trying to list down all the EC2 instances with its IAM role attached using boto3 in python3. But I don't find any method to get the IAM role attached to existing EC2 instance. is there any method in boto3 to do that ?
When I describe an Instance, It has a key name IamInstanceProfile. That contains instance profile id and arn of the iam instance profile. I don't find name of IAM instance profile or any other info about IAM roles attached to it. I tried to use instance profile id to describe instance profile, But it seems to describe an instance profile, we need name of instance profile (not the id).
Can someone help on this ? I might be missing something.
Thanks
When we describe EC2 instance, We get IamInstanceProfile key which has Arn and id.
Arn has IamInstanceProfile name attached to it.
Arn': 'arn:aws:iam::1234567890:instance-profile/instanceprofileOrRolename'
This name can be used for further operation like get role description or listing policies attached to role.
Thanks
You can get the metadata of an EC2 instance by making an HTTP call to http://169.254.169.254/latest/meta-data/ from the instance.
In your case, you may want to navigate to http://169.254.169.254/latest/meta-data/iam/security-credentials to get the IAM role attached to the instance.
EC2 Instance Metadata
You can call IAM list_instance_profiles(), and then filter the results by the ARN or ID from EC2 describe_instances() result. This response will contain Roles for given instance profile.
Boto3 IAM documentation

Terraform VPC In New Accounts

I want to work with multiple AWS Accounts/Organization-Units (Acct1/Acct2/etc) within an Organization. Creating a new Account (let's say Acct4) from the AWS Console results in the automatic creation of a VPC (let's say VPC4). Is there a way to create a new Account from Terraform (and control the creation of the resulting VPC)? Or if I wanted to track the VPC in the new Account, would I simply import the details? Thanks in advance.

How to specify metadata_service_timeout during boto client creation?

I'm using the following way to create a botoclient
def create_boto_client(self, service_name: str):
return boto3.session.Session().client(
service_name=service_name
)
# or I can do: return boto3.client(service_name)
How I could set the "metadata_service_timeout" and "metadata_service_num_attempts" values?
I need to specify them, because otherwise boto can fail to fetch credentials in IAM role from Metadata server.
I read in doc that it's possible to specify this value like this:
# ~/.aws/config
[default]
metadata_service_timeout = 5.0
metadata_service_num_attempts = 10
but I don't have an ability to add this file to instance.
You can use env variables:
AWS_METADATA_SERVICE_TIMEOUT: The number of seconds before a connection to the instance metadata service should time out. When attempting to retrieve credentials on an EC2 instance that has been configured with an IAM role, a connection to the instance metadata service will time out after 1 second by default. If you know you are running on an EC2 instance with an IAM role configured, you can increase this value if needed.
AWS_METADATA_SERVICE_NUM_ATTEMPTS: When attempting to retrieve credentials on an EC2 instance that has been configured with an IAM role, boto3 will only make one attempt to retrieve credentials from the instance metadata service before giving up. If you know your code will be running on an EC2 instance, you can increase this value to make boto3 retry multiple times before giving up.
To set them from inside python:
os.environ["AWS_METADATA_SERVICE_TIMEOUT"] = "5.0"
os.environ["AWS_METADATA_SERVICE_NUM_ATTEMPTS"] = "10"

How to connect IAM login name with an EC2 instance?

I am using the boto3 Python3 module provided by AWS. I'm able to extract the security key name and the various tags associated with an EC2 instance. Unfortunately, none of that information tells me who created the instance.
Is there a way to use AWS IAM to see what active instances were created by a user?

Resources