1
0
mirror of synced 2024-11-25 22:36:04 +03:00

Update AWS template (#1463)

This commit is contained in:
Scottpedia 2023-09-27 23:29:07 -04:00 committed by GitHub
parent f86c1eff4b
commit 45908905a2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 126 additions and 73 deletions

View File

@ -2,7 +2,7 @@
# 使用 CloudFormation 在 Amazon EC2 上部署 # 使用 CloudFormation 在 Amazon EC2 上部署
使用这个模板,你可以在 Amazon Elastic Compute CloudAmazon EC2上快速搭建一个 IPsec VPN 服务器。在继续之前,请参见 EC2 [定价细节](https://aws.amazon.com/cn/ec2/pricing/on-demand/)。在部署中使用 `t2.micro` 服务器实例可能符合 [AWS 免费套餐](https://aws.amazon.com/cn/free/) 的资格。 使用这个模板,你可以在 Amazon Elastic Compute CloudAmazon EC2上快速搭建一个 IPsec VPN 服务器。在继续之前,请参见 EC2 [定价细节](https://aws.amazon.com/cn/ec2/pricing/on-demand/)。在部署中使用 `t2.micro` `t3.micro` 服务器实例可能符合 [AWS 免费套餐](https://aws.amazon.com/cn/free/) 的资格。
可用的自定义参数: 可用的自定义参数:
@ -80,22 +80,30 @@ EC2 上的每个 Linux 服务器发行版本都有它自己的默认登录用户
| CentOS (`CentOS 7`) | `centos` | | CentOS (`CentOS 7`) | `centos` |
| Amazon Linux 2 | `ec2-user` | | Amazon Linux 2 | `ec2-user` |
此模板在部署期间为你生成一个密钥对,并且在成功创建堆栈后,其中的私钥将在 **Outputs** 选项卡下以文本形式提供 此模板在部署期间为你生成一个密钥对。在成功创建堆栈后,你可以使用以下的其中一种方式来获取私钥
如果要通过 SSH 访问 VPN 服务器,则需要将 **Outputs** 选项卡中的私钥保存到你的计算机上的一个新文件。 1. 在 **Outputs** 页面下拷贝密钥对 ID ,然后使用以下命令来提取私钥内容并且将其保存为一个证书文件:
> **注:** 在保存到你的计算机之前,你可能需要修改私钥的格式,比如用换行符替换所有的空格。在保存后,需要为该私钥文件设置[适当的权限](https://docs.aws.amazon.com/zh_cn/AWSEC2/latest/UserGuide/connection-prereqs.html#connection-prereqs-private-key)才能使用 > **注:** 在使用以下命令前,你需要在你的电脑上正确的安装和配置好 AWS 命令行。更多关于开始使用 AWS 命令行的信息,请参照 [Get started with the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html)
![显示密钥](images/show-key.png) ```
$ aws ssm get-parameter --region your-region --name /ec2/keypair/your-key-pair-id --with-decryption --query Parameter.Value --output text > new-key-pair.pem
```
![显示密钥 ID](images/show-key-id.png)
2. 直接从 **Outputs** 页面拷贝私钥对内容 ,然后将其保存入一个证书文件。请注意在保存到你的计算机之前,你可能需要修改私钥的格式,比如用换行符替换所有的空格。在保存后,需要为该私钥文件设置[适当的权限](https://docs.aws.amazon.com/zh_cn/AWSEC2/latest/UserGuide/connection-prereqs.html#connection-prereqs-private-key)才能使用。
![显示密钥内容](images/show-key-id.png)
要为私钥文件设置适当的权限,请在该文件所在的目录下运行以下命令: 要为私钥文件设置适当的权限,请在该文件所在的目录下运行以下命令:
```bash ```bash
$ sudo chmod 400 key-file.pem $ sudo chmod 400 new-key-file.pem
``` ```
使用 SSH 登录到 EC2 实例的示例命令: 使用 SSH 登录到 EC2 实例的示例命令:
```bash ```bash
$ ssh -i path/to/your/key-file.pem instance-username@instance-ip-address $ ssh -i path/to/your/new-key-file.pem instance-username@instance-ip-address
``` ```
</details> </details>
@ -104,10 +112,7 @@ $ ssh -i path/to/your/key-file.pem instance-username@instance-ip-address
如何删除 CloudFormation 堆栈? 如何删除 CloudFormation 堆栈?
</summary> </summary>
你可以使用 CloudFormation 堆栈页面上的 "Delete" 按钮删除你创建的 CloudFormation 堆栈和它相关的资源。请注意,删除堆栈时以下资源不会被自动删除,你可以手动删除: 你可以使用 CloudFormation 堆栈页面上的 "Delete" 按钮删除你创建的 CloudFormation 堆栈和它相关的资源。请注意,删除堆栈时存放生成的 IKEv2 配置文件的 S3 储存桶不会被自动删除。参见上面的 "如何在部署结束后提取 IKEv2 连接配置文件"。
1. 在部署期间添加的 EC2 密钥对。要管理你的密钥对,请转到 EC2 控制台 -> 密钥对。
1. 存放生成的 IKEv2 配置文件的 S3 储存桶。参见上面的 "如何在部署结束后提取 IKEv2 连接配置文件"。
</details> </details>
## 作者 ## 作者

View File

@ -2,7 +2,7 @@
# Deploy to Amazon EC2 using CloudFormation # Deploy to Amazon EC2 using CloudFormation
This template will create a fully-working IPsec VPN server on Amazon Elastic Compute Cloud (Amazon EC2). Please make sure to check the EC2 [pricing details](https://aws.amazon.com/ec2/pricing/on-demand/) before continuing. Using a `t2.micro` server instance for your deployment may qualify for the [AWS Free Tier](https://aws.amazon.com/free/). This template will create a fully-working IPsec VPN server on Amazon Elastic Compute Cloud (Amazon EC2). Please make sure to check the EC2 [pricing details](https://aws.amazon.com/ec2/pricing/on-demand/) before continuing. Using a `t2.micro` or `t3.micro` server instance for your deployment may qualify for the [AWS Free Tier](https://aws.amazon.com/free/).
Available customization parameters: Available customization parameters:
@ -80,22 +80,30 @@ List of default usernames:
| CentOS (`CentOS 7`) | `centos` | | CentOS (`CentOS 7`) | `centos` |
| Amazon Linux 2 | `ec2-user` | | Amazon Linux 2 | `ec2-user` |
This template generates a key pair for you during deployment, and the private key will be available as text under the **Outputs** tab after the stack is successfully created. This template generates a key pair for you during deployment, and to acquire the private key you can choose one of the following two methods.
You will need to save the private key from the **Outputs** tab to a file on your computer, if you want to access the VPN server via SSH. 1. Copy the key pair ID displayed under the **Outputs** tab, and use the following command to retrieve the private key material and save it into a certificate file:
> **Note:** You may need to format the private key by replacing all spaces with newlines, before saving to a file. The file will need to be set with [proper permissions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connection-prereqs.html#connection-prereqs-private-key) before using. > **Note:** You need to first properly set up the AWS CLI on your computer before using the following command. For more information on how to get started with AWS CLI, please refer to [Get started with the AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-started.html).
![Show key](images/show-key.png) ```
$ aws ssm get-parameter --region your-region --name /ec2/keypair/your-key-pair-id --with-decryption --query Parameter.Value --output text > new-key-file.pem
```
![Show key ID](images/show-key-id.png)
2. Copy the private key material directly from the **Outputs** tab, and save it into a certificate file. Note that You may need to format the private key by replacing all spaces with newlines, before saving to a file. The file will need to be set with [proper permissions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/connection-prereqs.html#connection-prereqs-private-key) before using.
![Show key material](images/show-key.png)
To apply proper permissions to your private key file, run the following command under the directory where the file is located: To apply proper permissions to your private key file, run the following command under the directory where the file is located:
```bash ```bash
$ sudo chmod 400 key-file.pem $ sudo chmod 400 new-key-file.pem
``` ```
Example command to login to your EC2 instance using SSH: Example command to login to your EC2 instance using SSH:
```bash ```bash
$ ssh -i path/to/your/key-file.pem instance-username@instance-ip-address $ ssh -i path/to/your/new-key-file.pem instance-username@instance-ip-address
``` ```
</details> </details>
@ -104,10 +112,7 @@ $ ssh -i path/to/your/key-file.pem instance-username@instance-ip-address
How to delete the CloudFormation stack? How to delete the CloudFormation stack?
</summary> </summary>
You may use the "Delete" button on the CloudFormation stack page to delete the CloudFormation stack you created and its associated resources. Note that when deleting the stack, the following resources will not be automatically deleted, you may manually delete them: You may use the "Delete" button on the CloudFormation stack page to delete the CloudFormation stack you created and its associated resources. Note that when deleting the stack, the S3 bucket that stores the generated IKEv2 credentials will not be automatically deleted. Refer to "How to retrieve the IKEv2 credentials following the deployment" above.
1. The EC2 key pair that was added during deployment. To manage your key pairs, go to EC2 console -> Key Pairs.
1. The S3 bucket that stores the generated IKEv2 credentials. Refer to "How to retrieve the IKEv2 credentials following the deployment" above.
</details> </details>
## Author ## Author

View File

@ -52,10 +52,7 @@
"Type": "AWS::IAM::InstanceProfile", "Type": "AWS::IAM::InstanceProfile",
"Properties": { "Properties": {
"InstanceProfileName": { "InstanceProfileName": {
"Fn::GetAtt": [ "Ref": "KeyPair"
"KeyPairInfo",
"KeyName"
]
}, },
"Path": "/setup-ipsec-vpn/", "Path": "/setup-ipsec-vpn/",
"Roles": [ "Roles": [
@ -66,7 +63,7 @@
}, },
"DependsOn": [ "DependsOn": [
"S3ExecutionRole", "S3ExecutionRole",
"KeyPairInfo" "KeyPair"
] ]
}, },
"Ikev2S3Bucket": { "Ikev2S3Bucket": {
@ -90,14 +87,14 @@
}, },
"BucketName": { "BucketName": {
"Fn::GetAtt": [ "Fn::GetAtt": [
"KeyPairInfo", "KeyPairDisplayFunctionInfo",
"KeyName" "Combination"
] ]
} }
}, },
"Metadata": {}, "Metadata": {},
"DependsOn": [ "DependsOn": [
"KeyPairInfo" "KeyPair"
] ]
}, },
"OpenBucketPolicy": { "OpenBucketPolicy": {
@ -295,10 +292,7 @@
"Ref": "InstanceType" "Ref": "InstanceType"
}, },
"KeyName": { "KeyName": {
"Fn::GetAtt": [ "Ref": "KeyPair"
"KeyPairInfo",
"KeyName"
]
}, },
"ImageId": { "ImageId": {
"Fn::GetAtt": [ "Fn::GetAtt": [
@ -310,13 +304,29 @@
"Metadata": {}, "Metadata": {},
"DependsOn": [ "DependsOn": [
"VpnRouteTable", "VpnRouteTable",
"KeyPairCreation", "KeyPair",
"AMIInfoFunction", "AMIInfoFunction",
"VpnSecurityGroup", "VpnSecurityGroup",
"Ikev2S3Bucket", "Ikev2S3Bucket",
"IAMInstanceProfile" "IAMInstanceProfile"
] ]
}, },
"KeyPair": {
"Type": "AWS::EC2::KeyPair",
"Properties": {
"KeyName": {
"Fn::Join": [
"-",
[
"setup-ipsec-vpn",
{
"Ref": "AWS::StackName"
}
]
]
}
}
},
"VpnSecurityGroup": { "VpnSecurityGroup": {
"Type": "AWS::EC2::SecurityGroup", "Type": "AWS::EC2::SecurityGroup",
"Properties": { "Properties": {
@ -374,7 +384,7 @@
}, },
"Metadata": {} "Metadata": {}
}, },
"KeyPairCreation": { "KeyPairDisplayFunction": {
"Type": "AWS::Lambda::Function", "Type": "AWS::Lambda::Function",
"Properties": { "Properties": {
"Handler": "index.handler", "Handler": "index.handler",
@ -385,7 +395,6 @@
"Arn" "Arn"
] ]
}, },
"Timeout": 30,
"Code": { "Code": {
"ZipFile": { "ZipFile": {
"Fn::Join": [ "Fn::Join": [
@ -395,30 +404,72 @@
"import cfnresponse", "import cfnresponse",
"import string", "import string",
"import random", "import random",
"import traceback",
"'''", "'''",
"This python program should be embedded into its designated cloudformation", "This python program should be embedded into its designated cloudformation",
"template as the inline code of one of the lambda functions.", "template as the inline code of one of the lambda functions.",
"Its function is to create a random combination of 20 characters for the naming of the Ikev2S3Bucket, and",
"to retrieve the private key material for display under the Outputs tab.",
"'''", "'''",
"def handler(event, context):", "def handler(event, context):",
" try:", " try:",
" keyName = 'setup-ipsec-vpn-' + ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(20)).lower()", " if event['RequestType'] == 'Delete':",
" cfnresponse.send(event, context, cfnresponse.SUCCESS, {})",
" elif event['RequestType'] == 'Create':",
" rCombination = 'setup-ipsec-vpn-' + ''.join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(20)).lower()",
" region = event['ResourceProperties']['Region']", " region = event['ResourceProperties']['Region']",
" ec2 = boto3.client('ec2',region)", " ssm = boto3.client('ssm',region)",
" response = ec2.create_key_pair(", " response = ssm.get_parameter(",
" KeyName=keyName", {
"Fn::Join": [
"",
[
" Name='/ec2/keypair/",
{
"Fn::GetAtt": [
"KeyPair",
"KeyPairId"
]
},
"',"
]
]
},
" WithDecryption=True",
" )", " )",
" keyMaterial = response['KeyMaterial']", " keyMaterial = response['Parameter']['Value']",
" cfnresponse.send(event, context, cfnresponse.SUCCESS, {'KeyMaterial':keyMaterial, 'KeyName':keyName}, 'KeyPairInfo')", " cfnresponse.send(event, context, cfnresponse.SUCCESS, {'KeyMaterial':keyMaterial, 'Combination':rCombination}, 'KeyPairDisplayFunctionInfo')",
" except Exception:", " except Exception as e:",
" cfnresponse.send(event, context, cfnresponse.FAILED, {})" " cfnresponse.send(event, context, cfnresponse.FAILED, {'ErrorMsg':traceback.format_exc()})"
] ]
] ]
} }
},
"Timeout": 30
},
"Metadata": {},
"DependsOn": [
"LambdaExecutionRole",
"KeyPair"
]
},
"KeyPairDisplayFunctionInfo": {
"Type": "Custom::KeyPairDisplayFunctionInfo",
"Properties": {
"Region": {
"Ref": "AWS::Region"
},
"ServiceToken": {
"Fn::GetAtt": [
"KeyPairDisplayFunction",
"Arn"
]
} }
}, },
"Metadata": {}, "Metadata": {},
"DependsOn": [ "DependsOn": [
"LambdaExecutionRole" "KeyPairDisplayFunction",
"KeyPair"
] ]
}, },
"AMIInfo": { "AMIInfo": {
@ -460,6 +511,7 @@
[ [
"import boto3", "import boto3",
"import cfnresponse", "import cfnresponse",
"import traceback",
"'''", "'''",
"This python script should be embeded into its designated cloudformation template.", "This python script should be embeded into its designated cloudformation template.",
"Its function is to sort out the correct AMI image to use for each of the distribution options available.", "Its function is to sort out the correct AMI image to use for each of the distribution options available.",
@ -487,7 +539,7 @@
" AMIId = images[0]['ImageId']", " AMIId = images[0]['ImageId']",
" cfnresponse.send(event, context, cfnresponse.SUCCESS, {'AMIId':AMIId}, 'AMIInfo')", " cfnresponse.send(event, context, cfnresponse.SUCCESS, {'AMIId':AMIId}, 'AMIInfo')",
" except Exception:", " except Exception:",
" cfnresponse.send(event, context, cfnresponse.FAILED, {})" " cfnresponse.send(event, context, cfnresponse.FAILED, {'ErrorMsg':traceback.format_exc()})"
] ]
] ]
} }
@ -588,24 +640,6 @@
}, },
"Metadata": {} "Metadata": {}
}, },
"KeyPairInfo": {
"Type": "Custom::KeyPairInfo",
"Properties": {
"Region": {
"Ref": "AWS::Region"
},
"ServiceToken": {
"Fn::GetAtt": [
"KeyPairCreation",
"Arn"
]
}
},
"Metadata": {},
"DependsOn": [
"KeyPairCreation"
]
},
"InternetGatewayAttachment": { "InternetGatewayAttachment": {
"Type": "AWS::EC2::VPCGatewayAttachment", "Type": "AWS::EC2::VPCGatewayAttachment",
"Properties": { "Properties": {
@ -648,7 +682,7 @@
}, },
"InstanceType": { "InstanceType": {
"Type": "String", "Type": "String",
"Description": "The instance type of your VPN server. Using t2.micro may qualify for the AWS Free Tier.", "Description": "The instance type of your VPN server. Using t2.micro or t3.micro may qualify for the AWS Free Tier.",
"AllowedValues": [ "AllowedValues": [
"t2.micro", "t2.micro",
"t3.nano", "t3.nano",
@ -694,24 +728,33 @@
"Ref": "VpnIpsecPsk" "Ref": "VpnIpsecPsk"
} }
}, },
"5EC2PrivateKeyMaterial": { "5EC2PrivateKeyId": {
"Description": "The ID of the key pair created. For more information regarding how to retrieve the private key for authentication, please refer to: https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/aws/README.md#faqs",
"Value": {
"Fn::GetAtt": [
"KeyPair",
"KeyPairId"
]
}
},
"6EC2PrivateKeyMaterial": {
"Description": "The content of your private key for accessing the VPN server via SSH. Save it as a file for use when connecting.", "Description": "The content of your private key for accessing the VPN server via SSH. Save it as a file for use when connecting.",
"Value": { "Value": {
"Fn::GetAtt": [ "Fn::GetAtt": [
"KeyPairInfo", "KeyPairDisplayFunctionInfo",
"KeyMaterial" "KeyMaterial"
] ]
} }
}, },
"6NextStep": { "7NextStep": {
"Description": "Learn how to configure VPN clients.", "Description": "Learn how to configure VPN clients.",
"Value": "https://github.com/hwdsl2/setup-ipsec-vpn#next-steps" "Value": "https://github.com/hwdsl2/setup-ipsec-vpn#next-steps"
}, },
"7WarningForDebianUsers": { "8WarningForDebianUsers": {
"Description": "Please be noted that due to Debian images on AWS EC2 using cloud kernels, you are unable to use IPSec/L2TP mode if your server is running Debian. For more information, please refer to the link to the left.", "Description": "Please be noted that due to Debian images on AWS EC2 using cloud kernels, you are unable to use IPSec/L2TP mode if your server is running Debian. For more information, please refer to the link to the left.",
"Value": "https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/docs/clients.md#debian-kernel" "Value": "https://github.com/hwdsl2/setup-ipsec-vpn/blob/master/docs/clients.md#debian-kernel"
}, },
"8RetrieveYourIkev2Credentials": { "9RetrieveYourIkev2Credentials": {
"Description": "Please use the following link to download your IKEv2 connection credentials. The password to the ZIP file that stores the credentials, is the same password used to connect to your VPN server. The download link for the credentials will expire in ONE day.", "Description": "Please use the following link to download your IKEv2 connection credentials. The password to the ZIP file that stores the credentials, is the same password used to connect to your VPN server. The download link for the credentials will expire in ONE day.",
"Value": { "Value": {
"Fn::Join": [ "Fn::Join": [

BIN
aws/images/show-key-id.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 427 KiB