

文档 AWS SDK 示例 GitHub 存储库中还有更多 [S AWS DK 示例](https://github.com/awsdocs/aws-doc-sdk-examples)。

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

# 使用 Elastic Beanstalk 的代码示例 AWS SDKs
<a name="elastic-beanstalk_code_examples"></a>

以下代码示例向您展示了如何 AWS Elastic Beanstalk 使用 AWS 软件开发套件 (SDK)。

*操作*是大型程序的代码摘录，必须在上下文中运行。您可以通过操作了解如何调用单个服务函数，还可以通过函数相关场景的上下文查看操作。

**更多资源**
+  **[Elastic Beanstalk 开发人员指南](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/Welcome.html)**：有关 Elastic Beanstalk 的更多信息。
+ **[Elastic Beanstalk API 参考](https://docs.aws.amazon.com/elasticbeanstalk/latest/api/Welcome.html)**：所有可用 Elastic Beanstalk 操作的详细信息。
+ **[AWS 开发者中心](https://aws.amazon.com/developer/code-examples/?awsf.sdk-code-examples-product=product%23)** — 您可以按类别或全文搜索筛选的代码示例。
+ **[AWS SDK 示例](https://github.com/awsdocs/aws-doc-sdk-examples)** — 包含首选语言完整代码的 GitHub 存储库。包括有关设置和运行代码的说明。

**Contents**
+ [基本功能](elastic-beanstalk_code_examples_basics.md)
  + [操作](elastic-beanstalk_code_examples_actions.md)
    + [`DescribeApplications`](elastic-beanstalk_example_elastic-beanstalk_DescribeApplications_section.md)
    + [`ListAvailableSolutionStacks`](elastic-beanstalk_example_elastic-beanstalk_ListAvailableSolutionStacks_section.md)
    + [`UpdateApplication`](elastic-beanstalk_example_elastic-beanstalk_UpdateApplication_section.md)

# 使用 Elastic Beanstalk 的基本示例 AWS SDKs
<a name="elastic-beanstalk_code_examples_basics"></a>

以下代码示例说明如何使用 with 的基础 AWS Elastic Beanstalk 知识 AWS SDKs。

**Contents**
+ [操作](elastic-beanstalk_code_examples_actions.md)
  + [`DescribeApplications`](elastic-beanstalk_example_elastic-beanstalk_DescribeApplications_section.md)
  + [`ListAvailableSolutionStacks`](elastic-beanstalk_example_elastic-beanstalk_ListAvailableSolutionStacks_section.md)
  + [`UpdateApplication`](elastic-beanstalk_example_elastic-beanstalk_UpdateApplication_section.md)

# 使用 Elastic Beanstalk 的操作 AWS SDKs
<a name="elastic-beanstalk_code_examples_actions"></a>

以下代码示例演示了如何使用执行单个 Elastic Beanstalk 操作。 AWS SDKs每个示例都包含一个指向的链接 GitHub，您可以在其中找到有关设置和运行代码的说明。

 以下示例仅包括最常用的操作。有关完整列表，请参阅 [AWS Elastic Beanstalk API 参考](https://docs.aws.amazon.com/elasticbeanstalk/latest/api/Welcome.html)。

**Topics**
+ [`DescribeApplications`](elastic-beanstalk_example_elastic-beanstalk_DescribeApplications_section.md)
+ [`ListAvailableSolutionStacks`](elastic-beanstalk_example_elastic-beanstalk_ListAvailableSolutionStacks_section.md)
+ [`UpdateApplication`](elastic-beanstalk_example_elastic-beanstalk_UpdateApplication_section.md)

# `DescribeApplications`与 AWS SDK 或 CLI 配合使用
<a name="elastic-beanstalk_example_elastic-beanstalk_DescribeApplications_section"></a>

以下代码示例演示如何使用 `DescribeApplications`。

------
#### [ CLI ]

**AWS CLI**  
**查看应用程序列表**  
以下命令检索有关当前区域中应用程序的信息：  

```
aws elasticbeanstalk describe-applications
```
输出：  

```
{
    "Applications": [
        {
            "ApplicationName": "ruby",
            "ConfigurationTemplates": [],
            "DateUpdated": "2015-08-13T21:05:44.376Z",
            "Versions": [
                "Sample Application"
            ],
            "DateCreated": "2015-08-13T21:05:44.376Z"
        },
        {
            "ApplicationName": "pythonsample",
            "Description": "Application created from the EB CLI using \"eb init\"",
            "Versions": [
                "Sample Application"
            ],
            "DateCreated": "2015-08-13T19:05:43.637Z",
            "ConfigurationTemplates": [],
            "DateUpdated": "2015-08-13T19:05:43.637Z"
        },
        {
            "ApplicationName": "nodejs-example",
            "ConfigurationTemplates": [],
            "DateUpdated": "2015-08-06T17:50:02.486Z",
            "Versions": [
                "add elasticache",
                "First Release"
            ],
            "DateCreated": "2015-08-06T17:50:02.486Z"
        }
    ]
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[DescribeApplications](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/describe-applications.html)*中的。

------
#### [ Ruby ]

**适用于 Ruby 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/elasticbeanstalk#code-examples)中查找完整示例，了解如何进行设置和运行。

```
# Class to manage Elastic Beanstalk applications
class ElasticBeanstalkManager
  def initialize(eb_client, logger: Logger.new($stdout))
    @eb_client = eb_client
    @logger = logger
  end

  # Lists applications and their environments
  def list_applications
    @eb_client.describe_applications.applications.each do |application|
      log_application_details(application)
      list_environments(application.application_name)
    end
  rescue Aws::ElasticBeanstalk::Errors::ServiceError => e
    @logger.error("Elastic Beanstalk Service Error: #{e.message}")
  end

  private

  # Logs application details
  def log_application_details(application)
    @logger.info("Name:        #{application.application_name}")
    @logger.info("Description: #{application.description}")
  end

  # Lists and logs details of environments for a given application
  def list_environments(application_name)
    @eb_client.describe_environments(application_name: application_name).environments.each do |env|
      @logger.info("  Environment:  #{env.environment_name}")
      @logger.info("    URL:        #{env.cname}")
      @logger.info("    Health:     #{env.health}")
    end
  rescue Aws::ElasticBeanstalk::Errors::ServiceError => e
    @logger.error("Error listing environments for application #{application_name}: #{e.message}")
  end
end
```
+  有关 API 的详细信息，请参阅 *适用于 Ruby 的 AWS SDK API 参考[DescribeApplications](https://docs.aws.amazon.com/goto/SdkForRubyV3/elastic-beanstalk-2010-12-01/DescribeApplications)*中的。

------

# `ListAvailableSolutionStacks`与 AWS SDK 或 CLI 配合使用
<a name="elastic-beanstalk_example_elastic-beanstalk_ListAvailableSolutionStacks_section"></a>

以下代码示例演示如何使用 `ListAvailableSolutionStacks`。

------
#### [ CLI ]

**AWS CLI**  
**查看解决方案堆栈**  
以下命令列出了所有当前可用平台配置以及您过去使用过的所有和任何平台配置的解决方案堆栈：  

```
aws elasticbeanstalk list-available-solution-stacks
```
输出（缩减）：  

```
{
    "SolutionStacks": [
        "64bit Amazon Linux 2015.03 v2.0.0 running Node.js",
        "64bit Amazon Linux 2015.03 v2.0.0 running PHP 5.6",
        "64bit Amazon Linux 2015.03 v2.0.0 running PHP 5.5",
        "64bit Amazon Linux 2015.03 v2.0.0 running PHP 5.4",
        "64bit Amazon Linux 2015.03 v2.0.0 running Python 3.4",
        "64bit Amazon Linux 2015.03 v2.0.0 running Python 2.7",
        "64bit Amazon Linux 2015.03 v2.0.0 running Python",
        "64bit Amazon Linux 2015.03 v2.0.0 running Ruby 2.2 (Puma)",
        "64bit Amazon Linux 2015.03 v2.0.0 running Ruby 2.2 (Passenger Standalone)",
        "64bit Amazon Linux 2015.03 v2.0.0 running Ruby 2.1 (Puma)",
        "64bit Amazon Linux 2015.03 v2.0.0 running Ruby 2.1 (Passenger Standalone)",
        "64bit Amazon Linux 2015.03 v2.0.0 running Ruby 2.0 (Puma)",
        "64bit Amazon Linux 2015.03 v2.0.0 running Ruby 2.0 (Passenger Standalone)",
        "64bit Amazon Linux 2015.03 v2.0.0 running Ruby 1.9.3",
        "64bit Amazon Linux 2015.03 v2.0.0 running Tomcat 8 Java 8",
        "64bit Amazon Linux 2015.03 v2.0.0 running Tomcat 7 Java 7",
        "64bit Amazon Linux 2015.03 v2.0.0 running Tomcat 7 Java 6",
        "64bit Windows Server Core 2012 R2 running IIS 8.5",
        "64bit Windows Server 2012 R2 running IIS 8.5",
        "64bit Windows Server 2012 running IIS 8",
        "64bit Windows Server 2008 R2 running IIS 7.5",
        "64bit Amazon Linux 2015.03 v2.0.0 running Docker 1.6.2",
        "64bit Amazon Linux 2015.03 v2.0.0 running Multi-container Docker 1.6.2 (Generic)",
        "64bit Debian jessie v2.0.0 running GlassFish 4.1 Java 8 (Preconfigured - Docker)",
        "64bit Debian jessie v2.0.0 running GlassFish 4.0 Java 7 (Preconfigured - Docker)",
        "64bit Debian jessie v2.0.0 running Go 1.4 (Preconfigured - Docker)",
        "64bit Debian jessie v2.0.0 running Go 1.3 (Preconfigured - Docker)",
        "64bit Debian jessie v2.0.0 running Python 3.4 (Preconfigured - Docker)",
    ],
    "SolutionStackDetails": [
        {
            "PermittedFileTypes": [
                "zip"
            ],
            "SolutionStackName": "64bit Amazon Linux 2015.03 v2.0.0 running Node.js"
        },
        ...
    ]
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[ListAvailableSolutionStacks](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/list-available-solution-stacks.html)*中的。

------
#### [ Ruby ]

**适用于 Ruby 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/elasticbeanstalk#code-examples)中查找完整示例，了解如何进行设置和运行。

```
# Manages listing of AWS Elastic Beanstalk solution stacks
# @param [Aws::ElasticBeanstalk::Client] eb_client
# @param [String] filter - Returns subset of results based on match
# @param [Logger] logger
class StackLister
  # Initialize with AWS Elastic Beanstalk client
  def initialize(eb_client, filter, logger: Logger.new($stdout))
    @eb_client = eb_client
    @filter = filter.downcase
    @logger = logger
  end

  # Lists and logs Elastic Beanstalk solution stacks
  def list_stacks
    stacks = @eb_client.list_available_solution_stacks.solution_stacks
    orig_length = stacks.length
    filtered_length = 0

    stacks.each do |stack|
      if @filter.empty? || stack.downcase.include?(@filter)
        @logger.info(stack)
        filtered_length += 1
      end
    end

    log_summary(filtered_length, orig_length)
  rescue Aws::Errors::ServiceError => e
    @logger.error("Error listing solution stacks: #{e.message}")
  end

  private

  # Logs summary of listed stacks
  def log_summary(filtered_length, orig_length)
    if @filter.empty?
      @logger.info("Showed #{orig_length} stack(s)")
    else
      @logger.info("Showed #{filtered_length} stack(s) of #{orig_length}")
    end
  end
end
```
+  有关 API 的详细信息，请参阅 *适用于 Ruby 的 AWS SDK API 参考[ListAvailableSolutionStacks](https://docs.aws.amazon.com/goto/SdkForRubyV3/elastic-beanstalk-2010-12-01/ListAvailableSolutionStacks)*中的。

------

# `UpdateApplication`与 AWS SDK 或 CLI 配合使用
<a name="elastic-beanstalk_example_elastic-beanstalk_UpdateApplication_section"></a>

以下代码示例演示如何使用 `UpdateApplication`。

------
#### [ CLI ]

**AWS CLI**  
**更改应用程序的描述**  
以下命令更新名为 `my-app` 的应用程序的描述：  

```
aws elasticbeanstalk update-application --application-name my-app --description "my Elastic Beanstalk application"
```
输出：  

```
{
    "Application": {
        "ApplicationName": "my-app",
        "Description": "my Elastic Beanstalk application",
        "Versions": [
            "2fba-stage-150819_234450",
            "bf07-stage-150820_214945",
            "93f8",
            "fd7c-stage-150820_000431",
            "22a0-stage-150819_185942"
        ],
        "DateCreated": "2015-08-13T19:15:50.449Z",
        "ConfigurationTemplates": [],
        "DateUpdated": "2015-08-20T22:34:56.195Z"
    }
}
```
+  有关 API 的详细信息，请参阅*AWS CLI 命令参考[UpdateApplication](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/elasticbeanstalk/update-application.html)*中的。

------
#### [ Ruby ]

**适用于 Ruby 的 SDK**  
 还有更多相关信息 GitHub。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/ruby/example_code/elasticbeanstalk#code-examples)中查找完整示例，了解如何进行设置和运行。

```
# Manages deployment of Rails applications to AWS Elastic Beanstalk
class RailsAppDeployer
  def initialize(eb_client, s3_client, app_name, logger: Logger.new($stdout))
    @eb_client = eb_client
    @s3_client = s3_client
    @app_name = app_name
    @logger = logger
  end

  # Deploys the latest application version to Elastic Beanstalk
  def deploy
    create_storage_location
    zip_file_name = create_zip_file
    upload_zip_to_s3(zip_file_name)
    create_and_deploy_new_application_version(zip_file_name)
  end

  private

  # Creates a new S3 storage location for the application
  def create_storage_location
    resp = @eb_client.create_storage_location
    @logger.info("Created storage location in bucket #{resp.s3_bucket}")
  rescue Aws::Errors::ServiceError => e
    @logger.error("Failed to create storage location: #{e.message}")
  end

  # Creates a ZIP file of the application using git
  def create_zip_file
    zip_file_basename = SecureRandom.urlsafe_base64
    zip_file_name = "#{zip_file_basename}.zip"
    `git archive --format=zip -o #{zip_file_name} HEAD`
    zip_file_name
  end

  # Uploads the ZIP file to the S3 bucket
  def upload_zip_to_s3(zip_file_name)
    zip_contents = File.read(zip_file_name)
    key = "#{@app_name}/#{zip_file_name}"
    @s3_client.put_object(body: zip_contents, bucket: fetch_bucket_name, key: key)
  rescue Aws::Errors::ServiceError => e
    @logger.error("Failed to upload ZIP file to S3: #{e.message}")
  end

  # Fetches the S3 bucket name from Elastic Beanstalk application versions
  def fetch_bucket_name
    app_versions = @eb_client.describe_application_versions(application_name: @app_name)
    av = app_versions.application_versions.first
    av.source_bundle.s3_bucket
  rescue Aws::Errors::ServiceError => e
    @logger.error("Failed to fetch bucket name: #{e.message}")
    raise
  end

  # Creates a new application version and deploys it
  def create_and_deploy_new_application_version(zip_file_name)
    version_label = File.basename(zip_file_name, '.zip')
    @eb_client.create_application_version(
      process: false,
      application_name: @app_name,
      version_label: version_label,
      source_bundle: {
        s3_bucket: fetch_bucket_name,
        s3_key: "#{@app_name}/#{zip_file_name}"
      },
      description: "Updated #{Time.now.strftime('%d/%m/%Y')}"
    )
    update_environment(version_label)
  rescue Aws::Errors::ServiceError => e
    @logger.error("Failed to create or deploy application version: #{e.message}")
  end

  # Updates the environment to the new application version
  def update_environment(version_label)
    env_name = fetch_environment_name
    @eb_client.update_environment(
      environment_name: env_name,
      version_label: version_label
    )
  rescue Aws::Errors::ServiceError => e
    @logger.error("Failed to update environment: #{e.message}")
  end

  # Fetches the environment name of the application
  def fetch_environment_name
    envs = @eb_client.describe_environments(application_name: @app_name)
    envs.environments.first.environment_name
  rescue Aws::Errors::ServiceError => e
    @logger.error("Failed to fetch environment name: #{e.message}")
    raise
  end
end
```
+  有关 API 的详细信息，请参阅 *适用于 Ruby 的 AWS SDK API 参考[UpdateApplication](https://docs.aws.amazon.com/goto/SdkForRubyV3/elastic-beanstalk-2010-12-01/UpdateApplication)*中的。

------