

# 与其他 Amazon Web Services 账户中的 VPC 建立对等连接
与另一个账户中的 VPC 对等

您可以使用 [https://docs.amazonaws.cn/AWSCloudFormation/latest/TemplateReference/aws-resource-ec2-vpcpeeringconnection.html](https://docs.amazonaws.cn/AWSCloudFormation/latest/TemplateReference/aws-resource-ec2-vpcpeeringconnection.html) 与其他 Amazon Web Services 账户中的虚拟私有云（VPC）建立对等连接。这会在两个 VPC 之间创建网络连接，使您能够在它们之间路由流量，它们可以像在同一网络中那样进行通信。VPC 对等连接有助于简化数据访问和数据传输。

要建立 VPC 对等连接，您需要为单个 CloudFormation 堆栈中的两个单独 Amazon Web Services 账户 授权。

有关 VPC 对等连接及其限制的更多信息，请参阅 [Amazon VPC 对等连接指南](https://docs.amazonaws.cn/vpc/latest/peering/)。

## 先决条件


1. 您需要为对等连接提供对等 VPC ID、对等 Amazon Web Services 账户 ID 以及[跨账户访问角色](https://docs.amazonaws.cn/IAM/latest/UserGuide/id_roles_common-scenarios_aws-accounts.html)。
**注意**  
本演练涉及两个账户：第一个是允许跨账户对等的账户 (*接受方账户*)。第二个是请求对等连接的账户 (*请求者账户*)。

1. 要接受 VPC 对等连接，您必须能够担任跨账户访问角色。该资源的行为方式与同一账户中的 VPC 对等连接资源相同。要了解 IAM 管理员如何授予代入跨账户角色的权限，请参阅 *IAM 用户指南*中的[向用户授予切换角色的权限](https://docs.amazonaws.cn/IAM/latest/UserGuide/id_roles_use_permissions-to-switch.html)。

## 步骤 1：创建 VPC 和跨账户角色


在该步骤中，您需要在*接受方账户* 中创建 VPC 和角色。

**创建 VPC 和跨账户访问角色**

1. 登录到 Amazon Web Services 管理控制台 并打开 Amazon CloudFormation 控制台 [https://console.aws.amazon.com/cloudformation](https://console.amazonaws.cn/cloudformation/)。

1. 在**堆栈**页面，选择右上角的**创建堆栈**，然后选择**使用新资源（标准）**。

1. 在**先决条件 – 准备模板**中，选择**选择现有模板**，然后依次选择**上传模板文件** > **选择文件**。

1. 在本地计算机上打开文本编辑器并添加以下模板之一。保存文件并返回控制台，将其选择为模板文件。  
**Example JSON**  

   ```
   {
     "AWSTemplateFormatVersion": "2010-09-09",
     "Description": "Create a VPC and an assumable role for cross account VPC peering.",
     "Parameters": {
       "PeerRequesterAccountId": {
         "Type": "String"
       }
     },
     "Resources": {
       "vpc": {
         "Type": "AWS::EC2::VPC",
         "Properties": {
           "CidrBlock": "10.1.0.0/16",
           "EnableDnsSupport": false,
           "EnableDnsHostnames": false,
           "InstanceTenancy": "default"
         }
       },
       "peerRole": {
         "Type": "AWS::IAM::Role",
         "Properties": {
           "AssumeRolePolicyDocument": {
             "Statement": [
               {
                 "Principal": {
                   "AWS": {
                     "Ref": "PeerRequesterAccountId"
                   }
                 },
                 "Action": [
                   "sts:AssumeRole"
                 ],
                 "Effect": "Allow"
               }
             ]
           },
           "Path": "/",
           "Policies": [
             {
               "PolicyName": "root",
               "PolicyDocument": {
                 "Version": "2012-10-17",		 	 	 
                 "Statement": [
                   {
                     "Effect": "Allow",
                     "Action": "ec2:AcceptVpcPeeringConnection",
                     "Resource": "*"
                   }
                 ]
               }
             }
           ]
         }
       }
     },
     "Outputs": {
       "VPCId": {
         "Value": {
           "Ref": "vpc"
         }
       },
       "RoleARN": {
         "Value": {
           "Fn::GetAtt": [
             "peerRole",
             "Arn"
           ]
         }
       }
     }
   }
   ```  
**Example YAML**  

   ```
   AWSTemplateFormatVersion: 2010-09-09
   Description: Create a VPC and an assumable role for cross account VPC peering.
   Parameters:
     PeerRequesterAccountId:
       Type: String
   Resources:
     vpc:
       Type: AWS::EC2::VPC
       Properties:
         CidrBlock: 10.1.0.0/16
         EnableDnsSupport: false
         EnableDnsHostnames: false
         InstanceTenancy: default
     peerRole:
       Type: AWS::IAM::Role
       Properties:
         AssumeRolePolicyDocument:
           Statement:
             - Principal:
                 AWS: !Ref PeerRequesterAccountId
               Action:
                 - 'sts:AssumeRole'
               Effect: Allow
         Path: /
         Policies:
           - PolicyName: root
             PolicyDocument:
               Version: 2012-10-17 		 	 	 
               Statement:
                 - Effect: Allow
                   Action: 'ec2:AcceptVpcPeeringConnection'
                   Resource: '*'
   Outputs:
     VPCId:
       Value: !Ref vpc
     RoleARN:
       Value: !GetAtt 
         - peerRole
         - Arn
   ```

1. 选择**下一步**。

1. 为堆栈提供一个名称（例如 **VPC-owner**），然后在 **PeerRequesterAccountId** 字段中输入*请求者账户*的 Amazon Web Services 账户 ID。

1. 接受默认值，然后选择 **Next**。

1. 选择**我确认 Amazon CloudFormation 可能创建 IAM 资源**，然后选择**创建堆栈**。

## 步骤 2：创建包含 `AWS::EC2::VPCPeeringConnection` 的模板


现在，您已创建 VPC 和跨账户角色，您可以与使用另一个 Amazon Web Services 账户（*请求者账户*）的 VPC 进行对等。

**创建包含 [AWS::EC2::VPCPeeringConnection](https://docs.amazonaws.cn/AWSCloudFormation/latest/TemplateReference/aws-resource-ec2-vpcpeeringconnection.html) 资源的模板**

1. 返回 Amazon CloudFormation 控制台主页。

1. 在**堆栈**页面，选择右上角的**创建堆栈**，然后选择**使用新资源（标准）**。

1. 在**先决条件 – 准备模板**中，选择**选择现有模板**，然后依次选择**上传模板文件** > **选择文件**。

1. 在本地计算机上打开文本编辑器并添加以下模板之一。保存文件并返回控制台，将其选择为模板文件。  
**Example JSON**  

   ```
   {
     "AWSTemplateFormatVersion": "2010-09-09",
     "Description": "Create a VPC and a VPC Peering connection using the PeerRole to accept.",
     "Parameters": {
       "PeerVPCAccountId": {
         "Type": "String"
       },
       "PeerVPCId": {
         "Type": "String"
       },
       "PeerRoleArn": {
         "Type": "String"
       }
     },
     "Resources": {
       "vpc": {
         "Type": "AWS::EC2::VPC",
         "Properties": {
           "CidrBlock": "10.2.0.0/16",
           "EnableDnsSupport": false,
           "EnableDnsHostnames": false,
           "InstanceTenancy": "default"
         }
       },
       "vpcPeeringConnection": {
         "Type": "AWS::EC2::VPCPeeringConnection",
         "Properties": {
           "VpcId": {
             "Ref": "vpc"
           },
           "PeerVpcId": {
             "Ref": "PeerVPCId"
           },
           "PeerOwnerId": {
             "Ref": "PeerVPCAccountId"
           },
           "PeerRoleArn": {
             "Ref": "PeerRoleArn"
           }
         }
       }
     },
     "Outputs": {
       "VPCId": {
         "Value": {
           "Ref": "vpc"
         }
       },
       "VPCPeeringConnectionId": {
         "Value": {
           "Ref": "vpcPeeringConnection"
         }
       }
     }
   }
   ```  
**Example YAML**  

   ```
   AWSTemplateFormatVersion: 2010-09-09
   Description: Create a VPC and a VPC Peering connection using the PeerRole to accept.
   Parameters:
     PeerVPCAccountId:
       Type: String
     PeerVPCId:
       Type: String
     PeerRoleArn:
       Type: String
   Resources:
     vpc:
       Type: AWS::EC2::VPC
       Properties:
         CidrBlock: 10.2.0.0/16
         EnableDnsSupport: false
         EnableDnsHostnames: false
         InstanceTenancy: default
     vpcPeeringConnection:
       Type: AWS::EC2::VPCPeeringConnection
       Properties:
         VpcId: !Ref vpc
         PeerVpcId: !Ref PeerVPCId
         PeerOwnerId: !Ref PeerVPCAccountId
         PeerRoleArn: !Ref PeerRoleArn
   Outputs:
     VPCId:
       Value: !Ref vpc
     VPCPeeringConnectionId:
       Value: !Ref vpcPeeringConnection
   ```

1. 选择**下一步**。

1. 为堆栈提供一个名称（例如，**VPC-peering-connection**）。

1. 接受默认值，然后选择 **Next**。

1. 选择**我确认 Amazon CloudFormation 可能创建 IAM 资源**，然后选择**创建堆栈**。

## 创建具有高度限制策略的模板


在将您的 VPC 与另一个 Amazon Web Services 账户 对等时，您可能需要创建一个高度限制的策略。

以下示例模板显示如何更改 VPC 对等所有者模板 (上面步骤 1 中创建的*接受方账户*)，以加强对它的限制。

**Example JSON**  

```
{
  "AWSTemplateFormatVersion":"2010-09-09",
  "Description":"Create a VPC and an assumable role for cross account VPC peering.",
  "Parameters":{
    "PeerRequesterAccountId":{
      "Type":"String"
    }
  },
  "Resources":{
    "peerRole":{
      "Type":"AWS::IAM::Role",
      "Properties":{
        "AssumeRolePolicyDocument":{
          "Statement":[
            {
              "Action":[
                "sts:AssumeRole"
              ],
              "Effect":"Allow",
              "Principal":{
                "AWS":{
                  "Ref":"PeerRequesterAccountId"
                }
              }
            }
          ]
        },
        "Path":"/",
        "Policies":[
          {
            "PolicyDocument":{
              "Statement":[
                {
                  "Action":"ec2:acceptVpcPeeringConnection",
                  "Effect":"Allow",
                  "Resource":{
                    "Fn::Sub":"arn:aws:ec2:${AWS::Region}:${AWS::AccountId}:vpc/${vpc}"
                  }
                },
                {
                  "Action":"ec2:acceptVpcPeeringConnection",
                  "Condition":{
                    "StringEquals":{
                      "ec2:AccepterVpc":{
                        "Fn::Sub":"arn:aws:ec2:${AWS::Region}:${AWS::AccountId}:vpc/${vpc}"
                      }
                    }
                  },
                  "Effect":"Allow",
                  "Resource":{
                    "Fn::Sub":"arn:aws:ec2:${AWS::Region}:${AWS::AccountId}:vpc-peering-connection/*"
                  }
                }
              ],
              "Version":"2012-10-17" 		 	 	 
            },
            "PolicyName":"root"
          }
        ]
      }
    },
    "vpc":{
      "Type":"AWS::EC2::VPC",
      "Properties":{
        "CidrBlock":"10.1.0.0/16",
        "EnableDnsHostnames":false,
        "EnableDnsSupport":false,
        "InstanceTenancy":"default"
      }
    }
  },
  "Outputs":{
    "RoleARN":{
      "Value":{
        "Fn::GetAtt":[
          "peerRole",
          "Arn"
        ]
      }
    },
    "VPCId":{
      "Value":{
        "Ref":"vpc"
      }
    }
  }
}
```

**Example YAML**  

```
AWSTemplateFormatVersion: 2010-09-09
Description: Create a VPC and an assumable role for cross account VPC peering.
Parameters:
  PeerRequesterAccountId:
    Type: String
Resources:
  peerRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Action:
              - 'sts:AssumeRole'
            Effect: Allow
            Principal:
              AWS:
                Ref: PeerRequesterAccountId
      Path: /
      Policies:
        - PolicyDocument:
            Statement:
              - Action: 'ec2:acceptVpcPeeringConnection'
                Effect: Allow
                Resource:
                  'Fn::Sub': 'arn:aws:ec2:${AWS::Region}:${AWS::AccountId}:vpc/${vpc}'
              - Action: 'ec2:acceptVpcPeeringConnection'
                Condition:
                  StringEquals:
                    'ec2:AccepterVpc':
                      'Fn::Sub': 'arn:aws:ec2:${AWS::Region}:${AWS::AccountId}:vpc/${vpc}'
                Effect: Allow
                Resource:
                  'Fn::Sub': >-
                    arn:aws:ec2:${AWS::Region}:${AWS::AccountId}:vpc-peering-connection/*
            Version: 2012-10-17 		 	 	 
          PolicyName: root
  vpc:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.1.0.0/16
      EnableDnsHostnames: false
      EnableDnsSupport: false
      InstanceTenancy: default
Outputs:
  RoleARN:
    Value:
      'Fn::GetAtt':
        - peerRole
        - Arn
  VPCId:
    Value:
      Ref: vpc
```

要访问 VPC，您可以使用上面步骤 2 中使用的请求者模板。

有关更多信息，请参阅*《Amazon VPC 对等连接指南》*中的[VPC 对等连接的身份和访问权限管理](https://docs.amazonaws.cn/vpc/latest/peering/security-iam.html)。