

# 将 `UploadServerCertificate` 与 AWS SDK 或 CLI 配合使用
<a name="iam_example_iam_UploadServerCertificate_section"></a>

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

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

**AWS CLI**  
**将服务器证书上传到 AWS 账户**  
使用以下 **upload-server-certificate** 命令可将服务器证书上传到 AWS 账户。在此示例中，证书位于 `public_key_cert_file.pem` 文件中，关联的私有密钥位于 `my_private_key.pem` 文件中，而证书颁发机构（CA）提供的证书链位于 `my_certificate_chain_file.pem` 文件中。文件上传完成后，就位于 *myServerCertificate* 名称下。以 `file://` 开头的参数让命令读取文件的内容，将其用作参数值，而不是文件名本身。  

```
aws iam upload-server-certificate \
    --server-certificate-name myServerCertificate \
    --certificate-body file://public_key_cert_file.pem \
    --private-key file://my_private_key.pem \
    --certificate-chain file://my_certificate_chain_file.pem
```
输出：  

```
{
    "ServerCertificateMetadata": {
        "Path": "/",
        "ServerCertificateName": "myServerCertificate",
        "ServerCertificateId": "ASCAEXAMPLE123EXAMPLE",
        "Arn": "arn:aws:iam::1234567989012:server-certificate/myServerCertificate",
        "UploadDate": "2019-04-22T21:13:44+00:00",
        "Expiration": "2019-10-15T22:23:16+00:00"
    }
}
```
有关更多信息，请参阅《使用 IAM》指南**中的“创建、上传和删除服务器证书”。  
+  有关 API 详细信息，请参阅《AWS CLI 命令参考》**中的 [UploadServerCertificate](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/iam/upload-server-certificate.html)。

------
#### [ JavaScript ]

**SDK for JavaScript (v3)**  
 查看 GitHub，了解更多信息。在 [AWS 代码示例存储库](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/iam#code-examples)中查找完整示例，了解如何进行设置和运行。

```
import { UploadServerCertificateCommand, IAMClient } from "@aws-sdk/client-iam";
import { readFileSync } from "node:fs";
import { dirnameFromMetaUrl } from "@aws-doc-sdk-examples/lib/utils/util-fs.js";
import * as path from "node:path";

const client = new IAMClient({});

const certMessage = `Generate a certificate and key with the following command, or the equivalent for your system.

openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes \
-keyout example.key -out example.crt -subj "/CN=example.com" \
-addext "subjectAltName=DNS:example.com,DNS:www.example.net,IP:10.0.0.1"
`;

const getCertAndKey = () => {
  try {
    const cert = readFileSync(
      path.join(dirnameFromMetaUrl(import.meta.url), "./example.crt"),
    );
    const key = readFileSync(
      path.join(dirnameFromMetaUrl(import.meta.url), "./example.key"),
    );
    return { cert, key };
  } catch (err) {
    if (err.code === "ENOENT") {
      throw new Error(
        `Certificate and/or private key not found. ${certMessage}`,
      );
    }

    throw err;
  }
};

/**
 *
 * @param {string} certificateName
 */
export const uploadServerCertificate = (certificateName) => {
  const { cert, key } = getCertAndKey();
  const command = new UploadServerCertificateCommand({
    ServerCertificateName: certificateName,
    CertificateBody: cert.toString(),
    PrivateKey: key.toString(),
  });

  return client.send(command);
};
```
+  有关 API 详细信息，请参阅《适用于 JavaScript 的 AWS SDK API Reference》**中的 [UploadServerCertificate](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/client/iam/command/UploadServerCertificateCommand)。

------
#### [ PowerShell ]

**适用于 PowerShell V4 的工具**  
**示例 1：此示例将新服务器证书上传到 IAM 账户。包含证书正文、私有密钥和（可选）证书链的文件必须均采用 PEM 编码。请注意，参数需要文件的实际内容，而不是文件名。必须使用 `-Raw` 开关参数才能成功处理文件内容。**  

```
Publish-IAMServerCertificate -ServerCertificateName MyTestCert -CertificateBody (Get-Content -Raw server.crt) -PrivateKey (Get-Content -Raw server.key)
```
**输出**：  

```
Arn                   : arn:aws:iam::123456789012:server-certificate/MyTestCert
Expiration            : 1/14/2018 9:52:36 AM
Path                  : /
ServerCertificateId   : ASCAJIEXAMPLE7J7HQZYW
ServerCertificateName : MyTestCert
UploadDate            : 4/21/2015 11:14:16 AM
```
+  有关 API 详细信息，请参阅《AWS Tools for PowerShell Cmdlet Reference (V4)》**中的 [UploadServerCertificate](https://docs.aws.amazon.com/powershell/v4/reference)。

**Tools for PowerShell V5**  
**示例 1：此示例将新服务器证书上传到 IAM 账户。包含证书正文、私有密钥和（可选）证书链的文件必须均采用 PEM 编码。请注意，参数需要文件的实际内容，而不是文件名。必须使用 `-Raw` 开关参数才能成功处理文件内容。**  

```
Publish-IAMServerCertificate -ServerCertificateName MyTestCert -CertificateBody (Get-Content -Raw server.crt) -PrivateKey (Get-Content -Raw server.key)
```
**输出**：  

```
Arn                   : arn:aws:iam::123456789012:server-certificate/MyTestCert
Expiration            : 1/14/2018 9:52:36 AM
Path                  : /
ServerCertificateId   : ASCAJIEXAMPLE7J7HQZYW
ServerCertificateName : MyTestCert
UploadDate            : 4/21/2015 11:14:16 AM
```
+  有关 API 详细信息，请参阅《*AWS Tools for PowerShell Cmdlet 参考 (V5)*》中的 [UploadServerCertificate](https://docs.aws.amazon.com/powershell/v5/reference)。

------

有关 AWS SDK 开发人员指南和代码示例的完整列表，请参阅 [将此服务与 AWS SDK 结合使用](sdk-general-information-section.md) 本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。