

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 的預留容量範例 AWS CodeBuild
<a name="reserved-capacity-samples"></a>

這些範例可用於實驗 CodeBuild 中的預留容量機群。

**Topics**
+ [使用預留容量範例進行快取](#reserved-capacity-samples.caching)

## 使用預留容量範例進行快取
<a name="reserved-capacity-samples.caching"></a>

快取可以存放組建環境的可重複使用部分，並在多個組建間使用這些部分。此範例示範如何使用預留容量在建置專案中啟用快取。如需詳細資訊，請參閱[快取建置以改善效能](build-caching.md)。

您可以先在專案設定中指定一或多個快取模式：

```
Cache:
        Type: LOCAL
        Modes:
          - LOCAL_CUSTOM_CACHE
          - LOCAL_DOCKER_LAYER_CACHE
          - LOCAL_SOURCE_CACHE
```

**注意**  
請務必啟用特權模式，才能使用 Docker layer 快取。

您的專案 buildspec 設定應如下所示：

```
version: 0.2
      phases:
        build:
          commands:
            - echo testing local source cache
            - touch /codebuild/cache/workspace/foobar.txt
            - git checkout -b cached_branch
            - echo testing local docker layer cache
            - docker run alpine:3.14 2>&1 | grep 'Pulling from' || exit 1
            - echo testing local custom cache
            - touch foo
            - mkdir bar && ln -s foo bar/foo2
            - mkdir bar/bar && touch bar/bar/foo3 && touch bar/bar/foo4
            - "[ -f foo ] || exit 1"
            - "[ -L bar/foo2 ] || exit 1"
            - "[ -f bar/bar/foo3 ] || exit 1"
            - "[ -f bar/bar/foo4 ] || exit 1"
      cache:
        paths:
           - './foo'
           - './bar/**/*'
           - './bar/bar/foo3'
```

您可以從使用新專案執行組建開始，以植入快取。完成後，您應該使用覆寫的 buildspec 啟動另一個組建，如下所示：

```
version: 0.2
      phases:
        build:
          commands:
            - echo testing local source cache
            - git branch | if grep 'cached_branch'; then (exit 0); else (exit 1); fi
            - ls /codebuild/cache/workspace | if grep 'foobar.txt'; then (exit 0); else (exit 1); fi
            - echo testing local docker layer cache
            - docker run alpine:3.14 2>&1 | if grep 'Pulling from'; then (exit 1); else (exit 0); fi
            - echo testing local custom cache
            - "[ -f foo ] || exit 1"
            - "[ -L bar/foo2 ] || exit 1"
            - "[ -f bar/bar/foo3 ] || exit 1"
            - "[ -f bar/bar/foo4 ] || exit 1"
      cache:
        paths:
           - './foo'
           - './bar/**/*'
           - './bar/bar/foo3'
```