

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# AWS CodeBuild 与亚马逊 Virtual Private Cloud 一起使用
<a name="vpc-support"></a>

通常， AWS CodeBuild 无法访问 VPC 中的资源。要启用访问权限，您必须在项目配置中提供其他 VPC 特定的配置信息。 CodeBuild 这包括 VPC ID、VPC 子网 IDs和 VPC 安全组 IDs。支持 VPC 的构建随后就可以访问 VPC 中的资源。有关在 Amazon VPC 中设置 VPC 的更多信息，请参阅《[Amazon VPC 用户指南](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Introduction.html)》。

**Topics**
+ [使用案例](#use-cases)
+ [的最佳实践 VPCs](#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 或使用内部 Elastic Load Balancing 的服务上的内部 Web 服务交互。
+ 从自托管的内部构件存储库（如适用于 Python 的 PyPI、适用于 Java 的 Maven 和适用于 Node.js 的 npm）检索依赖项。
+ 访问配置为仅允许通过 Amazon VPC 端点访问的 S3 存储桶中的对象。
+ 利用与您的子网关联的 NAT 网关或 NAT 实例的弹性 IP 地址，来查询需要固定 IP 地址的外部 Web 服务。

您的构建可以访问您的 VPC 中托管的任何资源。

## 的最佳实践 VPCs
<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 实例才能 CodeBuild 与您的 VPC 配合使用，这样它 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)》。

有关使用配置 VPC CloudFormation 以使用 VP CodeBuild C 功能的更多信息，请参阅[CloudFormation VPC 模板](cloudformation-vpc-template.md)。

## 的局限性 VPCs
<a name="vpc-limitations"></a>
+ 共享不支持来自 CodeBuild 的 VPC 连接 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)](create-project.md#create-project-cli)。 AWS CLI 如果您使用的是 w AWS CLI it CodeBuild h，则用于代表 IAM 用户与服务交互的服务角色必须附加策略。 CodeBuild 有关信息，请参阅[允许 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*：必需。包含 IDs 所用资源的子网 CodeBuild。运行此命令获取以下内容 IDs：

  ```
  aws ec2 describe-subnets --filters "Name=vpc-id,Values=<vpc-id>" --region us-east-1
  ```
**注意**  
将 `us-east-1` 替换为您的区域。
+ *securityGroupIds*：必需。 IDs用于允许 CodeBuild 访问中的资源的安全组 VPCs。运行此命令以获取以下内容 IDs：

  ```
  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. [确保您的网络 ACLs 允许流量流动](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. 确保用于代表 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 有关更多信息，请参阅 [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>

您可以通过配置为使用接口 VPC 终端节点 AWS CodeBuild 来提高构建的安全性。接口终端节点由 PrivateLink一种可用于私有访问 Amazon EC2 的技术和 CodeBuild 私有 IP 地址提供支持。 PrivateLink 将您的托管实例与 Amazon EC2 之间的所有网络流量限制到亚马逊网络。 CodeBuild（托管实例无法访问 Internet。） 而且，您无需 Internet 网关、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 连接 CodeBuild 的 AWS 服务一起使用，请使用 NA [T 网关](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_NAT_Instance.html)。
+  VPC 端点仅通过 Amazon Route 53 支持 Amazon 提供的 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 Web Services 一般参考》中的 [Amazon Simple Storage Service](https://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region)。如果您使用向 Amazon S3 发出请求，请将默认区域设置为创建存储桶的相同区域，或者在请求中使用`--region`参数。 AWS CLI 

## 为创建 VPC 终端节点 CodeBuild
<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_cn/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 端点会相应地更新。

## 为创建 VPC 终端节点策略 CodeBuild
<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://aws.amazon.com/codebuild/定价/。](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创建实例集时启用此特征。您需要定义几个属性：

**定义代理配置 - 可选**  
对预留容量实例应用网络访问控制的代理配置。

**默认行为**  
定义传出流量的行为。    
**允许**  
默认情况下，允许流向所有目标的传出流量。  
**拒绝**  
默认情况下，拒绝流向所有目标的传出流量。

**代理规则**  
指定要为其限制网络访问控制的目标域。

要在控制台中定义代理配置，请参阅[创建预留容量实例集](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 VPC 的私有子网中安装代理服务器。

在代理服务器上运行 CodeBuild 有两个主要用例：
+  它不再需要您的 VPC 中的 NAT 网关或 NAT 实例。
+  它允许您指定代理服务器中的实例 URLs 可以访问的 URLs 实例以及代理服务器拒绝访问的实例。

 您可以 CodeBuild 与两种类型的代理服务器一起使用。对于这两者，代理服务器都在公有子网中 CodeBuild 运行，在私有子网中运行。
+  **显式代理**：如果您使用显式代理服务器`NO_PROXY`，则必须在项目级别配置`HTTP_PROXY`、和`HTTPS_PROXY`环境变量。 CodeBuild 有关更多信息，请参阅[在中更改构建项目设置 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 中的一个公有子网。
+  CodeBuild 的 VPC 中的一个私有子网。
+  一个 Internet 网关，允许 VPC 和 Internet 之间进行通信。

 下图显示了组件的交互方式。

![\[图中显示了组件的交互方式。\]](http://docs.aws.amazon.com/zh_cn/codebuild/latest/userguide/images/codebuild-proxy-transparent.png)


## 设置 VPC、子网和网络网关
<a name="use-proxy-server-transparent-setup"></a>

 要在透明或显式代理服务器 AWS CodeBuild 中运行，需要执行以下步骤。

1. 创建 VPC。有关信息，请参阅《Amazon VPC 用户指南》中的[创建 VPC](https://docs.aws.amazon.com/vpc/latest/userguide/working-with-vpcs.html#Create-VPC)。

1. 在您的 VPC 中创建两个子网。一个是名为 `Public Subnet` 的公有子网，代理服务器将在其中运行。另一个是名为的私有子网，`Private Subnet`在其中 CodeBuild 运行。

   有关信息，请参阅[在 VPC 中创建子网](https://docs.aws.amazon.com/vpc/latest/userguide/working-with-vpcs.html#AddaSubnet)。

1.  创建 Internet 网关，并将其连接到您的 VPC。有关更多信息，请参阅[创建并附加 Internet 网关](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Internet_Gateway.html#Add_IGW_Attach_Gateway)。

1.  向默认路由表添加一条规则，该规则将来自 VPC 的传出流量路由到 Internet 网关。有关信息，请参阅[在路由表中添加和删除路由](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Route_Tables.html#AddRemoveRoutes)。

1.  向 VPC 的默认安全组添加一条规则，该规则允许来自 VPC (0.0.0.0/0) 的入站 SSH 流量 (0.0.0.0/0)。

1.  请按照《Amazon EC2 用户指南》中的[使用启动实例向导启动实例](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/launching-instance.html)来启动 Amazon Linux 实例。当您运行该向导时，请选择以下选项：
   +  在**选择实例类型**中，选择一个 Amazon Linux 亚马逊机器映像（AMI）。
   +  在**子网**中，选择您在本主题的前面步骤中创建的公有子网。如果您使用了建议的名称，则该名称是**公有子网**。
   +  在**自动分配公有 IP** 中，选择**启用**。
   +  在**配置安全组**页面上，对于**分配安全组**，选择**选择现有安全组**。接下来，选择默认安全组。
   +  选择**启动**后，选择现有密钥对或创建密钥对。

    选择所有其他选项的默认设置。

1.  在您的 EC2 实例运行后，禁用 source/destination 检查。有关信息，请参阅 *Amazon VPC 用户指南*中的[禁用 Source/Destination 检查](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_NAT_Instance.html#EIP_Disable_SrcDestCheck)。

1.  在 VPC 中创建路由表。向路由表中添加一条规则，该规则将发往 Internet 的流量路由到您的代理服务器。将此路由表与私有子网关联。这是必需的，这样才能始终通过代理服务器路由来自私有子网中 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 流量封装在一个传输层安全性协议（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 请求消息中检索主机标头字段，该字段指定所请求的 Internet 主机。

# 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 的请求。接下来的两行授予您的代理服务器访问可能 URLs 使用的目标的权限 AWS CodeBuild。编辑最后一行的正则表达式以指定 S3 存储桶或 AWS 区域中的 CodeCommit 存储库。例如：
  + 如果您的源是 Amazon S3，请使用命令 **acl download\$1src dstdom\$1regex .\$1s3\$1.us-west-1\$1.amazonaws\$1.com** 来授权访问 `us-west-1` 区域中的 S3 存储桶。
  +  如果您的来源是 AWS CodeCommit，请使用将 AWS 区域`git-codecommit.<your-region>.amazonaws.com`添加到允许列表中。

  ```
  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 超时错误，请参阅[RequestError CodeBuild 在代理服务器上运行时出现超时错误](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 项目的方式。示例网站是 Bitbucket GitHub、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 上侦听 HTTP 流量（而不是 80），并在端口 3130 上侦听 HTTPS 流量（而不是 443）。使用 **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. 在构建规范文件中添加以下语句，以便 `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)。

下面是用于配置 VPC 以使用 CloudFormation 的 AWS CodeBuild YAML 模板。该文件也可在 [samples.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
```