---
# System prepended metadata

title: GROUP4 - Create AMI

---

# GROUP4 - Create AMI
![](https://i.imgur.com/lW1FQe0.png)

## Init variable
```
$keyName = "tuannd67"
$sgGroupId = "sg-05306f6795fe2025b"
$subnetId = "subnet-061a0f7fde133b9b8"
$Server1Name = "group4-svr1"
```

## Create Server 1 with nginx (userdata)
```
$Server1ID = aws ec2 run-instances `
    --image-id ami-0574da719dca65348 `
    --instance-type t2.micro `
    --key-name $keyName `
    --security-group-ids $sgGroupId `
    --subnet-id $subnetId `
    --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=$Server1Name}]" `
    --associate-public-ip-address `
    --query "Instances[0].InstanceId" `
    --user-data file://server1_user_data.txt
```
### server1_user_data.txt
```
#!/bin/bash
sudo apt-get update
sudo apt-get upgrade -y
sudo apt-get install nginx -y
sudo systemctl enable nginx
sudo systemctl start nginx
```
## Create AMI from Server 1

```
$Server1AmiID = aws ec2 create-image `
    --instance-id $Server1ID `
    --name "$Server1Name-nginx-ami" `
    --tag-specifications "ResourceType=image,Tags=[{Key=Name,Value=$Server1Name-nginx-ami}]" `
    --query "ImageId"
```

## Launch new EC2 with AMI (Server 1)
```
$Server2FromAmiID = aws ec2 run-instances `
    --image-id $Server1AmiID `
    --instance-type t2.micro `
    --key-name $keyName `
    --security-group-ids $sgGroupId `
    --subnet-id $subnetId `
    --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=$Server1Name-from-ami}]" `
    --associate-public-ip-address `
    --query "Instances[0].InstanceId"
```


# Clean up
```
$Server1AmiSnapshotID = aws ec2 describe-images `
    --filters "Name=tag:Name,Values=$Server1Name-nginx-ami" `
    --query "Images[*].BlockDeviceMappings[*].Ebs[].SnapshotId | [0]"
    
aws ec2 terminate-instances --instance-ids $Server1ID
aws ec2 terminate-instances --instance-ids $Server2FromAmiID
aws ec2 deregister-image --image-id $Server1AmiID
aws ec2 delete-snapshot --snapshot-id $Server1AmiSnapshotID
```