如何在AWS上启动远程服务器

AWS is so cool because it is made up of discreet building blocks that you can use to build some fairly complex infrastructure. This is awesome once you get a handle on things. But when you are just starting out you need to know things like "how do I get the IP address of my server" and "wait which SSH key".

AWS之所以如此酷,是因为它由谨慎的构建基块组成,您可以使用它们构建一些相当复杂的基础架构。 一旦掌握了一切,这将非常棒。 但是,当您刚入门时,您需要了解诸如“我如何获取服务器的IP地址”和“等待哪个SSH密钥”之类的知识。

Let's go over a few of the key concepts, and then spin up our very own server on the cloud!

让我们研究一些关键概念,然后在云上启动我们自己的服务器!

在AWS上管理远程服务器所需的知识 (What you need to know to administer remote servers on AWS)

There are many reasons why you might want to get started on AWS. Maybe your company is moving infrastructure onto the cloud. Maybe you want to start freelancing and don't want to invest in upfront server costs. Or maybe you just want to learn a new skillset.

有许多原因使您可能想开始使用AWS。 也许您的公司正在将基础架构迁移到云中。 也许您想开始自由职业,并且不想投资于前期服务器成本。 或者,也许您只是想学习新的技能。

In order to spin up a remote server on AWS you need to know a few foundational AWS terms and concepts. I'll go over some terms that are directly applicable to spinning up a remote server, but these same concepts are used for more complex infrastructure services such as ElasticBeanstalk, Docker Swarm, and Kubernetes.

为了在AWS上启动远程服务器,您需要了解一些基本的AWS术语和概念。 我将讨论一些直接适用于扩展远程服务器的术语,但是这些相同的概念用于更复杂的基础架构服务,例如ElasticBeanstalk,Docker Swarm和Kubernetes。

弹性计算云(EC2) (Elastic Compute Cloud (EC2))

AWS EC2 instances are where you compute power lives. These are your remote servers. Knowing how to deal with EC2 instances is incredibly important because they appear just about everywhere.

AWS EC2实例是您计算功率寿命的地方。 这些是您的远程服务器。 知道如何处理EC2实例非常重要,因为它们几乎随处可见。

安全组 (Security Groups)

Security groups are what allow access to your various AWS services, in this case an EC2 instance. These define which ports are open for inward and outward bound traffic.

安全组允许访问您的各种AWS服务(在本例中为EC2实例)。 这些定义了哪些端口开放用于向内和向外的绑定流量。

密钥对 (Key Pairs)

Key pairs are your SSH keys. Make sure you keep track of these and keep them somewhere safe! Also, if you use AWS a lot you will start a collection of key pairs, so make sure that you give them descriptive names and not just ssh. ;-)

密钥对是您的SSH密钥。 确保跟踪并确保它们在安全的地方! 另外,如果您经常使用AWS,则会启动一组密钥对,因此请确保为它们提供描述性名称,而不仅仅是ssh 。 ;-)

虚拟私有云(VPC) ( Virtual Private Cloud (VPC))

A VPC is an isolated resource where your compute infrastructure lives. To carry on with my everything is Legos philosophy, the VPC is the Lego box while the EC2, Security Groups, and KeyPairs are the actual Legos.

VPC是计算基础结构所在的隔离资源。 要使我的一切都是Legos理念,VPC是Lego盒子,而EC2,Security Groups和KeyPairs是实际的Legos。

VPCs take care of all of your networking. When you sign up for an AWS account you will get a default VPC and that is what we will be using today.

VPC负责您的所有网络。 当您注册一个AWS账户时,您将获得一个默认的VPC,这就是我们今天要使用的。

如何启动EC2实例 (How to Launch an EC2 Instance)

There are so, so many ways to launch an EC2 instance. Which one you want will depend upon your needs. Today we will go over using the AWS web console and using the python boto3 library.

启动EC2实例的方法有很多。 您想要哪一个取决于您的需求。 今天,我们将使用AWS Web控制台和python boto3库进行介绍。

As a quick aside, because AWS has so many services you have to go into each service individually to manage it. If you're ever lost, just search for your service from the 'Services' Menu.

顺便说一句,由于AWS有这么多服务,因此您必须单独进入每个服务进行管理。 如果您迷路了,只需从“服务”菜单中搜索服务即可。

使用向导启动EC2实例 (Launch an EC2 Instance Using the Wizard )

First you'll need to login to your AWS Console.

首先,您需要登录到AWS控制台。

  1. Click on Services to bring up the search box.

    单击服务以打开搜索框。
  2. Type in the service name you want - in this case, EC2.

    输入所需的服务名称-在这种情况下为EC2。
  3. Click on your service name from the menu to bring you to that services dashboard.

    从菜单中单击您的服务名称,以将您带到该服务仪表板。

选择“启动实例” (Select 'Launch Instance')

Once we're at the EC2 Dashboard you'll want to click the 'Launch Instance' button in the middle of the screen. This will start up the the AWS EC2 Launch Wizard, which will walk us through the process of starting up an EC2 instance.

进入EC2仪表板后,您需要单击屏幕中间的“启动实例”按钮。 这将启动AWS EC2启动向导,该向导将引导我们完成启动EC2实例的过程。

If you want to go through part 2 where we'll startup an EC2 server programatically with Python this is an excellent chance to write down your default VPC id!

如果您想了解第2部分,我们将使用Python编程启动EC2服务器,那么这是写下您的默认VPC ID的绝佳机会!

EC2向导概述 (EC2 Wizard Overview)

Once you select 'Launch Instance' you'll be brought to a wizard. The wizard menu has 7 steps, and you can switch between them as you like to get your instance configured just the way you want it.

选择“启动实例”后,您将进入向导。 向导菜单包含7个步骤,您可以根据需要在它们之间进行切换,以按所需方式配置实例。

EC2向导-选择您的AMI类型 (EC2 Wizard - Select Your AMI Type)

Here is where the magic happens!

这就是魔术发生的地方!

This is where you will choose your AMI type, which is mostly what operating system you want. There are any number of preconfigured AMIs for lots of common use cases, including ML applications, web servers, and databases. Check out the AWS Marketplace to see all the cool AMIs out there!

在这里,您将选择AMI类型,这主要是您想要的操作系统。 对于许多常见用例,包括ML应用程序,Web服务器和数据库,有许多预配置的AMI。 查看AWS Marketplace ,查看那里所有漂亮的AMI!

I like the Amazon Linux 2 image, but you can search for any image type, including Ubuntu, Centos, or any number of Bitnami images.

我喜欢Amazon Linux 2映像,但是您可以搜索任何映像类型,包括Ubuntu,Centos或任意数量的Bitnami映像。

Quick side note here. I love the Bitnami images. They are all awesome, and if you're looking into deploying any kind of web application such as Ghost, Wordpress, Nginx, or even more complex applications like Redash or Airflow I really recommend them.

快速旁注在这里。 我喜欢Bitnami图片。 它们都很棒,如果您正在考虑部署任何类型的Web应用程序,例如Ghost,Wordpress,Nginx,甚至是更复杂的应用程序(例如Redash或Airflow),我都非常推荐它们。

EC2向导-选择您的实例类型 (EC2 Wizard - Choose your Instance Type)

I'm going with the free one because I intend on killing this, but if you're actually using this EC2 instance for anything important you'll want to add more power. If you need anything involving internet, such as transferring data, make sure that you pay attention to the internet capabilities and choose something in the moderate range.

我打算使用免费的版本,因为我打算杀死它,但是如果您实际上将此EC2实例用于任何重要的事情,则需要增加功能。 如果您需要任何涉及互联网的内容,例如传输数据,请确保注意互联网功能并选择适当的范围。

Scroll down and choose either 'Launch' to launch with default settings or 'Configure your Instance' to add in additional configurations such as changing the root file system size, choosing a VPC, or adding in user data.

向下滚动并选择“启动”以默认设置启动,或选择“配置实例”以添加其他配置,例如更改根文件系统大小,选择VPC或添加用户数据。

EC2向导-添加标签 (EC2 Wizard - Add Tags)

When you're just starting out this doesn't matter too much, but as you get going with AWS you will want to make sure that all of your instances have, at the least, Name tags. This will allow you to more easily search for your instances and do nice things like create resource groups to group together your AWS services.

刚开始时这没什么大不了的,但是在使用AWS时,您将要确保所有实例至少都具有Name标签。 这将使您可以更轻松地搜索实例并执行诸如创建资源组以将您的AWS服务分组在一起的出色工作。

In the wizard menu select 'Add Tags'. Don't worry, you can switch between steps in the wizard as often as you like.

在向导菜单中,选择“添加标签”。 不用担心,您可以根据需要在向导中的各个步骤之间进行切换。

EC2向导-配置安全组 (EC2 Wizard - Configure the Security Group)

Before we finish up we'll configure the security group, which is what defines the access rules. AWS will create a security group for you, or you can choose one already. The default is to open port 22 for SSH, but if you'll use this for any web or database applications you will need to open those ports too.

在结束之前,我们将配置安全组,该组定义了访问规则。 AWS将为您创建一个安全组,或者您可以选择一个。 默认设置是为SSH打开端口22,但是如果将其用于任何Web或数据库应用程序,则也需要打开这些端口。

EC2向导-启动 (EC2 Wizard - LAUNCH)

Now that we've told AWS what we want let's launch our instance! Click on the Review and Launch. You'll get a popup window asking you which SSH Key you want. You can also create a new SSH Keypair here.

现在,我们已经告诉了AWS我们想要什么,让我们启动实例! 单击查看并启动。 您将看到一个弹出窗口,询问您想要哪个SSH密钥。 您还可以在此处创建新的SSH密钥对。

EC2向导-确认页面 (EC2 Wizard - Confirmation Page)

Once you've launched you'll be brought to a confirmation page with your EC2 Instance ID.

启动后,您将进入带有EC2实例ID的确认页面。

EC2仪表板-获取您的IP地址 (EC2 Dashboard - Get your IP Address)

There we go! Now all that is left is to wait for our instance to be ready and SSH on over.

好了! 现在剩下的就是等待我们的实例准备好并且SSH结束。

Ok! Now we just have to SSH over to our instance. The details for this will be slightly different depending on which instance type you chose.

好! 现在我们只需要通过SSH切换到我们的实例。 根据您选择的实例类型,此操作的详细信息将略有不同。

This assumes you downloaded your keypair named my-remote-server.pem and moved it to ~/.ssh

假设您下载了名为my-remote-server.pem密钥对并将其移至~/.ssh

chmod 400 ~/.ssh/my-remote-server.pem

# Amazon linux 2 ami
ssh -i ~/.ssh/my-remote-server.pem ec2-user@PUBLIC_DNS

# Ubuntu or Bitnami
ssh -i ~/.ssh/my-remote-server.pem ubuntu@PUBLIC_DNS

That's it! Now you have a remote server on the cloud!

而已! 现在,您在云上有了一个远程服务器!

使用Boto3 Python库启动EC2实例 (Spin up an EC2 Instance with the Boto3 Python Library)

Full disclaimer here. This is well beyond what I would normally do with the boto3 library. For anything beyond launching an EC2 instance I would recommend using the console or using an infrastructure as code tool such as Cloudformation or Terraform. But when you are starting out it is really important to understand the foundations.

此处有完整的免责声明。 这远远超出了我通常使用boto3库所做的工作。 除了启动EC2实例外,我建议使用控制台或将基础结构用作代码工具,例如CloudformationTerraform 。 但是,当您开始时,了解基础确实很重要。

I also have an obsessive need to write out reports for absolutely everything. Feel free to remove if you're not as paranoid. ;-)

我还迫切需要为所有内容写出报告。 如果您不是偏执狂,请随时删除。 ;-)

import boto3
import time
import json
from pprint import pprint
from select import select
import logging
from logging import Logger
from paramiko import SSHClient
import paramiko
from typing import Any
import os

logger = logging.getLogger('launch_ec2')
logger.setLevel(logging.DEBUG)

PROJECT = "my-remote-server"
KEY_PAIR = "my-remote-server"
SECURITY_GROUP="sg-some-number"
# Amazon Linux 2 AMI
AMI_ID="ami-062f7200baf2fa504"
INSTANCE_TYPE="t3a.medium"

report_data = {
    'name': PROJECT,
    'computer_name': KEY_PAIR,
}

def initialize_dir():
	"""
    Initialize a directory to write out our keypair and reports
    """
    if not os.path.exists(KEY_PAIR):
        os.mkdir(KEY_PAIR)


def create_key_pair():
    ec2_client = boto3.client('ec2')
    key_pair_response = ec2_client.create_key_pair(KeyName=KEY_PAIR)
    report_data['ssh_key'] = {}
    report_data['ssh_key']['id'] = key_pair_response['KeyPairId']
    report_data['ssh_key']['name'] = key_pair_response['KeyName']
    report_data['ssh_key']['key'] = key_pair_response['KeyMaterial']
    report_data['ssh_key']['key_file'] = os.path.abspath(os.path.join(KEY_PAIR, 'keypair.pem'))
    logger.info('Successfully created ssh key')


def write_key_file():
    """
    Write out the .pem ssh key file
    :return:
    """
    f = open(os.path.join(KEY_PAIR, 'keypair.pem'), 'w+')
    f.write(report_data['ssh_key']['key'])
    f.close()
    os.chmod(os.path.join(KEY_PAIR, 'keypair.pem'), 0o400)
    logger.info(
        'Wrote out ssh key file to {keypair}'.format(
            keypair=
            os.path.abspath(os.path.join(KEY_PAIR, 'keypair.pem'))
        )
    )


def create_instance():
    ec2 = boto3.resource('ec2')
    instance = ec2.create_instances(
        SecurityGroupIds=[SECURITY_GROUP],
        ImageId=AMI_ID,
        MinCount=1,
        MaxCount=1,
        InstanceType=INSTANCE_TYPE,
        KeyName=KEY_PAIR,
        TagSpecifications=[
            {
                'ResourceType': 'instance',
                'Tags': [
                    {
                        'Key': 'Name',
                        'Value': PROJECT
                    },
                ]
            },
        ],
    )
    report_data['ec2'] = {}
    report_data['ec2']['id'] = instance[0].id
    report_data['ec2']['PublicIP'] = None


def get_public_ip():
    print('Waiting for instance to initialize with public IP address...')
    print('This may take some time...')
    time.sleep(10)
    ec2 = boto3.resource('ec2')
    running_instances = ec2.instances.filter(Filters=[
        {
            'Name': 'instance-state-name',
            'Values': ['running']
        },
        {
            'Name': 'instance-id',
            'Values': [report_data['ec2']['id']]
        }
    ])
    for instance in running_instances:
        # Add instance info to a dictionary
        report_data['ec2'] = {
            'instance_id': report_data['ec2']['id'],
            'Type': instance.instance_type,
            'State': instance.state['Name'],
            'PrivateIP': instance.private_ip_address,
            'PublicIP': instance.public_ip_address,
            'LaunchTime': str(instance.launch_time)
        }


def write_report():
	"""
    Write out a JSON file with all of the IDs and things we need
    """
    logger.info('Writing report to {}'.format(
        os.path.abspath(os.path.join(KEY_PAIR, 'report.json'))
    ))
    f = open(os.path.abspath(os.path.join(KEY_PAIR, 'report.json'))
             , 'w+')
    json.dump(report_data, f, ensure_ascii=False, indent=4)
    f.close()


def print_helper_commands():
    """
    Print some helper commands for ssh and rsync to the screen
    """
    rsync_command = "rsync -av --progress -e 'ssh -i {key_file}' HOST_DIR ec2-user@{public_id}:/home/ec2-user/efs".format(
        key_file=report_data['ssh_key']['key_file'],
        public_id=report_data['ec2']['PublicIP']
    )
    ssh_command = "ssh -i {key_file} ec2-user@{public_ip}".format(
        key_file=report_data['ssh_key']['key_file'],
        public_ip=report_data['ec2']['PublicIP']
    )
    report_data['ssh_command'] = ssh_command
    report_data['rsync_command'] = rsync_command
    print('Some helpful commands!')
    print('###################################')
    print('# SSH to the instance with: ')
    print(ssh_command)
    print('###################################')

    print('###################################')
    print('# Rsync data to the instance with: ')
    print(rsync_command)
    print('###################################')


def print_end_message():
    print('##################################')
    print('Finished!')
    print('See {dir}/report.json for details'.format(dir=KEY_PAIR))


initialize_dir()
create_key_pair()
write_key_file()
create_instance()
while report_data['ec2']['PublicIP'] is None:
    get_public_ip()
print_helper_commands()
write_report()
print_end_message()

结语 (WrapUp)

That's all you need to know to get started with spinning up remote servers in the cloud! What kinds of projects do you want to deploy to the cloud?

这就是开始在云中扩展远程服务器所需的一切! 您想将哪些项目部署到云?

翻译自: https://www.freecodecamp.org/news/getting-started-with-server-administration-on-aws/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值