Master AWS CLI with this comprehensive guide! Learn how to install, configure, and use AWS CLI commands for EC2, S3, IAM, Lambda, CloudFormation, and more. Boost efficiency with automation and best practices. #centlinux #linux #awsforbeginners
Table of Contents
1. Introduction
AWS Command Line Interface (AWS CLI) is a powerful tool that allows users to manage AWS services through command-line commands. It simplifies cloud management by providing a direct way to interact with AWS resources without using the graphical AWS Management Console.
With AWS CLI, developers, system administrators, and cloud engineers can automate workflows, manage cloud resources, and execute commands efficiently. Whether you’re working with Amazon S3, EC2, IAM, Lambda, or other AWS services, AWS CLI provides an effective and scriptable way to streamline operations.
Why Use AWS CLI?
- Automates repetitive cloud management tasks
- Reduces the need for manual interaction with the AWS Console
- Allows bulk operations using shell scripts
- Provides programmatic access to AWS services
2. What is AWS CLI?
AWS CLI is a command-line tool that interacts with AWS services using commands instead of a graphical interface. It is built on top of AWS SDKs and provides complete control over AWS services.
Key Features of AWS CLI
- Supports multiple AWS services, including S3, EC2, IAM, Lambda, and more
- Enables scripting and automation of AWS tasks
- Works across Windows, macOS, and Linux
- Supports AWS profiles for managing multiple accounts
- Provides JSON-formatted output for easy parsing
AWS CLI vs. AWS Management Console
Feature | AWS CLI | AWS Management Console |
---|---|---|
User Interface | Command-line | Graphical UI |
Automation | Supports scripting & automation | Limited automation features |
Accessibility | Requires terminal knowledge | Easy for beginners |
Bulk Operations | Easily managed via scripts | Requires manual input |
Recommended Training: Ultimate AWS Certified Cloud Practitioner CLF-C02 2025 from Stephane Maarek
3. Installing AWS CLI
AWS CLI is available for Windows, macOS, and Linux. Follow the steps below to install it on your preferred platform.
Windows Installation
- Download the AWS CLI MSI installer from the AWS website.
- Run the installer and follow the setup wizard.
- Verify the installation by running:
aws --version
macOS Installation
Install AWS CLI using Homebrew:
brew install awscli
Verify the installation:
aws --version
Linux Installation
Download the installer:
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
Unzip the installer:
unzip awscliv2.zip
Run the installation script:
sudo ./aws/install
Verify installation:
aws --version
Watch our video Tutorial to install AWS CLI on Linux:
4. Configuring AWS CLI
Before using AWS CLI, you need to configure it with your AWS credentials.
Setting Up AWS Credentials
Run the following command to configure AWS CLI:
aws configure
You will be prompted to enter:
- AWS Access Key ID
- AWS Secret Access Key
- Default AWS Region
- Output format (json, table, or text)
Managing Multiple AWS Profiles
You can configure multiple profiles for different AWS accounts:
aws configure --profile my-second-profile
To use a specific profile, run:
aws s3 ls --profile my-second-profile
5. AWS CLI Commands for Beginners
AWS CLI provides a wide range of commands for managing AWS services. Here are some essential commands to get started:
Listing S3 Buckets
aws s3 ls
This command lists all S3 buckets in your AWS account.
Uploading a File to S3
aws s3 cp myfile.txt s3://my-bucket/
Downloading a File from S3
aws s3 cp s3://my-bucket/myfile.txt .
Checking Running EC2 Instances
aws ec2 describe-instances
Creating a New IAM User
aws iam create-user --user-name newuser
These are just a few basic commands to get started with AWS CLI. Mastering these will help in managing AWS services efficiently.
6. Advanced AWS CLI Commands
As you get comfortable with AWS CLI basics, it’s time to explore more advanced commands that help manage AWS resources efficiently.
Managing EC2 Instances
AWS CLI allows you to start, stop, and terminate EC2 instances directly from the command line.
Start an EC2 instance:
aws ec2 start-instances --instance-ids i-0abcd1234efgh5678
Stop an EC2 instance:
aws ec2 stop-instances --instance-ids i-0abcd1234efgh5678
Terminate an EC2 instance:
aws ec2 terminate-instances --instance-ids i-0abcd1234efgh5678
Working with IAM Policies and Roles
List IAM policies
aws iam list-policies
Attach a policy to a user
aws iam attach-user-policy --user-name newuser --policy-arn arn:aws:iam::aws:policy/AmazonS3FullAccess
Detach a policy from a user
aws iam detach-user-policy --user-name newuser --policy-arn arn:aws:iam::aws:policy/AmazonS3FullAccess
Automating Tasks with AWS CLI Scripts
Using shell scripts, you can automate AWS operations like creating backups, managing EC2 instances, or rotating access keys.
Example: Script to Start All Stopped EC2 Instances
#!/bin/bash
aws ec2 describe-instances --query "Reservations[*].Instances[*].[InstanceId,State.Name]" --output text | awk '$2=="stopped"{print $1}' | while read instance; do
aws ec2 start-instances --instance-ids $instance
done
7. Working with S3 Using AWS CLI
Amazon S3 (Simple Storage Service) is one of the most commonly used AWS services. AWS CLI makes it easy to manage S3 buckets and objects.
Creating and Deleting S3 Buckets
Create an S3 bucket
aws s3 mb s3://my-new-bucket
Delete an S3 bucket
aws s3 rb s3://my-old-bucket --force
Uploading and Downloading Files
Upload a file to an S3 bucket
aws s3 cp myfile.txt s3://my-bucket/
Download a file from an S3 bucket
aws s3 cp s3://my-bucket/myfile.txt .
Setting Permissions and Managing ACLs
Make a file publicly readable
aws s3api put-object-acl --bucket my-bucket --key myfile.txt --acl public-read
List permissions of a file
aws s3api get-object-acl --bucket my-bucket --key myfile.txt
8. Managing EC2 Instances with AWS CLI
EC2 (Elastic Compute Cloud) is a core AWS service for running virtual machines. AWS CLI allows you to efficiently manage EC2 instances.
Launching a New EC2 Instance
aws ec2 run-instances --image-id ami-12345678 --count 1 --instance-type t2.micro --key-name MyKeyPair --security-groups MySecurityGroup
Viewing and Modifying Instance Details
Describe all running instances
aws ec2 describe-instances --query "Reservations[*].Instances[*].[InstanceId,State.Name,PublicIpAddress]"
Modify an instance type
aws ec2 modify-instance-attribute --instance-id i-0abcd1234efgh5678 --instance-type t3.micro
Stopping and Terminating Instances
Stop an instance
aws ec2 stop-instances --instance-ids i-0abcd1234efgh5678
Terminate an instance
aws ec2 terminate-instances --instance-ids i-0abcd1234efgh5678
9. Using AWS CLI for IAM Management
IAM (Identity and Access Management) is critical for securing AWS resources. AWS CLI provides full control over users, groups, and roles.
Creating and Managing IAM Users
Create a new IAM user
aws iam create-user --user-name newuser
Delete an IAM user
aws iam delete-user --user-name olduser
Assigning Roles and Permissions
Attach a policy to a user
aws iam attach-user-policy --user-name newuser --policy-arn arn:aws:iam::aws:policy/AmazonS3FullAccess
List policies attached to a user
aws iam list-attached-user-policies --user-name newuser
Generating Security Credentials
Create an access key for a user
aws iam create-access-key --user-name newuser
Delete an access key
aws iam delete-access-key --access-key-id ABCDEFGHIJKLMNOPQRST --user-name newuser
10. Automating Tasks with AWS CLI and Scripts
Automation is one of the key advantages of AWS CLI. By using shell scripts, you can schedule and automate AWS tasks.
Writing Shell Scripts for Automation
Example: Auto Backup S3 Files to Another Bucket
#!/bin/bash
aws s3 sync s3://source-bucket/ s3://backup-bucket/
Scheduling Tasks with Cron Jobs
To automate AWS CLI tasks, use cron jobs on Linux/macOS:
0 2 * * * /path/to/myscript.sh
This will run the script every day at 2 AM.
Best Practices for AWS CLI Automation
- Always use IAM roles instead of access keys
- Encrypt sensitive data using AWS KMS
- Use logging to track automation failures
11. Working with AWS Lambda Using AWS CLI
AWS Lambda lets you run code without managing servers. With AWS CLI, you can create, update, and invoke Lambda functions quickly.
Deploying a Lambda Function
To deploy a Lambda function, you first need a ZIP package containing your function’s code.
Create a ZIP file
zip function.zip index.js
Deploy the Lambda function
aws lambda create-function --function-name MyLambdaFunction --runtime nodejs14.x --role arn:aws:iam::123456789012:role/execution_role --handler index.handler --zip-file fileb://function.zip
Updating and Managing Lambda Configurations
Update Lambda function code
aws lambda update-function-code --function-name MyLambdaFunction --zip-file fileb://function.zip
Change Lambda memory size
aws lambda update-function-configuration --function-name MyLambdaFunction --memory-size 512
Invoking Functions from the Command Line
Invoke a Lambda function
aws lambda invoke --function-name MyLambdaFunction output.txt
Check Lambda logs
aws logs describe-log-streams --log-group-name /aws/lambda/MyLambdaFunction
12. AWS CLI and CloudFormation
AWS CloudFormation enables Infrastructure as Code (IaC). AWS CLI helps you create, update, and delete stacks efficiently.
Creating and Deploying CloudFormation Stacks
Create a new stack
aws cloudformation create-stack --stack-name MyStack --template-body file://template.json
List all stacks
aws cloudformation list-stacks
Updating and Managing Infrastructure as Code
Update an existing stack
aws cloudformation update-stack --stack-name MyStack --template-body file://updated-template.json
Rolling Back and Deleting CloudFormation Stacks
Rollback changes in case of failure
aws cloudformation rollback-stack --stack-name MyStack
Delete a stack
aws cloudformation delete-stack --stack-name MyStack
13. AWS CLI for Monitoring and Logging
AWS CLI can help monitor AWS resources and retrieve logs for troubleshooting.
Checking CloudWatch Metrics
List available metrics
aws cloudwatch list-metrics
Get CPU utilization of an EC2 instance
aws cloudwatch get-metric-statistics --metric-name CPUUtilization --namespace AWS/EC2 --statistics Average --dimensions Name=InstanceId,Value=i-0abcd1234efgh5678 --start-time 2024-01-01T00:00:00Z --end-time 2024-01-02T00:00:00Z --period 3600
Managing AWS Logs Using AWS CLI
List log groups
aws logs describe-log-groups
Retrieve recent log events
aws logs get-log-events --log-group-name /aws/lambda/MyLambdaFunction --log-stream-name latest
Setting Up Alerts and Notifications
Create a CloudWatch alarm
aws cloudwatch put-metric-alarm --alarm-name HighCPUUsage --metric-name CPUUtilization --namespace AWS/EC2 --statistic Average --period 300 --threshold 80 --comparison-operator GreaterThanThreshold --dimensions Name=InstanceId,Value=i-0abcd1234efgh5678 --evaluation-periods 2 --alarm-actions arn:aws:sns:us-east-1:123456789012:MyNotificationTopic
14. Security Best Practices for AWS CLI
Security is crucial when using AWS CLI. Follow these best practices to keep your AWS environment secure.
Using IAM Roles Instead of Access Keys
Avoid using static access keys and instead assign IAM roles to EC2 instances:
aws iam attach-role-policy --role-name MyRole --policy-arn arn:aws:iam::aws:policy/AmazonS3FullAccess
Implementing Multi-Factor Authentication (MFA)
Enable MFA for users with sensitive permissions:
aws iam enable-mfa-device --user-name admin --serial-number arn:aws:iam::123456789012:mfa/admin-mfa --authentication-code-1 123456 --authentication-code-2 654321
Regularly Rotating Credentials
Rotate IAM access keys every 90 days:
aws iam create-access-key --user-name developer
aws iam delete-access-key --access-key-id OLD_ACCESS_KEY_ID --user-name developer
15. Troubleshooting AWS CLI Issues
Even with proper configuration, AWS CLI issues may arise. Here’s how to troubleshoot common problems.
Common Errors and How to Fix Them
Invalid credentials error
aws configure
Reconfigure AWS CLI and ensure your credentials are correct.
Command not found error
aws --version
Ensure AWS CLI is installed properly.
Debugging AWS CLI Commands
Enable debugging mode:
aws s3 ls --debug
Where to Find AWS CLI Logs
AWS CLI logs errors and API calls. Check logs for debugging:
cat ~/.aws/cli/cache/*.json
16. Conclusion
AWS CLI is an essential tool for managing AWS services efficiently. Whether you’re handling EC2 instances, automating S3 backups, deploying Lambda functions, or monitoring CloudWatch metrics, AWS CLI streamlines cloud management with powerful commands and scripting capabilities.
Optimize your cloud infrastructure and secure your servers with my AWS and Linux administration services. Let’s ensure your systems run smoothly. Connect with me on Fiverr now!
By mastering AWS CLI, you can:
- Automate repetitive cloud tasks
- Improve security with IAM role-based access
- Enhance infrastructure management with CloudFormation
- Optimize monitoring and logging with CloudWatch
Start using AWS CLI today and take control of your cloud environment like a pro!
17. FAQs
1. How do I update AWS CLI to the latest version?
To update AWS CLI, use the following command:
Windows:
aws --version # Check version
msiexec.exe /i https://awscli.amazonaws.com/AWSCLIV2.msi
macOS (Homebrew):
brew upgrade awscli
Linux:
sudo curl -s "https://awscli.amazonaws.com/AWSCLIV2.pkg" -o "awscliv2.pkg"
sudo installer -pkg awscliv2.pkg -target /
2. Can I use AWS CLI without configuring credentials?
Yes, you can use AWS CLI without manually configuring credentials by using IAM roles. Attach an IAM role to your EC2 instance to grant necessary permissions automatically.
3. How can I switch between multiple AWS accounts in AWS CLI?
Use AWS CLI profiles to manage multiple accounts:
aws configure --profile my-second-account
aws s3 ls --profile my-second-account
4. What are the best alternatives to AWS CLI?
Alternatives to AWS CLI include:
- AWS SDKs (Python, Java, Go)
- AWS Tools for PowerShell
- AWS CDK (Cloud Development Kit)
5. Does AWS CLI support automation for all AWS services?
Most AWS services are supported, but some advanced configurations may require AWS SDKs or CloudFormation. Check the official AWS CLI documentation for full service compatibility.