Once VPC and subnets with related gateways/routes are ready, you can create EC2 instances. However, at least one access control needs to be created beforehand; this is called a security group. It can define ingress (incoming network access) and egress (outgoing network access) firewall rules.
In the following example, a security group and a rule for public subnet hosts are created that allows SSH from your machine's IP address, as well as open HTTP (80/tcp) world-wide:
//create one security group for public subnet $ aws ec2 create-security-group --vpc-id vpc-0ca37d4650963adbb --group-name public --description "public facing host"
{
"GroupId": "sg-03973d9109a19e592"
}
//check your machine's public IP (if not sure, use 0.0.0.0/0 as temporary) $ curl ifconfig.co 98.234.106.21
//public facing machine allows ssh only from your machine $ aws ec2 authorize-security-group-ingress --group-id sg-03973d9109a19e592 --protocol tcp --port 22 --cidr 98.234.106.21/32
//public facing machine allow HTTP access from any host (0.0.0.0/0) $ aws ec2 authorize-security-group-ingress --group-id sg-03973d9109a19e592 --protocol tcp --port 80 --cidr 0.0.0.0/0
Next, create a security group for a private subnet host that allows SSH from the public subnet host. In this case, specifying a public subnet security group ID (sg-03973d9109a19e592) instead of a CIDR block is convenient:
//create security group for private subnet $ aws ec2 create-security-group --vpc-id vpc-0ca37d4650963adbb --group-name private --description "private subnet host"
{
"GroupId": "sg-0f4058a729e2c207e"
}
//private subnet allows ssh only from public subnet host security group $ aws ec2 authorize-security-group-ingress --group-id sg-0f4058a729e2c207e --protocol tcp --port 22 --source-group sg-03973d9109a19e592
//it also allows HTTP (80/TCP) from public subnet security group
$ aws ec2 authorize-security-group-ingress --group-id sg-0f4058a729e2c207e --protocol tcp --port 80 --source-group sg-03973d9109a19e592
Overall, there are two security groups that have been created, as follows:
Name |
Security group ID |
Allow ssh (22/TCP) |
Allow HTTP (80/TCP) |
Public |
sg-03973d9109a19e592 |
Your machine (98.234.106.21) |
0.0.0.0/0 |
Private |
sg-0f4058a729e2c207e |
public sg (sg-03973d9109a19e592) |
public sg (sg-03973d9109a19e592) |