SFTP 서버에 사용자 추가

이 문서에서는 Cloud FTP 서버에 사용자를 추가하는 방법을 보여줍니다. 외부 파트너 및 내부 이해관계자와 같은 사용자는 서버를 사용하여 Cloud Storage로 파일을 안전하게 전송할 수 있습니다.

SFTP 서버에 사용자를 추가하는 단계는 다음과 같습니다.

  1. 사용자 권한을 구성합니다.
  2. SFTP 사용자를 만들고 해당 디렉터리를 Cloud Storage 버킷에 매핑합니다.

서버를 만드는 단계는 외부 SFTP 서버 만들기 및 내부 SFTP 서버 만들기를 참조하세요.

고려사항

  • 사용자에게 최대 10개의 버킷에 대한 액세스 권한을 부여할 수 있습니다.

  • 사용자는 최대 10개의 공개 키를 가질 수 있습니다.

시작하기 전에

  1. 버킷이 아직 없는 경우 사용자가 작업할 데이터를 저장할 하나 이상의 Cloud Storage 버킷을 만듭니다.

  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를 설치합니다. 설치 후 다음 명령어를 실행하여 Google Cloud CLI를 초기화합니다.

    gcloud init

    외부 ID 공급업체(IdP)를 사용하는 경우 먼저 제휴 ID로 gcloud CLI에 로그인해야 합니다.

  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.iam.gserviceaccount.com \
          --member="user:ADMINISTRATOR_EMAIL" \
          --role="roles/iam.serviceAccountUser"

      ADMINISTRATOR_EMAIL을 SFTP 사용자를 만드는 주체의 이메일 주소로 바꿉니다. 애플리케이션이 아닌 사용자를 만드는 경우 이 값은 Google Cloud에 액세스하는 데 사용하는 이메일 주소입니다.

      성공하면 다음과 같은 메시지가 표시됩니다.

      Updated IAM policy for serviceAccount [example-userid-sa@example-project.iam.gserviceaccount.com].
      bindings:
      - members:
      - user:admin@example.com
      role: roles/iam.serviceAccountUser
      etag: BwZJk7OiSzw=
      version: 1
      
    2. 버킷에 대한 스토리지 버킷 뷰어 (roles/storage.bucketViewer) 역할을 자신에게 부여합니다.

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

      BUCKET_NAME을 버킷 이름으로 바꿉니다.

      사용자가 액세스해야 하는 각 버킷에 대해 이 단계를 반복합니다.

    3. 버킷에 대한 스토리지 객체 뷰어 (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.iam.gserviceaccount.com" \
        --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.iam.gserviceaccount.com \
          --member="serviceAccount:SERVICE_AGENT_EMAIL" \
          --role="roles/iam.serviceAccountTokenCreator"

      SERVICE_AGENT_EMAIL을 서비스 에이전트의 이메일 주소로 바꿉니다.

그런 다음 사용자를 만듭니다.

SFTP 서버 사용자 만들기

사용자 권한을 구성한 후 사용자를 만들고 해당 디렉터리를 하나 이상의 Cloud Storage 버킷에 매핑합니다.

gcloud

  1. SFTP 서버의 사용자를 만들려면 gcloud alpha storage ftp users create 명령어를 실행합니다.

    아래의 명령어 데이터를 사용하기 전에 다음을 바꿉니다.

    • CREDENTIAL_NAME: 사용자 인증 정보를 식별하는 고유한 이름입니다.
    • SSH_PUBLIC_KEY: OpenSSH 형식의 사용자 SSH 공개 키 본문입니다. 예를 들면 ssh-rsa AAAAB3NzaC1ycRexample...입니다.
    • USERNAME: SFTP 사용자의 사용자 이름입니다.
    • SERVICE_ACCOUNT: 사용자의 서비스 계정입니다. 예를 들면 username-sa@example-project.iam.gserviceaccount.com입니다.
    • 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.iam.gserviceaccount.com입니다.
    • CREDENTIAL_NAME: 사용자 인증 정보를 식별하는 고유한 이름입니다.
    • SSH_PUBLIC_KEY: OpenSSH 형식의 사용자 SSH 공개 키 본문입니다. 예를 들면 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

다음 단계