SFTP サーバーにユーザーを追加する

このドキュメントでは、Cloud FTP サーバーにユーザーを追加する方法について説明します。外部パートナーや内部関係者などのユーザーは、サーバーを使用して Cloud Storage との間でファイルを安全に転送できます。

SFTP サーバーにユーザーを追加する手順の概要は次のとおりです。

  1. ユーザーの権限を構成します。
  2. SFTP ユーザーを作成し、そのディレクトリを Cloud Storage バケットにマッピングします。

サーバーを作成する手順については、外部 SFTP サーバーを作成すると内部 SFTP サーバーを作成するをご覧ください。

考慮事項

  • ユーザーに最大 10 個のバケットへのアクセス権を付与できます。

  • ユーザーは最大 10 個の公開鍵を持つことができます。

始める前に

  1. ユーザーが操作するデータを保存する Cloud Storage バケットを 1 つ以上作成します(バケットがまだ存在しない場合)。

  2. サーバーへの接続に使用する各 SSH 認証鍵ペアからユーザーの公開鍵を取得します。

    SSH 認証鍵ペアがない場合は、次の手順で生成します。

    SSH 認証鍵ペアを生成する

    必要な鍵の形式を選択してください。

    必要な鍵の形式は、SFTP サーバーへの接続に使用するクライアントによって異なります。詳細については、サポートされている SFTP クライアントをご覧ください。

    PEM 形式

    1. OpenSSH 鍵ペア(PEM 形式)を作成するには、ssh-keygen ユーティリティを使用します。

      SFTP サーバーに接続するクライアント マシンで、次のコマンドを実行します。

      ssh-keygen -t rsa -b 4096 -f ~/.ssh/KEY_PAIR_NAME

      KEY_PAIR_NAME は、sftp_user_key などの鍵ペアの名前に置き換えます。

    2. 公開鍵を抽出します。

      cat ~/.ssh/KEY_PAIR_NAME.pub

    PPK 形式

    1. PuTTY 鍵ペア(PPK 形式)を作成するには、PuTTYgen ツールを使用します。

      SFTP サーバーに接続するクライアント マシンで、次のコマンドを実行します。

      puttygen -t rsa -b 4096 -o KEY_PAIR_NAME.ppk

      KEY_PAIR_NAME は、鍵ペアの名前(sftp_user_key など)に置き換えます。

    2. 公開鍵を抽出します。

      puttygen -L KEY_PAIR_NAME.ppk

必要なロール

SFTP ユーザーを追加するために必要な権限を取得するには、プロジェクトに対する FTP 管理者 (roles/ftp.admin)IAM ロールを付与するよう管理者に依頼してください。ロールの付与については、プロジェクト、フォルダ、組織に対するアクセス権の管理をご覧ください。

この事前定義ロールには、SFTP ユーザーを追加するために必要な ftp.users.create 権限が含まれています。

カスタムロールや他の事前定義ロールを使用して、この権限を取得することもできます。

ユーザーの権限を構成する

  1. Google Cloud CLI をインストールし、 フェデレーション ID を使用して gcloud CLI にログインします。ログイン後、次のコマンドを実行して Google Cloud CLI を初期化します。

    gcloud init
  2. プロジェクトを設定します。

    gcloud config set project PROJECT_ID

    PROJECT_ID は、SFTP サーバーを含むプロジェクトの ID に置き換えます。

  3. サービス アカウントがまだ存在しない場合は、ユーザーのサービス アカウントを作成します。サービス アカウントは、ユーザーに代わって Cloud Storage リソースにアクセスします。

    gcloud iam service-accounts create USERNAME-sa \
        --description="USERNAME SFTP Service Account" \
        --display-name="USERNAME SFTP Service Account"

    USERNAME は、SFTP ユーザーの一意のユーザー名に置き換えます。ユーザー名の先頭は英小文字にする必要があります。英小文字、数字、ハイフンを使用できます。最大長は 32 文字です。

    成功すると、Created service account [example-userid-sa] のようなメッセージが表示されます。

  4. SFTP ユーザーを作成する管理者に IAM ロールを付与します。

    1. サービス アカウント ユーザー(roles/iam.serviceAccountUser)ロールを自分に付与します。

      gcloud iam service-accounts add-iam-policy-binding USERNAME-sa@PROJECT_ID. \
          --member="user:ADMINISTRATOR_EMAIL" \
          --role="roles/iam.serviceAccountUser"

      ADMINISTRATOR_EMAIL は、SFTP ユーザーを作成するプリンシパルのメールアドレスに置き換えます。ユーザー(アプリケーションではなく)を作成する場合は、この値は Google Cloudへのアクセスに使用するメールアドレスです。

      成功すると、次のようなメッセージが表示されます。

      Updated IAM policy for serviceAccount [example-userid-sa@example-project.].
      bindings:
      - members:
      - user:admin@example.com
      role: roles/iam.serviceAccountUser
      etag: BwZJk7OiSzw=
      version: 1
      
    2. バケットに対する Storage バケット閲覧者(roles/storage.bucketViewer)ロールを自分に付与します。

      gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \
          --member="user:ADMINISTRATOR_EMAIL" \
          --role="roles/storage.bucketViewer"

      BUCKET_NAME は、バケットの名前に置き換えます。

      ユーザーがアクセスする必要があるバケットごとに、この手順を繰り返します。

    3. バケットに対する Storage オブジェクト閲覧者(roles/storage.objectViewer)ロールを自分に付与します。

      gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \
          --member="user:ADMINISTRATOR_EMAIL" \
          --role="roles/storage.objectViewer"

      ユーザーがアクセスする必要があるバケットごとに、この手順を繰り返します。

  5. バケットへのアクセスに必要な IAM ロールをユーザーのサービス アカウントに付与します。

    gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \
        --member="serviceAccount:USERNAME-sa@PROJECT_ID." \
        --role="ROLE"

    ROLE は、次のいずれかの IAM ロールに置き換えます。

    • 読み取り専用アクセス権の場合は、roles/storage.objectViewer ロールを使用します。
    • 読み取り / 書き込みアクセス権を付与するには、roles/storage.objectAdmin ロールを使用します。

    ユーザーがアクセスする必要があるバケットごとに、この手順を繰り返します。

  6. ユーザーのサービス アカウントのトークンを生成する権限を Cloud FTP サービス エージェントに付与します。

    1. サーバーのサービス エージェントのメールアドレスを取得します。手順については、サーバーの詳細を取得するをご覧ください。

    2. Cloud FTP サービス エージェントを承認します。

      gcloud iam service-accounts add-iam-policy-binding USERNAME-sa@PROJECT_ID. \
          --member="serviceAccount:SERVICE_AGENT_EMAIL" \
          --role="roles/iam.serviceAccountTokenCreator"

      SERVICE_AGENT_EMAIL は、サービス エージェントのメールアドレスに置き換えます。

次に、ユーザーを作成します。

SFTP サーバー ユーザーを作成する

ユーザーの権限を構成したら、ユーザーを作成し、そのディレクトリを 1 つ以上の Cloud Storage バケットにマッピングします。

gcloud

  1. SFTP サーバーのユーザーを作成するには、gcloud alpha storage ftp users create コマンドを実行します。

    後述のコマンドデータを使用する前に、次のように置き換えます。

    • CREDENTIAL_NAME: ユーザー認証情報を識別する一意の名前。
    • SSH_PUBLIC_KEY: ユーザーの SSH 公開鍵の本文(OpenSSH 形式)。例: ssh-rsa AAAAB3NzaC1ycRexample...
    • USERNAME: SFTP ユーザーのユーザー名。
    • SERVICE_ACCOUNT: ユーザーのサービス アカウント。例: username-sa@example-project.
    • LOCATION_ID: サーバーのロケーション(us-west1 など)。
    • SERVER_ID: サーバー ID。
    • BUCKET_NAME: SFTP ユーザーにアクセス権が付与されているバケットの名前(example-bucket など)。gs:// を省略します。
    • (省略可)BUCKET_PREFIX: このディレクトリ マッピングのルート ディレクトリとして設定するバケット内のフォルダのパス。bucket_prefix プロパティを省略すると、Cloud FTP はバケットルートを使用します。
    • DIRECTORY: SFTP ユーザーに表示される論理ランディング ディレクトリのパス。例: /home/uploads。

      複数のバケットまたはフォルダをマッピングする場合は、マッピングごとに一意のディレクトリ パスを指定します。

      ネストされた論理ディレクトリはサポートされていません。ディレクトリに複数のマッピングを指定する場合は、ネストされた構造ではなく、フラットな構造でディレクトリを指定します。たとえば、/dir1 と /dir1/dir2 ではなく /dir1 と /dir2 を使用します。

    • SFTP_PERMISSION: ディレクトリのアクセスレベル。読み取り専用権限の場合は、この値を READ_ONLY に設定します。読み取り / 書き込みアクセス権の場合は、この値を READ_WRITE に設定します。

    次の点にご注意ください。

    • ユーザーに複数のバケットへのアクセス権を付与するには、--storage-directory-mapping フラグを複数回指定し、各バケットのディレクトリ マッピングを指定します。
    • ユーザーに複数の公開鍵を構成するには、credentials.json ファイルに複数の認証情報を指定します。

    次の内容を credentials.json という名前のファイルに保存します。

    [
      {
        "credentialName": "CREDENTIAL_NAME",
        "credentialType": "PUBLIC_KEY",
        "sshPublicKeyBody": "SSH_PUBLIC_KEY"
      }
    ]

    次のコマンドを実行します。

    Linux、macOS、Cloud Shell

    gcloud alpha storage ftp users create USERNAME \
        --customer-service-account=SERVICE_ACCOUNT --location=LOCATION_ID \
        --server=SERVER_ID \
        --storage-directory-mapping=bucket=BUCKET_NAME,bucket_prefix=BUCKET_PREFIX,directory=DIRECTORY,permission=SFTP_PERMISSION \
        --user-credentials-from-file=credentials.json

    Windows(PowerShell)

    gcloud alpha storage ftp users create USERNAME `
        --customer-service-account=SERVICE_ACCOUNT --location=LOCATION_ID `
        --server=SERVER_ID `
        --storage-directory-mapping=bucket=BUCKET_NAME,bucket_prefix=BUCKET_PREFIX,directory=DIRECTORY,permission=SFTP_PERMISSION `
        --user-credentials-from-file=credentials.json

    Windows(cmd.exe)

    gcloud alpha storage ftp users create USERNAME ^
        --customer-service-account=SERVICE_ACCOUNT --location=LOCATION_ID ^
        --server=SERVER_ID ^
        --storage-directory-mapping=bucket=BUCKET_NAME,bucket_prefix=BUCKET_PREFIX,directory=DIRECTORY,permission=SFTP_PERMISSION ^
        --user-credentials-from-file=credentials.json
    ユーザーの作成には数秒かかります。

  2. サーバーに接続するために必要な次の情報をユーザーに提供します。

    • ユーザーの SFTP ユーザー名。

    • サーバーのアクセス構成。サーバーの種類によって異なります。

      • 外部サーバーの場合は、サーバーの IP アドレス。

      • 内部サーバーの場合、サーバーのサービス アタッチメントの URI。

      サーバーのアクセス構成を取得する手順については、サーバーの詳細を取得するをご覧ください。

    • (省略可)サーバーの鍵のフィンガープリント。

REST

  1. SFTP サーバーのユーザーを作成するには、servers.users.create メソッドを使用します。

    リクエストのデータを使用する前に、次のように置き換えます。

    • PROJECT_ID: サーバーの Google Cloud プロジェクト ID。
    • LOCATION_ID: サーバーのロケーション(us-west1 など)。
    • SERVER_ID: サーバー ID。
    • USERNAME: SFTP ユーザーのユーザー名。
    • BUCKET_NAME: SFTP ユーザーにアクセス権が付与されているバケットの名前(example-bucket など)。gs:// を省略します。
    • (省略可)BUCKET_PREFIX: このディレクトリ マッピングのルート ディレクトリとして設定するバケット内のフォルダのパス。この値を省略すると、Cloud FTP はバケットのルートを使用します。
    • DIRECTORY: SFTP ユーザーに表示される論理ランディング ディレクトリのパス。例: /home/uploads。この値を省略すると、Cloud FTP はランディング ディレクトリを / に設定します。

      複数のバケットまたはフォルダをマッピングする場合は、マッピングごとに一意のディレクトリ パスを指定します。

      ネストされた論理ディレクトリはサポートされていません。ディレクトリに複数のマッピングを指定する場合は、ネストされた構造ではなく、フラットな構造でディレクトリを指定します。たとえば、/dir1 と /dir1/dir2 ではなく /dir1 と /dir2 を使用します。

    • SFTP_PERMISSION: ディレクトリのアクセスレベル。読み取り専用アクセスの場合は、この値を READ_ONLY に設定します。読み取り / 書き込みアクセス権の場合は、この値を READ_WRITE に設定します。
    • SERVICE_ACCOUNT: ユーザーのサービス アカウント。例: username-sa@example-project.
    • CREDENTIAL_NAME: ユーザー認証情報を識別する一意の名前。
    • SSH_PUBLIC_KEY: ユーザーの SSH 公開鍵の本文(OpenSSH 形式)。例: ssh-rsa AAAAB3NzaC1ycRexample...

    次の点にご注意ください。

    • 複数のバケットへのアクセス権をユーザーに付与するには、storageDirectoryMappings リストに複数のバケット マッピングを指定します。
    • ユーザーに複数の公開鍵を構成するには、userCredentials リストに複数の認証情報を指定します。

    HTTP メソッドと URL:

    POST https://ftp.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/servers/SERVER_ID/users?userId=USERNAME

    リクエストの本文(JSON):

    {
      "storageDirectoryMappings": [
        {
          "bucket": "BUCKET_NAME",
          "bucketPrefix": "BUCKET_PREFIX",
          "directory": "DIRECTORY",
          "permission": "SFTP_PERMISSION"
        }
      ],
      "customerServiceAccount": "SERVICE_ACCOUNT",
      "userCredentials": [
        {
          "credentialName": "CREDENTIAL_NAME",
          "credentialType": "PUBLIC_KEY",
          "sshPublicKeyBody": "SSH_PUBLIC_KEY"
        }
      ]
    }
    

    リクエストを送信するには、次のいずれかのオプションを展開します。

    レスポンスで長時間実行オペレーションを識別できます。ユーザーの作成には数秒かかります。

  2. サーバーへの接続に必要な次の情報をユーザーに提供します。

    • ユーザーの SFTP ユーザー名。

    • サーバーのアクセス構成。サーバーの種類によって異なります。

      • 外部サーバーの場合は、サーバーの IP アドレス。

      • 内部サーバーの場合、サーバーのサービス アタッチメントの URI。

      サーバーのアクセス構成を取得する手順については、サーバーの詳細を取得するをご覧ください。

    • (省略可)サーバーの鍵のフィンガープリント。

クライアント ライブラリ

C#

Cloud FTP 用のクライアント ライブラリをインストールして使用する方法については、Cloud FTP クライアント ライブラリをご覧ください。詳細については、Cloud FTP C# API リファレンス ドキュメントをご覧ください。

Cloud FTP に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

using Google.Cloud.Ftp.V1;
using Google.LongRunning;
using System.Threading.Tasks;

public sealed partial class GeneratedCloudFtpClientSnippets
{
    /// <summary>Snippet for CreateUserAsync</summary>
    /// <remarks>
    /// This snippet has been automatically generated and should be regarded as a code template only.
    /// It will require modifications to work:
    /// - It may require correct/in-range values for request initialization.
    /// - It may require specifying regional endpoints when creating the service client as shown in
    ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
    /// </remarks>
    public async Task CreateUserAsync()
    {
        // Create client
        CloudFtpClient cloudFtpClient = await CloudFtpClient.CreateAsync();
        // Initialize request argument(s)
        string parent = "projects/[PROJECT]/locations/[LOCATION]/servers/[SERVER]";
        User user = new User();
        string userId = "";
        // Make the request
        Operation<User, OperationMetadata> response = await cloudFtpClient.CreateUserAsync(parent, user, userId);

        // Poll until the returned long-running operation is complete
        Operation<User, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
        // Retrieve the operation result
        User result = completedResponse.Result;

        // Or get the name of the operation
        string operationName = response.Name;
        // This name can be stored, then the long-running operation retrieved later by name
        Operation<User, OperationMetadata> retrievedResponse = await cloudFtpClient.PollOnceCreateUserAsync(operationName);
        // Check if the retrieved long-running operation has completed
        if (retrievedResponse.IsCompleted)
        {
            // If it has completed, then access the result
            User retrievedResult = retrievedResponse.Result;
        }
    }
}

Go

Cloud FTP 用のクライアント ライブラリをインストールして使用する方法については、Cloud FTP クライアント ライブラリをご覧ください。 詳細については、Cloud FTP Go API リファレンス ドキュメントをご覧ください。

Cloud FTP に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


//go:build examples

package main

import (
	"context"

	ftp "cloud.google.com/go/ftp/apiv1"
	ftppb "cloud.google.com/go/ftp/apiv1/ftppb"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := ftp.NewCloudFtpRESTClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &ftppb.CreateUserRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/ftp/apiv1/ftppb#CreateUserRequest.
	}
	op, err := c.CreateUser(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}

	resp, err := op.Wait(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

Java

Cloud FTP 用のクライアント ライブラリをインストールして使用する方法については、Cloud FTP クライアント ライブラリをご覧ください。 詳細については、Cloud FTP Java API リファレンス ドキュメントをご覧ください。

Cloud FTP に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

import com.google.api.core.ApiFuture;
import com.google.cloud.ftp.v1.CloudFtpClient;
import com.google.cloud.ftp.v1.CreateUserRequest;
import com.google.cloud.ftp.v1.ServerName;
import com.google.cloud.ftp.v1.User;
import com.google.longrunning.Operation;

public class AsyncCreateUser {

  public static void main(String[] args) throws Exception {
    asyncCreateUser();
  }

  public static void asyncCreateUser() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (CloudFtpClient cloudFtpClient = CloudFtpClient.create()) {
      CreateUserRequest request =
          CreateUserRequest.newBuilder()
              .setParent(ServerName.of("[PROJECT]", "[LOCATION]", "[SERVER]").toString())
              .setUserId("userId-836030906")
              .setUser(User.newBuilder().build())
              .setRequestId("requestId693933066")
              .build();
      ApiFuture<Operation> future = cloudFtpClient.createUserCallable().futureCall(request);
      // Do something.
      Operation response = future.get();
    }
  }
}

Node.js

Cloud FTP 用のクライアント ライブラリをインストールして使用する方法については、Cloud FTP クライアント ライブラリをご覧ください。詳細については、Cloud FTP Node.js API リファレンス ドキュメントをご覧ください。

Cloud FTP に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

/**
 * This snippet has been automatically generated and should be regarded as a code template only.
 * It will require modifications to work.
 * It may require correct/in-range values for request initialization.
 * TODO(developer): Uncomment these variables before running the sample.
 */
/**
 *  Required. Value for parent.
 */
// const parent = 'abc123'
/**
 *  Required. A unique user ID for the SFTP user. The user ID must start with a
 *  lowercase letter and can include lowercase letters, numbers, or hyphens.
 */
// const userId = 'abc123'
/**
 *  Required. The resource being created
 */
// const user = {}
/**
 *  Optional. An optional request ID to identify requests. Specify a unique
 *  request ID so that if you must retry your request, the server will know to
 *  ignore the request if it has already been completed. The server will
 *  guarantee that for at least 60 minutes since the first request.
 *  For example, consider a situation where you make an initial request and the
 *  request times out. If you make the request again with the same request
 *  ID, the server can check if original operation with the same request ID
 *  was received, and if so, will ignore the second request. This prevents
 *  clients from accidentally creating duplicate commitments.
 *  The request ID must be a valid UUID with the exception that zero UUID is
 *  not supported (00000000-0000-0000-0000-000000000000).
 */
// const requestId = 'abc123'

// Imports the Ftp library
const {CloudFtpClient} = require('@google-cloud/ftp').v1;

// Instantiates a client
const ftpClient = new CloudFtpClient();

async function callCreateUser() {
  // Construct request
  const request = {
    parent,
    userId,
    user,
  };

  // Run request
  const [operation] = await ftpClient.createUser(request);
  const [response] = await operation.promise();
  console.log(response);
}

callCreateUser();

PHP

Cloud FTP 用のクライアント ライブラリをインストールして使用する方法については、Cloud FTP クライアント ライブラリをご覧ください。詳細については、Cloud FTP PHP API リファレンス ドキュメントをご覧ください。

Cloud FTP に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

use Google\ApiCore\ApiException;
use Google\ApiCore\OperationResponse;
use Google\Cloud\Ftp\V1\Client\CloudFtpClient;
use Google\Cloud\Ftp\V1\CreateUserRequest;
use Google\Cloud\Ftp\V1\StorageDirectoryMapping;
use Google\Cloud\Ftp\V1\StorageDirectoryMapping\Permission;
use Google\Cloud\Ftp\V1\User;
use Google\Cloud\Ftp\V1\UserCredential;
use Google\Cloud\Ftp\V1\UserCredential\Type;
use Google\Rpc\Status;

/**
 * Creates a new User in a given project and location and Server.
 *
 * @param string $formattedParent                        Value for parent. Please see
 *                                                       {@see CloudFtpClient::serverName()} for help formatting this field.
 * @param string $userId                                 A unique user ID for the SFTP user. The user ID must start with a
 *                                                       lowercase letter and can include lowercase letters, numbers, or hyphens.
 * @param string $userCustomerServiceAccount             Service account in customer project attached to this SFTP User.
 * @param string $userUserCredentialsCredentialName      Name of the user credential.
 * @param int    $userUserCredentialsCredentialType      Type of credential.
 * @param string $userStorageDirectoryMappingsBucket     Name of the bucket.
 * @param string $userStorageDirectoryMappingsDirectory  Directory where the user lands in the SFTP server.
 * @param int    $userStorageDirectoryMappingsPermission Permission to the bucket.
 */
function create_user_sample(
    string $formattedParent,
    string $userId,
    string $userCustomerServiceAccount,
    string $userUserCredentialsCredentialName,
    int $userUserCredentialsCredentialType,
    string $userStorageDirectoryMappingsBucket,
    string $userStorageDirectoryMappingsDirectory,
    int $userStorageDirectoryMappingsPermission
): void {
    // Create a client.
    $cloudFtpClient = new CloudFtpClient();

    // Prepare the request message.
    $userCredential = (new UserCredential())
        ->setCredentialName($userUserCredentialsCredentialName)
        ->setCredentialType($userUserCredentialsCredentialType);
    $userUserCredentials = [$userCredential];
    $storageDirectoryMapping = (new StorageDirectoryMapping())
        ->setBucket($userStorageDirectoryMappingsBucket)
        ->setDirectory($userStorageDirectoryMappingsDirectory)
        ->setPermission($userStorageDirectoryMappingsPermission);
    $userStorageDirectoryMappings = [$storageDirectoryMapping];
    $user = (new User())
        ->setCustomerServiceAccount($userCustomerServiceAccount)
        ->setUserCredentials($userUserCredentials)
        ->setStorageDirectoryMappings($userStorageDirectoryMappings);
    $request = (new CreateUserRequest())
        ->setParent($formattedParent)
        ->setUserId($userId)
        ->setUser($user);

    // Call the API and handle any network failures.
    try {
        /** @var OperationResponse $response */
        $response = $cloudFtpClient->createUser($request);
        $response->pollUntilComplete();

        if ($response->operationSucceeded()) {
            /** @var User $result */
            $result = $response->getResult();
            printf('Operation successful with response data: %s' . PHP_EOL, $result->serializeToJsonString());
        } else {
            /** @var Status $error */
            $error = $response->getError();
            printf('Operation failed with error data: %s' . PHP_EOL, $error->serializeToJsonString());
        }
    } catch (ApiException $ex) {
        printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
    }
}

/**
 * Helper to execute the sample.
 *
 * This sample has been automatically generated and should be regarded as a code
 * template only. It will require modifications to work:
 *  - It may require correct/in-range values for request initialization.
 *  - It may require specifying regional endpoints when creating the service client,
 *    please see the apiEndpoint client configuration option for more details.
 */
function callSample(): void
{
    $formattedParent = CloudFtpClient::serverName('[PROJECT]', '[LOCATION]', '[SERVER]');
    $userId = '[USER_ID]';
    $userCustomerServiceAccount = '[CUSTOMER_SERVICE_ACCOUNT]';
    $userUserCredentialsCredentialName = '[CREDENTIAL_NAME]';
    $userUserCredentialsCredentialType = Type::TYPE_UNSPECIFIED;
    $userStorageDirectoryMappingsBucket = '[BUCKET]';
    $userStorageDirectoryMappingsDirectory = '[DIRECTORY]';
    $userStorageDirectoryMappingsPermission = Permission::PERMISSION_UNSPECIFIED;

    create_user_sample(
        $formattedParent,
        $userId,
        $userCustomerServiceAccount,
        $userUserCredentialsCredentialName,
        $userUserCredentialsCredentialType,
        $userStorageDirectoryMappingsBucket,
        $userStorageDirectoryMappingsDirectory,
        $userStorageDirectoryMappingsPermission
    );
}

Python

Cloud FTP 用のクライアント ライブラリをインストールして使用する方法については、Cloud FTP クライアント ライブラリをご覧ください。詳細については、Cloud FTP Python API リファレンス ドキュメントをご覧ください。

Cloud FTP に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

# This snippet has been automatically generated and should be regarded as a
# code template only.
# It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
#   client as shown in:
#   https://googleapis.dev/python/google-api-core/latest/client_options.html
from google.cloud import ftp_v1


def sample_create_user():
    # Create a client
    client = ftp_v1.CloudFtpClient()

    # Initialize request argument(s)
    user = ftp_v1.User()
    user.customer_service_account = "customer_service_account_value"
    user.user_credentials.credential_name = "credential_name_value"
    user.user_credentials.credential_type = "PUBLIC_KEY"
    user.storage_directory_mappings.bucket = "bucket_value"
    user.storage_directory_mappings.directory = "directory_value"
    user.storage_directory_mappings.permission = "READ_WRITE"

    request = ftp_v1.CreateUserRequest(
        parent="parent_value",
        user_id="user_id_value",
        user=user,
    )

    # Make the request
    operation = client.create_user(request=request)

    print("Waiting for operation to complete...")

    response = operation.result()

    # Handle the response
    print(response)

Ruby

Cloud FTP 用のクライアント ライブラリをインストールして使用する方法については、Cloud FTP クライアント ライブラリをご覧ください。 詳細については、Cloud FTP Ruby API のリファレンス ドキュメントをご覧ください。

Cloud FTP に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

require "google/cloud/ftp/v1"

##
# Snippet for the create_user call in the CloudFtp service
#
# This snippet has been automatically generated and should be regarded as a code
# template only. It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in https://cloud.google.com/ruby/docs/reference.
#
# This is an auto-generated example demonstrating basic usage of
# Google::Cloud::Ftp::V1::CloudFtp::Rest::Client#create_user.
#
def create_user
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::Ftp::V1::CloudFtp::Rest::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::Ftp::V1::CreateUserRequest.new

  # Call the create_user method.
  result = client.create_user request

  # The returned object is of type Gapic::Operation. You can use it to
  # check the status of an operation, cancel it, or wait for results.
  # Here is how to wait for a response.
  result.wait_until_done! timeout: 60
  if result.response?
    p result.response
  else
    puts "No response received."
  end
end

次のステップ