How to create an EC2 instance with AWS CLI
1. Install aws CLI on your working station (Linux or Windows)
$aws configure AWS Access Key ID [****************GYFA]: AWS Secret Access Key [****************DTIn]: Default region name [us-east-1]: Default output format [None]: Available Tools
2. Create a key with following commnad
#aws ec2 create-key-pair --key-name ovi-key --query 'KeyMaterial' --output text > ovi-key.pem
3. Create an instance
#aws ec2 run-instances --image-id ami-6869aa05 --count 1 --instance-type t2.small --key-name ovi-key --security-group-ids sg-74ef3210 --subnet-id subnet-01ac3976 --associate-public-ip-address { "OwnerId": "896477545246", "ReservationId": "r-ce672779", "Groups": [], "Instances": [ { "Monitoring": { "State": "disabled" }, "PublicDnsName": "", "RootDeviceType": "ebs", "State": { "Code": 0, "Name": "pending" }, "EbsOptimized": false, "LaunchTime": "2016-10-05T14:30:51.000Z", "PrivateIpAddress": "172.30.0.240", "ProductCodes": [], "VpcId": "vpc-dfc7xxxx", "StateTransitionReason": "", "InstanceId": "i-c1a76xx7", "ImageId": "ami-6869aa05", "PrivateDnsName": "ip-172-30-0-240.ec2.internal", "KeyName": "ovi-key", "SecurityGroups": [ { "GroupName": "default", "GroupId": "sg-74xx3210" } ], "ClientToken": "", "SubnetId": "subnet-01xx3976", "InstanceType": "t2.small", "NetworkInterfaces": [ { "Status": "in-use", "MacAddress": "0a:84:92:2x:2x:95", "SourceDestCheck": true, "VpcId": "vpc-dfc7xxx", "Description": "", "NetworkInterfaceId": "eni-9f9xx999", "PrivateIpAddresses": [ { "PrivateDnsName": "ip-172-30-0-240.ec2.internal", "Primary": true, "PrivateIpAddress": "172.30.0.240" } ], "PrivateDnsName": "ip-172-30-0-240.ec2.internal", "Attachment": { "Status": "attaching", "DeviceIndex": 0, "DeleteOnTermination": true, "AttachmentId": "eni-attach-c3x01x76", "AttachTime": "2016-10-05T14:30:51.000Z" }, "Groups": [ { "GroupName": "default", "GroupId": "sg-74xf3211" } ], "SubnetId": "subnet-01xx3976", "OwnerId": "896477545299", "PrivateIpAddress": "172.30.yyy.yyy" } ], "SourceDestCheck": true, "Placement": { "Tenancy": "default", "GroupName": "", "AvailabilityZone": "us-east-1a" }, "Hypervisor": "xen", "BlockDeviceMappings": [], "Architecture": "x86_64", "StateReason": { "Message": "pending", "Code": "pending" }, "RootDeviceName": "/dev/xvda", "VirtualizationType": "hvm", "AmiLaunchIndex": 0 } ] }
Note :
You can pass a shell script during the EC2 instance creation using
--user-data file://script_name.sh