

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

# AWS CodeBuild 搭配 Amazon Virtual Private Cloud 使用
<a name="vpc-support"></a>

一般而言， AWS CodeBuild 無法存取 VPC 中的資源。若要啟用存取，您必須在 CodeBuild 專案組態中提供其他 VPC 特定的組態資訊。其中包括 VPC ID、VPC 子網路 ID 和 VPC 安全群組 ID。然後，已啟用 VPC 的建置就能夠存取 VPC 內的資源。如需在 Amazon VPC 中設定 VPC 的詳細資訊，請參閱 [Amazon VPC 使用者指南](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Introduction.html)。

**Topics**
+ [使用案例](#use-cases)
+ [VPC 最佳實務](#best-practices-for-vpcs)
+ [VPCs的限制](#vpc-limitations)
+ [允許 CodeBuild 專案中的 Amazon VPC 存取](enabling-vpc-access-in-projects.md)
+ [對 VPC 設定進行故障診斷](troubleshooting-vpc.md)
+ [使用 VPC 端點](use-vpc-endpoints-with-codebuild.md)
+ [AWS CodeBuild 搭配受管代理伺服器使用](run-codebuild-in-managed-proxy-server.md)
+ [AWS CodeBuild 搭配代理伺服器使用](use-proxy-server.md)
+ [CloudFormation VPC 範本](cloudformation-vpc-template.md)

## 使用案例
<a name="use-cases"></a>

 AWS CodeBuild 建置的 VPC 連線可讓您：
+ 針對私有子網路上隔離的 Amazon RDS 資料庫中的資料，從您的組建執行整合測試。
+ 直接從測試查詢 Amazon ElastiCache 叢集中的資料。
+ 與 Amazon EC2、Amazon ECS 上託管的內部 Web 服務，或使用內部 Elastic Load Balancing 的服務互動。
+ 從自我託管的內部成品儲存庫擷取相依性，例如 PyPI for Python、Maven for Java 和 npm for Node.js。
+ 在設定為僅允許透過 Amazon VPC 端點存取的 S3 儲存貯體中存取物件。
+ 透過與子網路相關聯的 NAT 閘道或 NAT 執行個體的彈性 IP 地址，查詢需要固定 IP 地址的外部 Web 服務。

您的組建可以存取您的 VPC 中託管的任何資源。

## VPC 最佳實務
<a name="best-practices-for-vpcs"></a>

當您設定 VPC 以使用 CodeBuild 時，請使用此檢查清單。
+ 使用公有和私有子網路以及 NAT 閘道來設定 VPC。NAT 閘道必須位於公有子網路中。如需詳細資訊，請參閱《*Amazon VPC 使用者指南*》中的[含公有和私有子網路 (NAT) 的 VPC](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Scenario2.html)。
**重要**  
您需要 NAT 閘道或 NAT 執行個體，才能搭配 VPC 使用 CodeBuild，以便 CodeBuild 可以連線到公有端點 （例如，在執行組建時執行 CLI 命令）。您無法使用網際網路閘道，而不是 NAT 閘道或 NAT 執行個體，因為 CodeBuild 不支援將彈性 IP 地址指派給其建立的網路介面，Amazon EC2 不支援針對在 Amazon EC2 執行個體啟動之外建立的任何網路介面自動指派公有 IP 地址。
+ 將多個可用區域加入您的 VPC。
+ 請確定您的安全群組不允許流量傳入 (進入) 您的組建。CodeBuild 對傳出流量沒有特定要求，但您必須允許存取建置所需的任何網際網路資源，例如 GitHub 或 Amazon S3。

  如需詳細資訊，請參閱《*Amazon VPC 使用者指南*》中的[安全群組規則](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html#SecurityGroupRules)。
+ 為您的組建設定個別子網路。
+ 當您設定 CodeBuild 專案以存取 VPC 時，請僅選擇私有子網路。

如需在 Amazon VPC 中設定 VPC 的詳細資訊，請參閱 [Amazon VPC 使用者指南](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Introduction.html)。

如需使用 CloudFormation 設定 VPC 以使用 CodeBuild VPC 功能的詳細資訊，請參閱 [CloudFormation VPC 範本](cloudformation-vpc-template.md)。

## VPCs的限制
<a name="vpc-limitations"></a>
+ 共用 VPC 不支援 CodeBuild VPCs 連線。

# 允許 CodeBuild 專案中的 Amazon VPC 存取
<a name="enabling-vpc-access-in-projects"></a>

在您的 VPC 組態中包含這些設定：
+ 針對 **VPC ID**，選擇 CodeBuild 使用的 VPC ID。
+ 針對**子網路**，選擇具有 NAT 轉譯的私有子網路，其中包含或具有 CodeBuild 所用資源的路由。
+ 針對**安全群組**，選擇 CodeBuild 用來允許存取 VPCs 中資源的安全群組。



若要使用主控台來建立建置專案，請參閱[建立組建專案 (主控台)](create-project.md#create-project-console)。當您建立或變更 CodeBuild 專案時，請在 **VPC** 中選擇您的 VPC ID、子網路和安全群組。



若要使用 AWS CLI 建立建置專案，請參閱 [建立建置專案 (AWS CLI)](create-project.md#create-project-cli)。如果您使用 AWS CLI 搭配 CodeBuild，則 CodeBuild 用來代表 IAM 使用者與 服務互動的服務角色必須連接政策。如需相關資訊，請參閱[允許 CodeBuild 存取建立 VPC 網路介面所需的 AWS 服務](auth-and-access-control-iam-identity-based-access-control.md#customer-managed-policies-example-create-vpc-network-interface)。

*vpcConfig* 物件應該包含您的 *vpcId*、*securityGroupIds* 和 *subnets*。
+ *vpcId*：必要的。CodeBuild 使用的 VPC ID。執行此命令以取得您區域中所有 Amazon VPC IDs的清單：

  ```
  aws ec2 describe-vpcs
  ```
+ *subnets*：必要。包含 CodeBuild 所用資源IDs。執行此命令以取得這些 ID：

  ```
  aws ec2 describe-subnets --filters "Name=vpc-id,Values=<vpc-id>" --region us-east-1
  ```
**注意**  
將 `us-east-1` 取代為您的區域。
+ *securityGroupIds*：必要。CodeBuild 用來允許存取 VPCs 中資源的安全群組 IDs。執行此命令以去得這些 ID：

  ```
  aws ec2 describe-security-groups --filters "Name=vpc-id,Values=<vpc-id>" --region us-east-1
  ```
**注意**  
將 `us-east-1` 取代為您的區域。

# 對 VPC 設定進行故障診斷
<a name="troubleshooting-vpc"></a>

請使用錯誤訊息中出現的資訊來協助您查明、診斷和解決問題。

以下是一些準則，可協助您疑難排解常見的 CodeBuild VPC 錯誤：`Build does not have internet connectivity. Please check subnet network configuration`。

1. [確定您的網際網路閘道連接至 VPC](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html#Add_IGW_Attach_Gateway)。

1. [確定公有子網路的路由表指向網際網路閘道](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html#route-tables-internet-gateway)。

1. [確定您的網路 ACL 允許流量流動](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html#SecurityGroupRules)。

1. [確定您的安全群組允許流量流動](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html#SecurityGroupRules)。

1. [為您的 NAT 閘道進行故障診斷](https://docs.aws.amazon.com/vpc/latest/userguide/VPC-nat-gateway.html#nat-gateway-troubleshooting)。

1. [確定私有子網路的路由表指向 NAT 閘道](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html#route-tables-nat)。

1. 請確定 CodeBuild 用來代表 IAM 使用者與 服務互動的服務角色具有[此政策](https://docs.aws.amazon.com/codebuild/latest/userguide/auth-and-access-control-iam-identity-based-access-control.html#customer-managed-policies-example-create-vpc-network-interface)中的許可。如需詳細資訊，請參閱[允許 CodeBuild 與其他 AWS 服務互動](setting-up-service-role.md)。

   如果 CodeBuild 缺少許可，您可能會收到錯誤，指出 `Unexpected EC2 error: UnauthorizedOperation`。如果 CodeBuild 沒有使用 VPC 所需的 Amazon EC2 許可，則可能會發生此錯誤。

# 使用 VPC 端點
<a name="use-vpc-endpoints-with-codebuild"></a>

您可以將 設定為 AWS CodeBuild 使用介面 VPC 端點，以改善建置的安全性。介面端點採用 PrivateLink，這項技術可讓您使用私有 IP 地址來私下存取 Amazon EC2 和 CodeBuild。PrivateLink 會將受管執行個體、CodeBuild 和 Amazon EC2 之間的所有網路流量限制在 Amazon 網路。(受管執行個體無法存取網際網路。) 此外，您不需要網際網路閘道、NAT 裝置或虛擬私有閘道。您不需要 (但建議) 設定 PrivateLink。如需 PrivateLink 和 VPC 端點的詳細資訊，請參閱[什麼是 AWS PrivateLink？](https://docs.aws.amazon.com/vpc/latest/privatelink/what-is-privatelink.html)。

## 建立 VPC 端點之前
<a name="vpc-endpoints-before-you-begin"></a>

 設定 VPC 端點之前 AWS CodeBuild，請注意下列限制。

**注意**  
 如果您想要搭配不支援 Amazon VPC PrivateLink 連線 AWS 的服務使用 CodeBuild，請使用 [NAT 閘道](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_NAT_Instance.html)。
+  VPC 端點僅支援 Amazon 透過 Amazon Route 53 提供的 DNS。如果您想要使用自己的 DNS，您可以使用條件式 DNS 轉送。如需詳細資訊，請參閱《Amazon VPC 使用者指南》**中的 [DHCP 選項集](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_DHCP_Options.html)。
+  VPC 端點目前不支援跨區域請求。請確定您在與存放建置輸入和輸出的任何 S3 儲存貯體相同的 AWS 區域中建立端點。您可以使用 Amazon S3 主控台或 [get-bucket-location](https://docs.aws.amazon.com/cli/latest/reference/s3api/get-bucket-location.html) 命令來尋找儲存貯體的位置。使用區域特定的 Amazon S3 端點來存取您的儲存貯體 （例如 `<bucket-name>.s3-us-west-2.amazonaws.com`)。如需 Amazon S3 區域特定端點的詳細資訊，請參閱《》中的 [Amazon Simple Storage Service](https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region)*Amazon Web Services 一般參考*。如果您使用 AWS CLI 向 Amazon S3 提出請求，請將預設區域設定為建立儲存貯體的相同區域，或在請求中使用 `--region` 參數。

## 為 CodeBuild 建立 VPC 端點
<a name="creating-vpc-endpoints"></a>

按照[建立界面端點](https://docs.aws.amazon.com/vpc/latest/userguide/vpce-interface.html#create-interface-endpoint)中的指示建立 `com.amazonaws.region.codebuild` 端點。這是 的 VPC 端點 AWS CodeBuild。

![\[VPC 端點組態。\]](http://docs.aws.amazon.com/zh_tw/codebuild/latest/userguide/images/vpc-endpoint.png)


 *region* 代表 CodeBuild 支援的 AWS 區域的區域識別符，例如`us-east-2`美國東部 （俄亥俄） 區域。如需支援 AWS 區域的清單，請參閱《 * AWS 一般參考*》中的 [CodeBuild](https://docs.aws.amazon.com/general/latest/gr/rande.html#codebuild_region)。端點會預先填入您在登入時指定的區域 AWS。如果變更您的區域，VPC 端點會隨之更新。

## 為 CodeBuild 建立 VPC 端點政策
<a name="creating-vpc-endpoint-policy"></a>

 您可以為 Amazon VPC 端點建立政策，您可以在 AWS CodeBuild 其中指定：
+ 可執行動作的主體。
+ 可執行的動作。
+ 可對其執行動作的資源。

以下範例政策會指定所有委託人只能開始和檢視 `project-name` 專案的建置。

```
{
    "Statement": [
        {
            "Action": [
                "codebuild:ListBuildsForProject",
                "codebuild:StartBuild",
                "codebuild:BatchGetBuilds"
            ],
            "Effect": "Allow",
            "Resource": "arn:aws:codebuild:region-ID:account-ID:project/project-name",
            "Principal": "*"
        }
    ]
}
```

 如需詳細資訊，請參閱《Amazon VPC 使用者指南》**中的[使用 VPC 端點控制對服務的存取](https://docs.aws.amazon.com/vpc/latest/userguide/vpc-endpoints-access.html)。

# AWS CodeBuild 搭配受管代理伺服器使用
<a name="run-codebuild-in-managed-proxy-server"></a>

 若要在受管代理伺服器中執行 AWS CodeBuild 預留容量機群，您必須設定代理伺服器，以允許或拒絕使用代理規則往返外部網站的流量。請注意，VPC、Windows 或 MacOS 不支援在受管代理伺服器中執行預留容量機群。

**重要**  
根據機群中存在代理組態的持續時間，會產生額外的成本。如需詳細資訊，請參閱 https：//[https://aws.amazon.com/codebuild/pricing/](https://aws.amazon.com/codebuild/pricing/)。

**Topics**
+ [設定預留容量機群的受管代理組態](#run-codebuild-in-managed-proxy-server-configure)
+ [執行 CodeBuild 預留容量機群](#use-managed-server-run-acb-fleet)

## 設定預留容量機群的受管代理組態
<a name="run-codebuild-in-managed-proxy-server-configure"></a>

 若要為預留容量機群設定受管代理伺服器，您必須在主控台或使用 建立機群時啟用此功能 AWS CLI。您需要定義幾個屬性：

**定義代理組態 - 選用**  
將網路存取控制套用至預留容量執行個體的代理組態。

**預設行為**  
定義傳出流量的行為。    
**Allow**  
根據預設，允許傳出流量到所有目的地。  
**拒絕**  
根據預設，拒絕所有目的地的傳出流量。

**Proxy 規則**  
指定要限制網路存取控制的目的地網域。

若要在主控台中定義代理組態，請參閱 [建立預留容量機群](fleets.md#fleets.how-to) 以取得指示。若要使用 定義代理組態 AWS CLI，您可以修改下列 JSON 語法並儲存結果來執行此操作：

```
"proxyConfiguration": {
    "defaultBehavior": "ALLOW_ALL" | "DENY_ALL",
    "orderedProxyRules": [
        {
            "type": "DOMAIN" | "IP",
            "effect": "ALLOW" | "DENY",
            "entities": [
                "destination"
            ]
        }
    ]
}
```

您的 JSON 檔案看起來可能會類似以下內容：

```
"proxyConfiguration": {
    "defaultBehavior": "DENY_ALL",
    "orderedProxyRules": [
        {
            "type": "DOMAIN",
            "effect": "ALLOW",
            "entities": [
                "github.com"
            ]
        }
    ]
}
```

## 執行 CodeBuild 預留容量機群
<a name="use-managed-server-run-acb-fleet"></a>

 使用受管代理伺服器執行 AWS CodeBuild 預留容量機群時，CodeBuild 會自動使用受管代理地址設定其 `HTTP_PROXY`和 `HTTPS_PROXY`環境變數。如果您的相依性軟體有自己的組態，且不遵守環境變數，您可以參考這些值，並在建置命令中更新您的軟體組態，以透過受管代理正確路由建置流量。如需詳細資訊，請參閱[在 中建立建置專案 AWS CodeBuild](create-project.md)及[在 中變更建置專案設定 AWS CodeBuild](change-project.md)。

# AWS CodeBuild 搭配代理伺服器使用
<a name="use-proxy-server"></a>

 您可以使用 AWS CodeBuild 搭配代理伺服器來調節進出網際網路的 HTTP 和 HTTPS 流量。若要使用代理伺服器執行 CodeBuild，請在公有子網路中安裝代理伺服器，並在 VPC 中的私有子網路中安裝 CodeBuild。

在代理伺服器中執行 CodeBuild 有兩種主要使用案例：
+  不需要在您的 VPC 中使用 NAT 閘道或 NAT 執行個體。
+  可讓您指定代理伺服器中的執行個體可以存取的 URL，以及代理伺服器拒絕存取的 URL。

 您可以搭配兩種類型的代理伺服器使用 CodeBuild。對於兩者，代理伺服器在公有子網路中執行，而 CodeBuild 在私有子網路中執行。
+  **明確代理**：如果您使用明確代理伺服器，您必須在專案層級的 CodeBuild 中設定 `HTTP_PROXY`、 `NO_PROXY`和 `HTTPS_PROXY`環境變數。如需詳細資訊，請參閱[在 中變更建置專案設定 AWS CodeBuild](change-project.md)及[在 中建立建置專案 AWS CodeBuild](create-project.md)。
+  **透明代理**：如果您使用透明代理伺服器，不需要特殊組態。

**Topics**
+ [設定在代理伺服器中執行 CodeBuild 所需的元件](use-proxy-server-transparent-components.md)
+ [在明確代理伺服器中執行 CodeBuild](run-codebuild-in-explicit-proxy-server.md)
+ [在透明代理伺服器中執行 CodeBuild](run-codebuild-in-transparent-proxy-server.md)
+ [在代理伺服器中執行套用管理員和其他工具](use-proxy-server-tools.md)

# 設定在代理伺服器中執行 CodeBuild 所需的元件
<a name="use-proxy-server-transparent-components"></a>

 您需要這些元件才能在透明或明確的代理伺服器 AWS CodeBuild 中執行：
+  VPC。
+  您的 VPC 中一個用於代理伺服器的公有子網路。
+  VPC for CodeBuild 中的一個私有子網路。
+  允許 VPC 和網際網路之間通訊的網際網路閘道。

 下圖顯示元件如何互動。

![\[圖表顯示元件如何互動。\]](http://docs.aws.amazon.com/zh_tw/codebuild/latest/userguide/images/codebuild-proxy-transparent.png)


## 設定 VPC、子網路和網路閘道
<a name="use-proxy-server-transparent-setup"></a>

 在透明或明確代理伺服器 AWS CodeBuild 中執行 需要下列步驟。

1. 建立 VPC。如需詳細資訊，請參閱《Amazon [VPC 使用者指南》中的建立](https://docs.aws.amazon.com/vpc/latest/userguide/working-with-vpcs.html#Create-VPC) VPC。 **

1. 在 VPC 中建立兩個子網路。一個是名為 `Public Subnet` 的公有子網路，您的代理伺服器在其中執行。另一個是名為 的私有子網路，`Private Subnet`在其中 CodeBuild 執行。

   如需相關資訊，請參閱[在您的 VPC 中建立子網路](https://docs.aws.amazon.com/vpc/latest/userguide/working-with-vpcs.html#AddaSubnet)。

1.  建立網際網路閘道並連接到您的 VPC。如需詳細資訊，請參閱[建立和連接網際網路閘道](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html#Add_IGW_Attach_Gateway)。

1.  在預設路由表中新增規則，將從 VPC (0.0.0.0/0) 傳出的流量路由傳送到網際網路閘道。如需相關資訊，請參閱[從路由表新增和移除路由](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html#AddRemoveRoutes)。

1.  在 VPC 的預設安全群組中新增規則，以允許來自 VPC (0.0.0.0/0) 的輸入 SSH 流量 (TCP 22)。

1.  遵循《*Amazon EC2 使用者指南*》中的[使用啟動執行個體精靈](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/launching-instance.html)啟動執行個體中的指示來啟動 Amazon Linux 執行個體。當您執行精靈時，請選擇以下選項：
   +  在**選擇執行個體類型**中，選擇 Amazon Linux Amazon Machine Image (AMI)。
   +  在 **Subnet (子網路)** 中，選擇您先前在此主題中建立的公有子網路。如果您使用建議的名稱，則為 **公有子網路 (Public Subnet)**。
   +  在 **Auto-assign Public IP (自動指派公有 IP)** 中，選擇 **Enable (啟用)**。
   +  在 **Configure Security Group (設定安全群組)** 頁面，針對 **Assign a security group (指派安全群組)**，選擇 **Select an existing security group (選取現有的安全群組)**。接下來，選擇預設安全群組。
   +  當您選擇 **Launch (啟動)** 之後，選擇現有的金鑰對或建立金鑰對。

    對於其他所有選項，選擇預設設定。

1.  在您的 EC2 執行個體執行之後，停用來源/目的地檢查。如需詳細資訊，請參閱《*Amazon VPC 使用者指南*》中的[停用來源/目的地檢查](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_NAT_Instance.html#EIP_Disable_SrcDestCheck)。

1.  在您 VPC 中建立路由表。在路由表中新增規則，將流向網際網路的流量路由傳送到您的代理伺服器。將此路由表與您的私有子網路建立關聯。這是必要的，因此來自您私有子網路中執行 CodeBuild 之執行個體的傳出請求一律會透過代理伺服器路由。

## 安裝和設定代理伺服器
<a name="use-proxy-server-squid-install"></a>

 有許多代理伺服器可供選擇。這裡使用開放原始碼代理伺服器 Squid 來示範 如何在代理伺服器中 AWS CodeBuild 執行。您可以將相同的概念套用到其他代理伺服器。

 若要安裝 Squid，請執行下列命令來使用 yum 儲存庫：

```
sudo yum update -y
sudo yum install -y squid
```

 安裝 Squid 之後，請按照本主題稍後的指示編輯其 `squid.conf` 檔案。

## 針對 HTTPS 流量來設定 Squid
<a name="use-proxy-server-squid-configure-https"></a>

 對於 HTTPS，HTTP 流量會封裝在 Transport Layer Security (TLS) 連線中。Squid 使用稱為 [SslPeekAndSplice](https://wiki.squid-cache.org/Features/SslPeekAndSplice) 的功能，從包含所要求網際網路主機的 TLS 初始中，擷取伺服器名稱指示 (SNI)。需要如此，Squid 就不需要解密 HTTPS 流量。若要啟用 SslPeekAndSplice，Squid 需要憑證。使用 OpenSSL 建立此憑證：

```
sudo mkdir /etc/squid/ssl
cd /etc/squid/ssl
sudo openssl genrsa -out squid.key 2048
sudo openssl req -new -key squid.key -out squid.csr -subj "/C=XX/ST=XX/L=squid/O=squid/CN=squid"
sudo openssl x509 -req -days 3650 -in squid.csr -signkey squid.key -out squid.crt
sudo cat squid.key squid.crt | sudo tee squid.pem
```

**注意**  
 對於 HTTP，Squid 不需要設定。它可以從所有 HTTP/1.1 請求訊息中擷取主機標頭欄位，此欄位指定所要求的網際網路主機。

# 在明確代理伺服器中執行 CodeBuild
<a name="run-codebuild-in-explicit-proxy-server"></a>

 若要 AWS CodeBuild 在明確代理伺服器中執行 ，您必須設定代理伺服器以允許或拒絕進出外部網站的流量，然後設定 `HTTP_PROXY`和 `HTTPS_PROXY`環境變數。

**Topics**
+ [將 Squid 設定為明確代理伺服器](#use-proxy-server-explicit-squid-configure)
+ [建立 CodeBuild 專案](#use-proxy-server-explicit-create-acb-project)
+ [明確代理伺服器 `squid.conf` 檔案範例](#use-proxy-server-explicit-sample-squid-conf)

## 將 Squid 設定為明確代理伺服器
<a name="use-proxy-server-explicit-squid-configure"></a>

 若要將 Squid 代理伺服器設定為明確，您必須將其 `/etc/squid/squid.conf` 檔案修改如下：
+  移除以下預設的存取控制清單 (ACL) 規則。

  ```
  acl localnet src 10.0.0.0/8     
  acl localnet src 172.16.0.0/12  
  acl localnet src 192.168.0.0/16 
  acl localnet src fc00::/7       
  acl localnet src fe80::/10
  ```

   新增以下規則來取代您移除的預設 ACL 規則。第一行允許來自 VPC 的請求。接下來兩行授予許可給您的代理伺服器存取 AWS CodeBuild可能使用的目的地 URL。編輯最後一行中的規則表達式，以在 AWS 區域中指定 S3 儲存貯體或 CodeCommit 儲存庫。例如：
  + 如果您的來源是 Amazon S3，請使用 命令**acl download\$1src dstdom\$1regex .\$1s3\$1.us-west-1\$1.amazonaws\$1.com**授予 `us-west-1`區域中 S3 儲存貯體的存取權。
  +  如果您的來源是 AWS CodeCommit，請使用 `git-codecommit.<your-region>.amazonaws.com`將 AWS 區域新增至允許清單。

  ```
  acl localnet src 10.1.0.0/16 #Only allow requests from within the VPC
  acl allowed_sites dstdomain .github.com #Allows to download source from GitHub
  acl allowed_sites dstdomain .bitbucket.com #Allows to download source from Bitbucket
  acl download_src dstdom_regex .*\.amazonaws\.com #Allows to download source from Amazon S3 or CodeCommit
  ```
+  將 `http_access allow localnet` 換成下列項目：

  ```
  http_access allow localnet allowed_sites
  http_access allow localnet download_src
  ```
+ 如果您想要建置上傳日誌和成品，請執行以下其中一項：

  1. 在 `http_access deny all` 陳述式之前，插入以下陳述式。它們允許 CodeBuild 存取 CloudWatch 和 Amazon S3。需要存取 CloudWatch，以便 CodeBuild 可以建立 CloudWatch 日誌。需要存取 Amazon S3 才能上傳成品和 Amazon S3 快取。
     + 

       ```
       https_port 3130 cert=/etc/squid/ssl/squid.pem ssl-bump intercept
       acl SSL_port port 443
       http_access allow SSL_port
       acl allowed_https_sites ssl::server_name .amazonaws.com
       acl step1 at_step SslBump1
       acl step2 at_step SslBump2
       acl step3 at_step SslBump3
       ssl_bump peek step1 all
       ssl_bump peek step2 allowed_https_sites
       ssl_bump splice step3 allowed_https_sites
       ssl_bump terminate step2 all
       ```
     + 儲存 之後`squid.conf`，請執行下列命令：

       ```
       sudo iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-port 3130
       sudo service squid restart
       ```

  1.  將 `proxy` 新增至您的 buildspec 檔案。如需詳細資訊，請參閱[Buildspec 語法](build-spec-ref.md#build-spec-ref-syntax)。

     ```
     version: 0.2
     proxy:
       upload-artifacts: yes
       logs: yes
     phases:
       build:
         commands:
           - command
     ```

**注意**  
如果您收到 RequestError 逾時錯誤，請參閱[在代理伺服器中執行 CodeBuild 時發生 RequestError 逾時錯誤](troubleshooting.md#code-request-timeout-error)。

如需詳細資訊，請參閱本主題後面部分的 [明確代理伺服器 `squid.conf` 檔案範例](#use-proxy-server-explicit-sample-squid-conf)。

## 建立 CodeBuild 專案
<a name="use-proxy-server-explicit-create-acb-project"></a>

 若要 AWS CodeBuild 使用明確代理伺服器執行 ，請使用您為代理伺服器建立的 EC2 執行個體私有 IP 地址`HTTP_PROXY`和專案層級的連接埠 3128 來設定其 和 `HTTPS_PROXY`環境變數。私有 IP 地址看起來像是 `http://your-ec2-private-ip-address:3128`。如需詳細資訊，請參閱[在 中建立建置專案 AWS CodeBuild](create-project.md)及[在 中變更建置專案設定 AWS CodeBuild](change-project.md)。

 使用以下命令來檢視 Squid 代理存取日誌：

```
sudo tail -f /var/log/squid/access.log
```

## 明確代理伺服器 `squid.conf` 檔案範例
<a name="use-proxy-server-explicit-sample-squid-conf"></a>

 以下是為明確代理伺服器設定的 `squid.conf` 檔案的範例。

```
  acl localnet src 10.0.0.0/16 #Only allow requests from within the VPC
  # add all URLS to be whitelisted for download source and commands to be run in build environment
  acl allowed_sites dstdomain .github.com    #Allows to download source from github
  acl allowed_sites dstdomain .bitbucket.com #Allows to download source from bitbucket
  acl allowed_sites dstdomain ppa.launchpad.net #Allows to run apt-get in build environment
  acl download_src dstdom_regex .*\.amazonaws\.com #Allows to download source from S3 or CodeCommit
  acl SSL_ports port 443
  acl Safe_ports port 80		# http
  acl Safe_ports port 21		# ftp
  acl Safe_ports port 443		# https
  acl Safe_ports port 70		# gopher
  acl Safe_ports port 210		# wais
  acl Safe_ports port 1025-65535	# unregistered ports
  acl Safe_ports port 280		# http-mgmt
  acl Safe_ports port 488		# gss-http
  acl Safe_ports port 591		# filemaker
  acl Safe_ports port 777		# multiling http
  acl CONNECT method CONNECT
  #
  # Recommended minimum Access Permission configuration:
  #
  # Deny requests to certain unsafe ports
  http_access deny !Safe_ports
  # Deny CONNECT to other than secure SSL ports
  http_access deny CONNECT !SSL_ports
  # Only allow cachemgr access from localhost
  http_access allow localhost manager
  http_access deny manager
  # We strongly recommend the following be uncommented to protect innocent
  # web applications running on the proxy server who think the only
  # one who can access services on "localhost" is a local user
  #http_access deny to_localhost
  #
  # INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
  #
  # Example rule allowing access from your local networks.
  # Adapt localnet in the ACL section to list your (internal) IP networks
  # from where browsing should be allowed
  http_access allow localnet allowed_sites
  http_access allow localnet download_src
  http_access allow localhost
  # Add this for CodeBuild to access CWL end point, caching and upload artifacts S3 bucket end point
  https_port 3130 cert=/etc/squid/ssl/squid.pem ssl-bump intercept
  acl SSL_port port 443
  http_access allow SSL_port
  acl allowed_https_sites ssl::server_name .amazonaws.com
  acl step1 at_step SslBump1
  acl step2 at_step SslBump2
  acl step3 at_step SslBump3
  ssl_bump peek step1 all
  ssl_bump peek step2 allowed_https_sites
  ssl_bump splice step3 allowed_https_sites
  ssl_bump terminate step2 all
  # And finally deny all other access to this proxy
  http_access deny all
  # Squid normally listens to port 3128
  http_port 3128
  # Uncomment and adjust the following to add a disk cache directory.
  #cache_dir ufs /var/spool/squid 100 16 256
  # Leave coredumps in the first cache dir
  coredump_dir /var/spool/squid
  #
  # Add any of your own refresh_pattern entries above these.
  #
  refresh_pattern ^ftp:		1440	20%	10080
  refresh_pattern ^gopher:	1440	0%	1440
  refresh_pattern -i (/cgi-bin/|\?) 0	0%	0
  refresh_pattern .		0	20%	4320
```

# 在透明代理伺服器中執行 CodeBuild
<a name="run-codebuild-in-transparent-proxy-server"></a>

 若要 AWS CodeBuild 在透明代理伺服器中執行 ，您必須將代理伺服器設定為可存取其互動的網站和網域。

**Topics**
+ [將 Squid 設定為透明代理伺服器](#use-proxy-server-transparent-squid-configure)
+ [建立 CodeBuild 專案](#use-proxy-server-transparent-create-acb-project)

## 將 Squid 設定為透明代理伺服器
<a name="use-proxy-server-transparent-squid-configure"></a>

 若要將代理伺服器設定為透明，您必須授與它您希望其存取之網域和網站的存取權。若要 AWS CodeBuild 使用透明代理伺服器執行 ，您必須將其存取權授予 `amazonaws.com`。您也必須將存取權授予 CodeBuild 使用的其他網站。視您建立 CodeBuild 專案的方式而定，這些項目會有所不同。例如，GitHub、Bitbucket、Yum 和 Maven 等儲存庫的網站。若要授與 Squid 存取特定網域和網站，請使用類似以下的命令來更新 `squid.conf` 檔案。此命令範例會授予對 `amazonaws.com`、`github.com` 和 `bitbucket.com` 的存取權。您可以編輯此範例來授與存取其他網站。

```
cat | sudo tee /etc/squid/squid.conf ≪EOF
visible_hostname squid
#Handling HTTP requests
http_port 3129 intercept
acl allowed_http_sites dstdomain .amazonaws.com
#acl allowed_http_sites dstdomain domain_name [uncomment this line to add another domain]
http_access allow allowed_http_sites
#Handling HTTPS requests
https_port 3130 cert=/etc/squid/ssl/squid.pem ssl-bump intercept
acl SSL_port port 443
http_access allow SSL_port
acl allowed_https_sites ssl::server_name .amazonaws.com
acl allowed_https_sites ssl::server_name .github.com
acl allowed_https_sites ssl::server_name .bitbucket.com
#acl allowed_https_sites ssl::server_name [uncomment this line to add another website]
acl step1 at_step SslBump1
acl step2 at_step SslBump2
acl step3 at_step SslBump3
ssl_bump peek step1 all
ssl_bump peek step2 allowed_https_sites
ssl_bump splice step3 allowed_https_sites
ssl_bump terminate step2 all
http_access deny all
EOF
```

 從私有子網路中的執行個體傳入的請求必須重新導向到 Squid 連接埠。Squid 會在連接埠 3129 (而不是 80) 接聽 HTTP 流量，在 3130 (而不是 443) 接聽 HTTPS 流量。使用 **iptables** 命令來路由流量：

```
sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-port 3129
sudo iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-port 3130
sudo service iptables save
sudo service squid start
```

## 建立 CodeBuild 專案
<a name="use-proxy-server-transparent-create-acb-project"></a>

 設定代理伺服器之後，您可以在私有子網路 AWS CodeBuild 中搭配 使用代理伺服器，無需更多組態。每個 HTTP 和 HTTPS 請求會通過公有代理伺服器。使用以下命令來檢視 Squid 代理存取日誌：

```
sudo tail -f /var/log/squid/access.log
```

# 在代理伺服器中執行套用管理員和其他工具
<a name="use-proxy-server-tools"></a>

使用下列程序在代理伺服器中執行套件管理員和其他工具。

**在代理伺服器中執行工具，例如套件管理員**

1.  在 `squid.conf` 檔案中新增陳述式，以將工具新增至代理伺服器的允許清單。

1.  在 buildspec 檔案中新增一行，指向您代理伺服器的私有端點。

 下列範例示範如何對 `apt-get`、`curl` 和 `maven` 這樣做。如果您使用不同的工具，也適用同樣的原則。將其新增至 `squid.conf` 檔案中的允許清單，並將命令新增至您的 buildspec 檔案，讓 CodeBuild 了解代理伺服器的端點。

**如何在代理伺服器中執行 `apt-get`**

1. 在 `squid.conf` 檔案中新增以下陳述式，將 `apt-get` 新增至代理伺服器的允許清單。前三行允許 在建置環境中`apt-get`執行 。

   ```
   acl allowed_sites dstdomain ppa.launchpad.net # Required for apt-get to run in the build environment
   acl apt_get dstdom_regex .*\.launchpad.net # Required for CodeBuild to run apt-get in the build environment
   acl apt_get dstdom_regex .*\.ubuntu.com    # Required for CodeBuild to run apt-get in the build environment
   http_access allow localnet allowed_sites
   http_access allow localnet apt_get
   ```

1. 在 buildspec 檔案中新增以下陳述式，讓 `apt-get` 命令在 `/etc/apt/apt.conf.d/00proxy` 中尋找代理組態。

   ```
   echo 'Acquire::http::Proxy "http://<private-ip-of-proxy-server>:3128"; Acquire::https::Proxy "http://<private-ip-of-proxy-server>:3128"; Acquire::ftp::Proxy "http://<private-ip-of-proxy-server>:3128";' > /etc/apt/apt.conf.d/00proxy
   ```

**如何在代理伺服器中執行 `curl`**

1.  在 `squid.conf` 檔案中新增以下陳述式，將 `curl` 新增至建置環境中的允許清單。

   ```
   acl allowed_sites dstdomain ppa.launchpad.net # Required to run apt-get in the build environment
   acl allowed_sites dstdomain google.com # Required for access to a webiste. This example uses www.google.com.
   http_access allow localnet allowed_sites
   http_access allow localnet apt_get
   ```

1.  在 buildspec 檔案中新增以下陳述式，讓 `curl` 使用私有代理伺服器來存取您新增到 `squid.conf` 的網站。在此範例中，網站為 `google.com`。

   ```
   curl -x <private-ip-of-proxy-server>:3128 https://www.google.com
   ```

**如何在代理伺服器中執行 `maven`**

1.  在 `squid.conf` 檔案中新增以下陳述式，將 `maven` 新增至建置環境中的允許清單。

   ```
   acl allowed_sites dstdomain ppa.launchpad.net # Required to run apt-get in the build environment
   acl maven dstdom_regex .*\.maven.org # Allows access to the maven repository in the build environment
   http_access allow localnet allowed_sites
   http_access allow localnet maven
   ```

1. 在您的 buildspec 檔案中新增以下陳述式。

   ```
   maven clean install -DproxySet=true -DproxyHost=<private-ip-of-proxy-server> -DproxyPort=3128
   ```

# CloudFormation VPC 範本
<a name="cloudformation-vpc-template"></a>

CloudFormation 可讓您以可預測且重複的方式建立和佈建 AWS 基礎設施部署，方法為使用範本檔案建立和刪除資源集合，做為單一單位 (*堆疊*)。如需詳細資訊，請參閱《CloudFormation 使用者指南》[https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html)。

以下是 CloudFormation YAML 範本，用於設定要使用的 VPC AWS CodeBuild。此檔案也可用於 [sample.zip。](./samples/samples.zip)

```
Description:  This template deploys a VPC, with a pair of public and private subnets spread
  across two Availability Zones. It deploys an internet gateway, with a default
  route on the public subnets. It deploys a pair of NAT gateways (one in each AZ),
  and default routes for them in the private subnets.

Parameters:
  EnvironmentName:
    Description: An environment name that is prefixed to resource names
    Type: String

  VpcCIDR:
    Description: Please enter the IP range (CIDR notation) for this VPC
    Type: String
    Default: 10.192.0.0/16

  PublicSubnet1CIDR:
    Description: Please enter the IP range (CIDR notation) for the public subnet in the first Availability Zone
    Type: String
    Default: 10.192.10.0/24

  PublicSubnet2CIDR:
    Description: Please enter the IP range (CIDR notation) for the public subnet in the second Availability Zone
    Type: String
    Default: 10.192.11.0/24

  PrivateSubnet1CIDR:
    Description: Please enter the IP range (CIDR notation) for the private subnet in the first Availability Zone
    Type: String
    Default: 10.192.20.0/24

  PrivateSubnet2CIDR:
    Description: Please enter the IP range (CIDR notation) for the private subnet in the second Availability Zone
    Type: String
    Default: 10.192.21.0/24

Resources:
  VPC:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: !Ref VpcCIDR
      EnableDnsSupport: true
      EnableDnsHostnames: true
      Tags:
        - Key: Name
          Value: !Ref EnvironmentName

  InternetGateway:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags:
        - Key: Name
          Value: !Ref EnvironmentName

  InternetGatewayAttachment:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      InternetGatewayId: !Ref InternetGateway
      VpcId: !Ref VPC

  PublicSubnet1:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      AvailabilityZone: !Select [ 0, !GetAZs '' ]
      CidrBlock: !Ref PublicSubnet1CIDR
      MapPublicIpOnLaunch: true
      Tags:
        - Key: Name
          Value: !Sub ${EnvironmentName} Public Subnet (AZ1)

  PublicSubnet2:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      AvailabilityZone: !Select [ 1, !GetAZs  '' ]
      CidrBlock: !Ref PublicSubnet2CIDR
      MapPublicIpOnLaunch: true
      Tags:
        - Key: Name
          Value: !Sub ${EnvironmentName} Public Subnet (AZ2)

  PrivateSubnet1:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      AvailabilityZone: !Select [ 0, !GetAZs  '' ]
      CidrBlock: !Ref PrivateSubnet1CIDR
      MapPublicIpOnLaunch: false
      Tags:
        - Key: Name
          Value: !Sub ${EnvironmentName} Private Subnet (AZ1)

  PrivateSubnet2:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref VPC
      AvailabilityZone: !Select [ 1, !GetAZs  '' ]
      CidrBlock: !Ref PrivateSubnet2CIDR
      MapPublicIpOnLaunch: false
      Tags:
        - Key: Name
          Value: !Sub ${EnvironmentName} Private Subnet (AZ2)

  NatGateway1EIP:
    Type: AWS::EC2::EIP
    DependsOn: InternetGatewayAttachment
    Properties:
      Domain: vpc

  NatGateway2EIP:
    Type: AWS::EC2::EIP
    DependsOn: InternetGatewayAttachment
    Properties:
      Domain: vpc

  NatGateway1:
    Type: AWS::EC2::NatGateway
    Properties:
      AllocationId: !GetAtt NatGateway1EIP.AllocationId
      SubnetId: !Ref PublicSubnet1

  NatGateway2:
    Type: AWS::EC2::NatGateway
    Properties:
      AllocationId: !GetAtt NatGateway2EIP.AllocationId
      SubnetId: !Ref PublicSubnet2

  PublicRouteTable:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref VPC
      Tags:
        - Key: Name
          Value: !Sub ${EnvironmentName} Public Routes

  DefaultPublicRoute:
    Type: AWS::EC2::Route
    DependsOn: InternetGatewayAttachment
    Properties:
      RouteTableId: !Ref PublicRouteTable
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref InternetGateway

  PublicSubnet1RouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref PublicRouteTable
      SubnetId: !Ref PublicSubnet1

  PublicSubnet2RouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref PublicRouteTable
      SubnetId: !Ref PublicSubnet2


  PrivateRouteTable1:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref VPC
      Tags:
        - Key: Name
          Value: !Sub ${EnvironmentName} Private Routes (AZ1)

  DefaultPrivateRoute1:
    Type: AWS::EC2::Route
    Properties:
      RouteTableId: !Ref PrivateRouteTable1
      DestinationCidrBlock: 0.0.0.0/0
      NatGatewayId: !Ref NatGateway1

  PrivateSubnet1RouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref PrivateRouteTable1
      SubnetId: !Ref PrivateSubnet1

  PrivateRouteTable2:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref VPC
      Tags:
        - Key: Name
          Value: !Sub ${EnvironmentName} Private Routes (AZ2)

  DefaultPrivateRoute2:
    Type: AWS::EC2::Route
    Properties:
      RouteTableId: !Ref PrivateRouteTable2
      DestinationCidrBlock: 0.0.0.0/0
      NatGatewayId: !Ref NatGateway2

  PrivateSubnet2RouteTableAssociation:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId: !Ref PrivateRouteTable2
      SubnetId: !Ref PrivateSubnet2

  NoIngressSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupName: "no-ingress-sg"
      GroupDescription: "Security group with no ingress rule"
      VpcId: !Ref VPC

Outputs:
  VPC:
    Description: A reference to the created VPC
    Value: !Ref VPC

  PublicSubnets:
    Description: A list of the public subnets
    Value: !Join [ ",", [ !Ref PublicSubnet1, !Ref PublicSubnet2 ]]

  PrivateSubnets:
    Description: A list of the private subnets
    Value: !Join [ ",", [ !Ref PrivateSubnet1, !Ref PrivateSubnet2 ]]

  PublicSubnet1:
    Description: A reference to the public subnet in the 1st Availability Zone
    Value: !Ref PublicSubnet1

  PublicSubnet2:
    Description: A reference to the public subnet in the 2nd Availability Zone
    Value: !Ref PublicSubnet2

  PrivateSubnet1:
    Description: A reference to the private subnet in the 1st Availability Zone
    Value: !Ref PrivateSubnet1

  PrivateSubnet2:
    Description: A reference to the private subnet in the 2nd Availability Zone
    Value: !Ref PrivateSubnet2

  NoIngressSecurityGroup:
    Description: Security group with no ingress rule
    Value: !Ref NoIngressSecurityGroup
```