# Packer Usage

We will use `packer` as the tool to build the AWS's AMI. You can follow [this guide](https://developer.hashicorp.com/packer/tutorials/aws-get-started/aws-get-started-build-image) to get more information.

1. Install `Packer` by following [this guide](https://developer.hashicorp.com/packer/install).
2. Enter the folder of `*.pkr.hcl`
3. Set your credentials of AWS, please be aware you need have the access to create the AMI:

    ```bash
    export AWS_ACCESS_KEY_ID="<YOUR_AWS_ACCESS_KEY_ID>"
    export AWS_SECRET_ACCESS_KEY="<YOUR_AWS_SECRET_ACCESS_KEY>"
    ```

4. (Optional) If you want a minimal set permissions for this user, you can use [this document](https://developer.hashicorp.com/packer/integrations/hashicorp/amazon#iam-task-or-instance-role) to create a user:

    ```json
    {
    "Version": "2012-10-17",
    "Statement": [
        {
        "Effect": "Allow",
        "Action": [
            "ec2:AttachVolume",
            "ec2:AuthorizeSecurityGroupIngress",
            "ec2:CopyImage",
            "ec2:CreateImage",
            "ec2:CreateKeyPair",
            "ec2:CreateSecurityGroup",
            "ec2:CreateSnapshot",
            "ec2:CreateTags",
            "ec2:CreateVolume",
            "ec2:DeleteKeyPair",
            "ec2:DeleteSecurityGroup",
            "ec2:DeleteSnapshot",
            "ec2:DeleteVolume",
            "ec2:DeregisterImage",
            "ec2:DescribeImageAttribute",
            "ec2:DescribeImages",
            "ec2:DescribeInstances",
            "ec2:DescribeInstanceStatus",
            "ec2:DescribeRegions",
            "ec2:DescribeSecurityGroups",
            "ec2:DescribeSnapshots",
            "ec2:DescribeSubnets",
            "ec2:DescribeTags",
            "ec2:DescribeVolumes",
            "ec2:DetachVolume",
            "ec2:GetPasswordData",
            "ec2:ModifyImageAttribute",
            "ec2:ModifyInstanceAttribute",
            "ec2:ModifySnapshotAttribute",
            "ec2:RegisterImage",
            "ec2:RunInstances",
            "ec2:StopInstances",
            "ec2:TerminateInstances"
        ],
        "Resource": "*"
        }
    ]
    }
    ```

5. If it is the first time that you run the packer, you need to run `packer init .` to download all of the plugins.
6. Run `packer build <YOUR_FILE_NAME>.pkr.hcl` to build. If it is success, you will see a la output:

    ```output
    ...
    Build 'genai.amazon-ebs.ubuntu' finished after 22 minutes 59 seconds.

    ==> Wait completed after 22 minutes 59 seconds

    ==> Builds finished. The artifacts of successful builds are:
    --> genai.amazon-ebs.ubuntu: AMIs were created:
    us-west-2: ami-06ac6b412766a3137
    ```

7. Then, you can copy the image to the other regions.

    ```bash
    aws ec2 copy-image --region <TARGET_REGION> --name <NEW_AMI_NAME> --source-image-id '<IMAGE_ID>' --source-region <SRC_REGION>
    ```
