SFTP 사용자의 버킷 업데이트

이 문서에서는 Cloud FTP 사용자의 Cloud Storage 버킷을 업데이트하는 방법을 보여줍니다. 여기에는 사용자가 액세스할 수 있는 버킷과 사용자에게 부여된 권한이 포함됩니다.

사용자의 버킷을 업데이트하는 단계는 다음과 같습니다.

  1. 사용자 서비스 계정의 IAM 역할을 업데이트합니다.
  2. 사용자의 디렉터리를 업데이트된 버킷에 매핑합니다.

시작하기 전에

필요한 역할

SFTP 사용자를 업데이트하는 데 필요한 권한을 얻으려면 관리자에게 프로젝트에 대한FTP 관리자 (roles/ftp.admin) IAM 역할을 부여해 달라고 요청하세요. 역할 부여에 대한 자세한 내용은 프로젝트, 폴더, 조직에 대한 액세스 관리를 참조하세요.

이 사전 정의된 역할에는 SFTP 사용자를 업데이트하는 데 필요한 ftp.users.update 권한이 포함되어 있습니다.

커스텀 역할이나 다른 사전 정의된 역할을 사용하여 이 권한을 부여받을 수도 있습니다.

사용자 서비스 계정의 IAM 역할 업데이트

사용자가 액세스할 수 있는 버킷을 변경하거나 사용자가 기존 디렉터리 매핑에 대해 보유한 권한을 변경하는 경우 관련 IAM 역할로 사용자 서비스 계정을 업데이트해야 합니다. 다음 단계를 따르세요.

  1. 사용자 서비스 계정의 이메일 주소를 가져옵니다. 단계는 사용자 세부정보 가져오기를 참조하세요.

  2. 디렉터리 매핑에 새 버킷을 추가하거나 기존 버킷에 대한 액세스 권한을 늘리려면 다음 단계를 따르세요.

    1. 아직 역할이 없는 경우 버킷에 대한 스토리지 버킷 뷰어 (roles/storage.bucketViewer) 역할을 자신에게 부여합니다.

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

      다음을 바꿉니다.

      • ADMINISTRATOR_EMAIL: SFTP 사용자를 만드는 주 구성원의 이메일 주소입니다. 애플리케이션이 아닌 사용자를 만드는 경우 이 값은 액세스하는 데 사용하는 이메일 주소입니다 Google Cloud.

      • BUCKET_NAME: 버킷의 이름입니다.

    2. 아직 역할이 없는 경우 버킷에 대한 스토리지 객체 뷰어 (roles/storage.objectViewer) 역할을 자신에게 부여합니다.

      gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \
          --member="user:ADMINISTRATOR_EMAIL" \
          --role="roles/storage.objectViewer"
    3. 사용자 서비스 계정에 버킷에 액세스하는 데 필요한 IAM 역할을 부여합니다.

      gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \
        --member="serviceAccount:SERVICE_ACCOUNT" \
        --role="ROLE_TO_GRANT"

      다음을 바꿉니다.

      • SERVICE_ACCOUNT: 사용자 서비스 계정의 이메일 주소입니다.
      • ROLE_TO_GRANT: 부여할 IAM 역할입니다. 다음 역할 중 하나를 지정합니다.

        • 읽기 전용 액세스 권한의 경우 roles/storage.objectViewer 역할을 사용합니다.
        • 읽기 및 쓰기 액세스 권한의 경우 roles/storage.objectAdmin 역할을 사용합니다.
    4. 사용자가 액세스해야 하는 각 버킷에 대해 이전 단계를 반복합니다.

  3. 디렉터리 매핑에서 버킷을 삭제하거나 기존 버킷에 대한 액세스 권한을 줄이는 경우 사용자 서비스 계정에서 액세스 권한을 취소합니다.

    gcloud storage buckets remove-iam-policy-binding gs://BUCKET_NAME \
      --member="serviceAccount:SERVICE_ACCOUNT" \
      --role="ROLE_TO_REVOKE"

    ROLE_TO_REVOKE를 취소하려는 IAM 역할로 바꿉니다.

    사용자가 더 이상 액세스할 수 없어야 하는 각 버킷 및 IAM 역할에 대해 이 단계를 반복합니다.

사용자의 버킷 업데이트

gcloud

SFTP 사용자의 버킷을 업데이트하려면 gcloud alpha storage ftp users update 명령어를 실행합니다.

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

  • USERNAME: SFTP 사용자의 사용자 이름입니다.
  • 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 플래그를 여러 번 제공합니다.

다음 명령어를 실행합니다.

Linux, macOS 또는 Cloud Shell

gcloud alpha storage ftp users update USERNAME --location=LOCATION_ID \
    --server=SERVER_ID \
    --storage-directory-mapping=bucket=BUCKET_NAME,bucket_prefix=BUCKET_PREFIX,directory=DIRECTORY,permission=SFTP_PERMISSION

Windows(PowerShell)

gcloud alpha storage ftp users update USERNAME --location=LOCATION_ID `
    --server=SERVER_ID `
    --storage-directory-mapping=bucket=BUCKET_NAME,bucket_prefix=BUCKET_PREFIX,directory=DIRECTORY,permission=SFTP_PERMISSION

Windows(cmd.exe)

gcloud alpha storage ftp users update USERNAME --location=LOCATION_ID ^
    --server=SERVER_ID ^
    --storage-directory-mapping=bucket=BUCKET_NAME,bucket_prefix=BUCKET_PREFIX,directory=DIRECTORY,permission=SFTP_PERMISSION
사용자가 업데이트되는 데 몇 초 정도 걸립니다.

사용자에게 활성 SFTP 연결이 있는 경우 업데이트된 버킷 설정이 적용되도록 연결을 끊은 후 다시 연결해야 할 수 있습니다.

REST

SFTP 사용자의 버킷을 업데이트하려면 servers.users.patch 메서드를 사용합니다. updateMask 쿼리 매개변수에서 storageDirectoryMappings 필드를 제공합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • 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로 설정합니다.

사용자에게 여러 버킷에 대한 액세스 권한을 부여하려면 storageDirectoryMappings 목록에 여러 버킷 매핑을 제공합니다.

HTTP 메서드 및 URL:

PATCH https://ftp.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION_ID/servers/SERVER_ID/users/USERNAME?updateMask=storageDirectoryMappings

요청 JSON 본문:

{
  "storageDirectoryMappings": [
    {
      "bucket": "BUCKET_NAME",
      "bucketPrefix": "BUCKET_PREFIX",
      "directory": "DIRECTORY",
      "permission": "SFTP_PERMISSION"
    }
  ]
}

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

응답은 장기 실행 작업을 식별합니다. 사용자가 업데이트되는 데 몇 초 정도 걸립니다.

사용자에게 활성 SFTP 연결이 있는 경우 업데이트된 버킷 설정이 적용되도록 연결을 끊은 후 다시 연결해야 할 수 있습니다.

클라이언트 라이브러리

C#

Cloud FTP용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Cloud FTP 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Cloud FTP C# API 참고 문서를 확인하세요.

Cloud FTP에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

public sealed partial class GeneratedCloudFtpClientSnippets
{
    /// <summary>Snippet for UpdateUserAsync</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 UpdateUserAsync()
    {
        // Create client
        CloudFtpClient cloudFtpClient = await CloudFtpClient.CreateAsync();
        // Initialize request argument(s)
        User user = new User();
        FieldMask updateMask = new FieldMask();
        // Make the request
        Operation<User, OperationMetadata> response = await cloudFtpClient.UpdateUserAsync(user, updateMask);

        // 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.PollOnceUpdateUserAsync(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.UpdateUserRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/ftp/apiv1/ftppb#UpdateUserRequest.
	}
	op, err := c.UpdateUser(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.UpdateUserRequest;
import com.google.cloud.ftp.v1.User;
import com.google.longrunning.Operation;
import com.google.protobuf.FieldMask;

public class AsyncUpdateUser {

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

  public static void asyncUpdateUser() 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()) {
      UpdateUserRequest request =
          UpdateUserRequest.newBuilder()
              .setUpdateMask(FieldMask.newBuilder().build())
              .setUser(User.newBuilder().build())
              .build();
      ApiFuture<Operation> future = cloudFtpClient.updateUserCallable().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.
 */
/**
 *  Optional. Field mask is used to specify the fields to be overwritten in the
 *  User resource by the update.
 *  The fields specified in the update_mask are relative to the resource, not
 *  the full request. A field will be overwritten if it is in the mask. If the
 *  user does not provide a mask then all fields present in the request will be
 *  overwritten.
 */
// const updateMask = {}
/**
 *  Required. The resource being updated
 */
// const user = {}

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

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

async function callUpdateUser() {
  // Construct request
  const request = {
    user,
  };

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

callUpdateUser();

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\StorageDirectoryMapping;
use Google\Cloud\Ftp\V1\StorageDirectoryMapping\Permission;
use Google\Cloud\Ftp\V1\UpdateUserRequest;
use Google\Cloud\Ftp\V1\User;
use Google\Cloud\Ftp\V1\UserCredential;
use Google\Cloud\Ftp\V1\UserCredential\Type;
use Google\Rpc\Status;

/**
 * Updates the parameters of a single User.
 *
 * @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 update_user_sample(
    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 UpdateUserRequest())
        ->setUser($user);

    // Call the API and handle any network failures.
    try {
        /** @var OperationResponse $response */
        $response = $cloudFtpClient->updateUser($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
{
    $userCustomerServiceAccount = '[CUSTOMER_SERVICE_ACCOUNT]';
    $userUserCredentialsCredentialName = '[CREDENTIAL_NAME]';
    $userUserCredentialsCredentialType = Type::TYPE_UNSPECIFIED;
    $userStorageDirectoryMappingsBucket = '[BUCKET]';
    $userStorageDirectoryMappingsDirectory = '[DIRECTORY]';
    $userStorageDirectoryMappingsPermission = Permission::PERMISSION_UNSPECIFIED;

    update_user_sample(
        $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_update_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.UpdateUserRequest(
        user=user,
    )

    # Make the request
    operation = client.update_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 update_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#update_user.
#
def update_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::UpdateUserRequest.new

  # Call the update_user method.
  result = client.update_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