# Launching AWS EC2 Instance using Python

### **Prerequisites:**

Required AWS account and ec2 knowledge

Install boto3 in Python

```python
pip install boto3
python3  -m pip install boto3 ( incase Python3 )
```

example\_ec2 = boto3.client('ec2', 'ca-central-1', aws\_access\_key\_id='', aws\_secret\_access\_key='')

the function to describe all the instances and current state

requested\_response = example\_ec2.describe\_instances()

print(requested\_response)

## To create an instance using python

import boto3

/

### Function for connecting to EC2

user\_ec2 = boto3.client('ec2', 'ap-south-1', aws\_access\_key\_id='', aws\_secret\_access\_key='')

### Function for running instances

instance\_run\_example= user\_ec2.run\_instances(InstanceType="t2.micro", MaxCount=1, MinCount=1, ImageId="ami-\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*")

print(instance\_run\_example)

## EC2 instance terminates using Python and the boto3 library

always import boto3

import boto3

* first Connect to the EC2 service
    

ec2 = boto3.client('ec2', 'ca-central-1', aws\_access\_key\_id='', aws\_secret\_access\_key='')

Terminate the instance using the specified ID

user\_output = ec2.terminate\_instances(InstanceIds=\['instance-id-1'\])

Print the user\_response

print(user\_output)
