AWS Logo

It’s easy to launch new instances from the EC2 Console, but sometimes you need to automate the task from a shell script. In that case, the AWS CLI has extensive commands for launching instances from the command line.

What You’ll Need

To start, you’ll need the AWS CLI installed and configured with an IAM user that has access to create new instances.

Unless you want to automate the creation of them, you’ll need an existing security group with the rules already configured. While the web interface creates a new group for each instance by default, you can reuse security groups for any number of instances. Keep in mind, though, that a port opened in a security group will open that port on each instance.

If you want to create a new security group from the command line, you can create and open ports with the following commands:

aws ec2 create-security-group --group-name NewSecurityGroup --description "Created from CLI"
aws ec2 authorize-security-group-ingress --group-name NewSecurityGroup --protocol tcp --port 22 --cidr 0.0.0.0/0

Whichever route you choose, you’ll need to make note of the security group ID. You can find this from the command line by describing the security group:

aws ec2 describe-security-groups --group-names EC2SecurityGroup

Which will show info about the group, including the group ID.

You’ll need to make note of the name of the key pair you use to access the instances. For simplicity’s sake, you likely want to use the same key pair, rather than creating a new one for each new instance you create.

You’ll need an AMI to launch the image from. This can be a fresh AMI, like Amazon Linux 2 or Ubuntu Server LTS 18.04, or it can be your own custom AMI with software preinstalled. (more on that down below).

ALSO READ  The U.S. Government Is “Looking at” Banning Chinese Apps, Including TikTok – Review Geek

You’ll need to know your subnet ID. You’ll want to launch all your instances in the same subnet and definitely in the same availability zone, as there are costs to transferring data between zones. You can find the subnet ID from the AWS EC2 console, or from the command line with jq:

aws ec2 describe-instances | jq '.Reservations[0].Instances[0].NetworkInterfaces[0].SubnetId'

Create Instances from the Command Line

You can launch instances using the run-instances command. This command has a lot of options, but the ones that matter most are:

aws ec2 run-instances 
--image-id ami-00000000 
--count 1 
--instance-type t2.micro 
--key-name MyKeyPair 
--security-group-ids sg-00000000 
--subnet-id subnet-00000000 
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=cli-generated}]'

You’ll have to replace the AMI ID, key pair name, security group ID, and subnet ID with your own values. The final --tag-specification directive assigns the name to the instance, which you’ll want to change as well.

This will launch a basic t2.micro micro instance in your account’s default region. This command will output a lot of JSON data:

{
    "OwnerId": "123456789012",
    "ReservationId": "r-5875ca20",
    "Groups": [
        {
            "GroupName": "my-sg",
            "GroupId": "sg-903004f8"
        }
    ],
    "Instances": [
        {
            "Monitoring": {
                "State": "disabled"
            },
            "PublicDnsName": null,
            "Platform": "windows",
            "State": {
                "Code": 0,
                "Name": "pending"
            },
            "EbsOptimized": false,
            "LaunchTime": "2013-07-19T02:42:39.000Z",
            "PrivateIpAddress": "10.0.1.114",
            "ProductCodes": [],
            "VpcId": "vpc-1a2b3c4d",
            "InstanceId": "i-5203422c",
            "ImageId": "ami-173d747e",
            "PrivateDnsName": ip-10-0-1-114.ec2.internal,
            "KeyName": "MyKeyPair",
            "SecurityGroups": [
                {
                    "GroupName": "my-sg",
                    "GroupId": "sg-903004f8"
                }
            ],
            "ClientToken": null,
            "SubnetId": "subnet-6e7f829e",
            "InstanceType": "t2.micro",
            "NetworkInterfaces": [
                {
                    "Status": "in-use",
                    "SourceDestCheck": true,
                    "VpcId": "vpc-1a2b3c4d",
                    "Description": "Primary network interface",
                    "NetworkInterfaceId": "eni-a7edb1c9",
                    "PrivateIpAddresses": [
                        {
                            "PrivateDnsName": "ip-10-0-1-114.ec2.internal",
                            "Primary": true,
                            "PrivateIpAddress": "10.0.1.114"
                        }
                    ],
                    "PrivateDnsName": "ip-10-0-1-114.ec2.internal",
                    "Attachment": {
                        "Status": "attached",
                        "DeviceIndex": 0,
                        "DeleteOnTermination": true,
                        "AttachmentId": "eni-attach-52193138",
                        "AttachTime": "2013-07-19T02:42:39.000Z"
                    },
                    "Groups": [
                        {
                            "GroupName": "my-sg",
                            "GroupId": "sg-903004f8"
                        }
                    ],
                    "SubnetId": "subnet-6e7f829e",
                    "OwnerId": "123456789012",
                    "PrivateIpAddress": "10.0.1.114"
                }              
            ],
            "SourceDestCheck": true,
            "Placement": {
                "Tenancy": "default",
                "GroupName": null,
                "AvailabilityZone": "us-west-2b"
            },
            "Hypervisor": "xen",
            "BlockDeviceMappings": [
                {
                    "DeviceName": "/dev/sda1",
                    "Ebs": {
                        "Status": "attached",
                        "DeleteOnTermination": true,
                        "VolumeId": "vol-877166c8",
                        "AttachTime": "2013-07-19T02:42:39.000Z"
                    }
                }              
            ],
            "Architecture": "x86_64",
            "StateReason": {
                "Message": "pending",
                "Code": "pending"
            },
            "RootDeviceName": "/dev/sda1",
            "VirtualizationType": "hvm",
            "RootDeviceType": "ebs",
            "Tags": [
                {
                    "Value": "MyInstance",
                    "Key": "Name"
                }
            ],
            "AmiLaunchIndex": 0
        }
    ]
}

You’ll probably want to pipe this to a file and save it for later reference. You can use a utility like jq to work with JSON on the command line, or import it into a Python or Node script for easy access.

ALSO READ  How To Disable HiSearch on Huawei Mate 20 Series Devices

Once the instance is created, you’ll be able to access it over SSH from its public IP address, or private IP address if you have an OpenVPN server running in your subnet.

Setting Up an Install Script

AWS allows you to pass an install script to the instance that will be ran at launch. In this script, you can automatically perform any configuration of the machine you need to do, such as installing and configuring programs.

To pass the script from the CLI, you’ll want to use the --user-data option, and pass the file using file://:

aws ec2 run-instances 
--image-id ami-00000000 
--count 1 
--instance-type t2.micro 
--key-name MyKeyPair 
--security-group-ids sg-00000000 
--subnet-id subnet-00000000 
--tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=cli-generated}]' 
--user-data file://startup_script.sh

This will only run once, and not on every reboot.

Creating a Custom AMI

Amazon Machine Images (AMIs) are an easy way to create copies of servers with software preinstalled, so you don’t have to run an install script every time. This can make your boot process much quicker, as you won’t have to wait for software to install on new instances.

To create one, you’ll likely want to start from scratch to ensure everything is correct, though you can just use your preconfigured server as a template.

If you’re starting from scratch, create a new t2.micro instance with a base AMI like Amazon Linux 2 to serve as your starting point. Configure it with all the programs you need, and verify everything works as intended.

Then, from the AWS EC2 console, right-click on your instance and choose Image > Create Image:

ALSO READ  How to Configure Your Microphone and Headset in Discord

Create custom AMI

This will automatically create an AMI based on your instance. You can also create AMI based on snapshots, but this wizard will create a snapshot for you to create the AMI with.

You AMI may take a bit to create, but once it’s done you’ll be able to access it in the AMI tab of the EC2 console. You can take the AMI ID and use it to create new instances based off that AMI. You can also use it as the base for an Autoscaling Group launch template, which is covered in our guide to using AMIs.



READ SOURCE

LEAVE A REPLY

Please enter your comment!
Please enter your name here