Location>code7788 >text

Why use the AWS CLI when I'm too lazy to click a mouse?

Popularity:423 ℃/2024-09-28 20:27:03

In this blog, we dive into the world of AWS CLI together, starting from scratch and building a home in the cloud step by step. The basic features and usage scenarios of AWS CLI will be introduced, how to create IAM users, VPCs, subnets, security groups, EC2 instances, etc., and even build an Application Load Balancer (ALB). Whether you're a beginner or a basic user, you'll be able to master the AWS CLI with this guide, making you more comfortable operating in the cloud. Ready? Let's start this journey to the cloud together!

Introduction to the AWS CLI

What is the AWS CLI

The AWS CLI (Command Line Interface) is a unified tool that allows users to manage and automate AWS services from the command line. It provides direct access to AWS APIs, enabling users to perform various operations in the terminal without relying on a graphical user interface (GUI).

Basic Functions and Usage Scenarios

  • Resource management: Create, update, and delete AWS resources such as EC2 instances, S3 storage buckets, and VPCs.
  • Automated tasks: Batch processing of resources through scripts to support automated deployment and management processes.
  • configuration management: Quickly configure properties of AWS resources, such as security groups, IAM permissions, and more.
  • Monitoring and Querying: Use the CLI to query resource status and health, view logs and metrics.
  • Integration and Compatibility: Integrate with other development tools and CI/CD pipelines to improve development efficiency.

 

I. Create an IAM user and configure aws cli

 

1. Open iam service

Type "iam" in the search box.

 

2. Create users

Click on "Roles" on the left, "Create User" on the right.

Enter user name

I'll just call it aws-cli here, feel free to

3. Setting permissions

I'll just give AdministratorAccess permission here for testing convenience. I'll be blogging specifically about IAM later. Please look forward to it!

Select "Direct Attachment Policy", then enter "AdministratorAccess", select AdministratorAccess, and next step.

4. Viewing and creation

See if the permissions are set correctly, and click Create User if it's okay.

You can see that you have been prompted to create a successful

 

5. Creating keys

Next we'll create the key, the accesskey

Click on the user name

Click Security Credentials - > Create Access Key

Just choose the first one

Setting up labels

I'm still using aws-cli here.

You can see that it has been created successfully, to prevent forgetting, it is recommended to download the .csv file

6. Configure aws cli

aws configure, just enter the contents of the .csv file, for the region I'm using us-west-1 (U.S.-West California), and for the format choose json.

For more information, please refer to the aws pipe web site: /cli/latest/userguide/.

Check that the aws cli is configured correctly

aws ec2 describe-instances

The aws cli is configured correctly.

Reproduced with permission from the original source at the beginning of this article: /Sunzz/p/18432935

 

II. Network configuration

1. Create vpc

aws ec2 create-vpc --cidr-block 10.0.0.0/16 

The output is as follows:

For easy identification, set a name for the vpcaws-cli-vpc (optional)

aws ec2 create-tags --resources vpc-0a3a6fd36df03aea6 --tags Key=Name,Value="aws-cli-vpc"

You can see on the console that the vpc has been successfully created with the vpc id of vpc-0a3a6fd36df03aea6 and the name aws-cli-vpc

2.Create subnet

Setting the cidr

Here the subnet segment is set to 10.0.1.0/24

aws ec2 create-subnet --vpc-id vpc-0a3a6fd36df03aea6 --cidr-block 10.0.1.0/24

The output is as follows:

Name the subnet

Convenient labeling (optional)

aws ec2 create-tags --resources subnet-08b88d4a329f823a9 --tags Key=Name,Value=aws-cli-subnet01

Checking the console, you can see that the subnet id issubnet-08b88d4a329f823a9 with the name ofaws-cli-subnet01, subnet with cidr 10.0.1.0/24 has been created

As ALB (Application Load Balancer) must set up multiple availability zones to ensure high availability and fault tolerance. If one availability zone fails, traffic is automatically forwarded to instances in other availability zones to maintain service availability. This configuration reduces the risk of a single point of failure and improves application reliability and stability. So again, create a subnet aws-cli-subnet02 with a cidr of 10.0.2.0/24 and an availability zone of us-west-1a.

aws ec2 create-subnet \
  --vpc-id vpc-0a3a6fd36df03aea6 \
  --cidr-block 10.0.2.0/24 \
  --availability-zone us-west-1a \
  --tag-specifications 'ResourceType=subnet,Tags=[{Key=Name,Value=aws-cli-subnet02}]'

View all subnet information

aws ec2 describe-subnets --filters "Name=vpc-id,Values=vpc-0a3a6fd36df03aea6" --query "Subnets[*].[Tags[?Key=='Name'].Value | [0], SubnetId, CidrBlock]" --output table

-----------------------------------------------------------------

|                        DescribeSubnets                        |

+-------------------+----------------------------+--------------+

|  aws-cli-subnet02 |  subnet-03dd42c387a0f3539  |  10.0.2.0/24 |

|  aws-cli-subnet01 |  subnet-08b88d4a329f823a9  |  10.0.1.0/24 |

+-------------------+----------------------------+--------------+

3. Gateway creation

Creating a Gateway

aws ec2 create-internet-gateway 

The output is as follows:

Come back with a name for easy identification (optional)

aws ec2 create-tags --resources igw-0787503762feb666c --tags Key=Name,Value=aws-cli-igw

Attach gateway to vpc

aws ec2 attach-internet-gateway --internet-gateway-id igw-0787503762feb666c --vpc-id vpc-0a3a6fd36df03aea6

This time we'll use the aws command to view the gateway and vpc additional information

aws ec2 describe-internet-gateways --internet-gateway-ids igw-0787503762feb666c

The output is as follows:

4. Updating of the routing table

Since AWS automatically creates a default routing table when creating a VPC

Add a route that will target the0.0.0.0/0 traffic to your Internet Gateway to be able to access the Internet.

View routing table id

aws ec2 describe-route-tables --query 'RouteTables[*].[RouteTableId, VpcId]' --output table

The output is as follows:

List the current two vpc ids and their corresponding routing table ids

Here I just want to query the routing table ID of the vpc vpc-0a3a6fd36df03aea6 that was created just now

aws ec2 describe-route-tables --filters "Name=vpc-id,Values=vpc-0a3a6fd36df03aea6" --query 'RouteTables[*].[RouteTableId]' --output table
---------------------------
|   DescribeRouteTables   |
+-------------------------+
|  rtb-094254eb8def0f2fc  |
+-------------------------+

Updating the routing table

aws ec2 create-route --route-table-id rtb-094254eb8def0f2fc --destination-cidr-block 0.0.0.0/0 --gateway-id igw-0787503762feb666c 
{
    "Return": true
}

You can query the routing table details with the following command

 aws ec2 describe-route-tables --route-table-ids rtb-094254eb8def0f2fc

5. Creation of security groups

Here create a security group named aws-cli-sg01 that runs rules for all IP addresses connecting to port 22 and ping.

aws ec2 create-security-group --group-name aws-cli-sg01 --description "Security group for AWS CLI demo" --vpc-id vpc-0a3a6fd36df03aea6
exports:
{
    "GroupId": "sg-0a986a2e312c0c947"
}

Allow all IP connections to port 22

aws ec2 authorize-security-group-ingress --group-id sg-0a986a2e312c0c947 --protocol tcp --port 22 --cidr 0.0.0.0/0

Run all ip access to port 80

aws ec2 authorize-security-group-ingress --group-id sg-0a986a2e312c0c947 --protocol tcp --port 80 --cidr 0.0.0.0/0

Allow ICMP (ping):

aws ec2 authorize-security-group-ingress --group-id sg-0a986a2e312c0c947 --protocol icmp --port -1 --cidr 0.0.0.0/0

Viewing Security Group Information

aws ec2 describe-security-groups --filters "Name=group-name,Values=aws-cli-sg01"

View only security group ids

aws ec2 describe-security-groups --filters "Name=group-name,Values=aws-cli-sg01" --query "SecurityGroups[*].GroupId" --output text
exports:
sg-0a986a2e312c0c947

Reproduced with permission from the original source at the beginning of this article: /Sunzz/p/18432935

 

III. Creating a server

1. Creating key pairs

Here create a key pair called aws-cli-key

 aws ec2 create-key-pair --key-name aws-cli-key --query 'KeyMaterial' --output text > 

This creates the key pair and saves the private key to the file. Make sure to set the permissions of this file to read-only to protect the private key:

chmod 400 

2. Creation of ec2 instances

aws ec2 run-instances \
  --image-id ami-047d7c33f6e7b4bc4 \
  --count 1 \
  --instance-type  \
  --subnet-id subnet-08b88d4a329f823a9 \
  --security-group-ids sg-0a986a2e312c0c947 \
  --key-name aws-cli-key \
  --block-device-mappings "[{\"DeviceName\":\"/dev/xvda\",\"Ebs\":{\"VolumeSize\":10}}]" \
  --tag-specifications 'ResourceType=instance,Tags=[{Key=Name,Value=aws-cli-ec2-instance}]' \
  --associate-public-ip-address

Viewing ec2 instance information

aws ec2 describe-instances \
  --filters "Name=instance-state-name,Values=running" \
  --query "Reservations[*].Instances[*].[Tags[?Key=='Name'].Value | [0], InstanceId, , InstanceType, PublicIpAddress]" \
  --output table

3. ssh login to ec2 server

Since we are using amazon linux, the login user is ec2-user.

ssh -i   [email protected]

network test

You can see that you can ping through, indicating that the security group settings are also as expected.

4. Install nginx

Preparing for the creation of an alb later

sudo yum install nginx -y
sudo systemctl start nginx

Reproduced with permission from the original source at the beginning of this article: /Sunzz/p/18432935

 

IV. Creating a load-balanced alb

1. Creation of target groups

First, you need to create a destination group and configure it to forward traffic to port 80 of the EC2 instance.

aws elbv2 create-target-group \
  --name aws-cli-target-group \
  --protocol HTTP \
  --port 80 \
  --vpc-id vpc-0a3a6fd36df03aea6 \
  --health-check-protocol HTTP \
  --health-check-path / \
  --output json

2. Registration objectives

Register your EC2 instance in the target group:

aws elbv2 register-targets \
  --target-group-arn arn:aws:elasticloadbalancing:us-west-1:xxxxxxxx:targetgroup/aws-cli-target-group/4c9f519307ef326f \
  --targets Id=i-0ebebdb8eda7d10c9

--target-group-arn from create-target-group output

--targets is the associated ec2

3. Create a load balancer

aws elbv2 create-load-balancer \
  --name aws-cli-load-balancer \
  --subnets subnet-08b88d4a329f823a9 subnet-03dd42c387a0f3539 \
  --security-groups sg-0a986a2e312c0c947 \
  --scheme internet-facing \
  --output json

4. Create a listener

Create a listener that forwards traffic from the ALB to the target group:

aws elbv2 create-listener \
  --load-balancer-arn arn:aws:elasticloadbalancing:us-west-1:xxxxxx:loadbalancer/app/aws-cli-load-balancer/2626f9962b63d4d5 \
  --protocol HTTP \
  --port 80 \
  --default-actions Type=forward,TargetGroupArn=arn:aws:elasticloadbalancing:us-west-1:712368562757:targetgroup/aws-cli-target-group/4c9f519307ef326f

The --load-balancer-arn value comes from the output of the previous step

5. Checking ALB status

Use the following command to view the ALB status and:

aws elbv2 describe-load-balancers

View the DNS name:

aws elbv2 describe-load-balancers --names aws-cli-load-balancer --query "LoadBalancers[*].[DNSName]" --output table

-----------------------------------------------------------------

|                     DescribeLoadBalancers                     |

+---------------------------------------------------------------+

|    |

+---------------------------------------------------------------+

6. Access testing

For more details and resources, see the official AWS CLI documentation:AWS CLI Documentation

In this blog, we have successfully created VPCs, Subnets, Security Groups, Internet Gateways, EC2 instances, and ALBs using AWS CLI, and the whole process was like a nice trip in the cloud. If you are interested in other features of AWS CLI, feel free to leave a comment in the comment section and tell me what you would like to know!

Remember to come back and visit often, the adventure in the clouds never stops!