# Set up application common

All applications share a common set of infrastructure components that are set up in this guide.

The stack sets up an ECS cluster for the current `Environment` and a rule for fetching public images through the ECR repository.

## Step 1: Add and configure the `app-common` package

```bash title="repo-iac/environments/dev/"
ok pkg add app-common
```

Update `package-config.yml` with your preferences.

## Step 2: Install the package

```bash title="repo-iac/environments/dev/app-common/"
ok pkg install
```

## Step 3: Initialize and apply the `app-common` stack

```bash title="repo-iac/environments/dev/app-common/"
terraform init
terraform apply
```

## Step 4: Perform initial pull for ECR

<!-- prettier-ignore-start -->
!!! info "What's this?"
    If you already pulled the following image:

    ```hcl
    public.ecr.aws/nginx/nginx:latest
    ```

    You can now pull the image via the ECR pull through cache address:

    ```hcl
    ${var.account_id}.dkr.ecr.${var.region}.amazonaws.com/${var.environment}-ecr-public/nginx/nginx:latest
    ```

    In other words, the original upstream registry URL:

    ```
    public.ecr.aws/
    ```

    Is replaced with:

    ```
    ${var.account_id}.dkr.ecr.${var.region}.amazonaws.com/${var.environment}-ecr-public/
    ```
<!-- prettier-ignore-end -->

ECR pull through cache is enabled by default, but can be configured with the following:

```yaml title="repo-iac/environments/dev/app-common/package-config.yml"
EcrPullThroughCache:
  Enable: true
```

Each image gets a separate ECR repository and needs a unique lifecycle policy, specify
the upstream images you need:

```hcl title="repo-iac/environments/dev/app-common/config_override.tf"
pull_through_cache_repositories = [
  "aws-observability/aws-otel-collector",
  "nginx/nginx-prometheus-exporter",
  "nginx/nginx"
]
pull_through_cache_ecr_max_image_count = 15
```

Then run the following to populate ECR with the latest version of `nginx/nginx`:

```bash title="repo-iac/environments/dev/app-common/bin/"
bash _gp_ecr_pull_through_cache_init.sh -i nginx/nginx
```

If a specific tag is required, use the `-t` flag:

```bash title="repo-iac/environments/dev/app-common/bin/"
bash _gp_ecr_pull_through_cache_init.sh -i nginx/nginx -t alpine-slim
```

Repeat for each image in the list defined earlier in `config_override.tf`.

Later pulls don't require internet access.

## Step 5: Verify

=== "AWS CLI"

    To verify that a new ECS cluster has been created, run the following command:

    ```bash
    aws ecs list-clusters | jq '.clusterArns'
    ```

    The output list should contain the name of the ECS cluster you just created.

=== "AWS console"

    Sign in to the AWS console and navigate to **ECS**.

    The list should contain the name of the ECS cluster you just created.

---

--8<-- "includes/commit.md"

You're done with the Application setup.

## Next step

Set up [CI/CD common](set-up-cicd-common.md).
