- Connecting securely to Microsoft Azure service with SFTP or FTPS
- Before Starting
- Connecting to a Linux Virtual Machine with SFTP
- Connecting to a Windows Virtual Machine with FTPS
- Connecting to an App Service (Web Site) with FTPS
- Deploy your app to Azure App Service using FTP/S
- Get deployment credentials
- Get FTP/S endpoint
- Deploy files to Azure
- Enforce FTPS
- What happens to my app during deployment?
- Troubleshoot FTP deployment
- How can I troubleshoot FTP deployment?
- I’m not able to FTP and publish my code. How can I resolve the issue?
- How can I connect to FTP in Azure App Service via passive mode?
- Создание и отслеживание FTP-файлов, а также управление ими с помощью Azure Logic Apps Create, monitor, and manage FTP files by using Azure Logic Apps
- Ограничения Limitations
- Как работают триггеры FTP How FTP triggers work
- Предварительные требования Prerequisites
- Подключение к FTP Connect to FTP
- Примеры Examples
- Добавление триггера FTP Add FTP trigger
- Добавление действия FTP Add FTP action
- Тестирование приложения логики Test your logic app
- Справочник по соединителям Connector reference
Connecting securely to Microsoft Azure service with SFTP or FTPS
With WinSCP you can easily upload and manage files on your Microsoft Azure instance/service over SFTP protocol or FTPS protocol.
Before Starting
Before starting you should have WinSCP installed.
Connecting to a Linux Virtual Machine with SFTP
First, collect information about your virtual machine instance, on the Azure portal:
- Host name:
- Use IP address you find in the Public IP address section on your virtual machine instance page;
- Or setup a DNS name for the virtual machine by clicking on the Configure link in DNS name section. A Configuration panel opens. There, in the DNS name label, enter a sub domain for your virtual machine. Click Save button. A full hostname now appears in the DNS name section in a format subdomain.location.cloudapp.azure.com .
- Username: Use the username, that you created, when creating the virtual machine.
- Host key fingerprint: On the first connect you will be prompted to verify server host key.
To securely acquire a fingerprint of the host key:- On your virtual machine instance page, use Run command function. You will find it in the virtual machine menu, in Operations group.
- Select “RunShellScript” command.
- Paste the following command:
- You will get an output like: The set of key types will vary with your virtual machine image.
- When creating new virtual machine, prefer setting up public key authentication by pasting your public key to SSH public key box in the Basics step in the Administrator account section. If you want to setup public key authentication later, you have to set it up manually.
To connect to a virtual machine instance with SFTP , start WinSCP. Login dialog will appear. On the dialog:
- Make sure New site node is selected.
- On the New site node, make sure SFTP protocol is selected.
- Enter Host name.
- Enter User name.
- Enter a password for the username. Or specify a private key, if you set up a public key authentication..
- Save your site settings using the Save button.
- Login using the Login button.
- Verify the host key by comparing fingerprints with those collected before (see above).
Connecting to a Windows Virtual Machine with FTPS
To connect to the virtual machine with FTPS , start WinSCP. Login dialog will appear. On the dialog:
- Make sure New site node is selected.
- On the New site node, select FTP protocol and TLS /SSL Explicit encryption.
- In Host name box enter an address of your virtual machine:
- Use IP address you find in the Public IP address section on your virtual machine instance page on the Azure portal.
- Or setup a DNS name for the virtual machine by clicking on the Configure link in DNS name section. A Configuration panel opens. There, in the DNS name label, enter a sub domain for your virtual machine. Click Save button. A full hostname now appears in the DNS name section in a format subdomain.location.cloudapp.azure.com .
- Enter username and password of an account you want to connect with. Use the account you have specified when creating the instance or any other account you have created on the instance.
- Save your site settings using the Save button.
- Login using the Login button.
- If you are using self-signed certificate, you will be prompted to accept it.
Connecting to an App Service (Web Site) with FTPS
First, collect information about your app service (previously web site), on the Azure portal:
- Host name: Copy host name from FTPS hostname section on the Overview page.
- User Name: Copy username from the FTP/deployment username section on the Overview page. If you did not set up an FTP account yet, goto Deployment Center page and select FTP in Manual Deployment section and switch to User Credentials tab. User name has a form name\user . You need to use both parts when authenticating.
To connect to the web site with FTPS, start WinSCP. Login dialog will appear. On the dialog:
Deploy your app to Azure App Service using FTP/S
This article shows you how to use FTP or FTPS to deploy your web app, mobile app backend, or API app to Azure App Service.
The FTP/S endpoint for your app is already active. No configuration is necessary to enable FTP/S deployment.
The Development Center (Classic) page in the Azure portal, which is the old deployment experience, will be deprecated in March, 2021. This change will not affect any existing deployment settings in your app, and you can continue to manage app deployment in the Deployment Center page.
Get deployment credentials
Follow the instructions at Configure deployment credentials for Azure App Service to copy the application-scope credentials or set the user-scope credentials. You can connect to the FTP/S endpoint of your app using either credentials.
Craft the FTP username in the following format, depending on your choice of credential scope:
Application-scope | User-scope |
---|---|
\$ | \ |
In App Service, the FTP/S endpoint is shared among apps. Because the user-scope credentials aren’t linked to a specific resource, you need to prepend the user-scope username with the app name as shown above.
Get FTP/S endpoint
In the same management page for your app where you copied the deployment credentials (Deployment Center > FTP Credentials), copy the FTPS endpoint.
Run the az webapp deployment list-publishing-profiles command. The following example uses a JMES path to extract the FTP/S endpoints from the output.
Each app has two FTP/S endpoints, one is read-write, while the other is read-only ( profileName contains ReadOnly ) and is for data recovery scenarios. To deploy files with FTP, copy the URL of the read-write endpoint.
Run the Get-AzWebAppPublishingProfile command. The following example extracts the FTP/S endpoint from the XML output.
Deploy files to Azure
- From your FTP client (for example, Visual Studio, Cyberduck, or WinSCP), use the connection information you gathered to connect to your app.
- Copy your files and their respective directory structure to the /site/wwwroot directory in Azure (or the /site/wwwroot/App_Data/Jobs/ directory for WebJobs).
- Browse to your app’s URL to verify the app is running properly.
Unlike Git-based deployments and Zip deployment, FTP deployment doesn’t support build automation, such as:
- dependency restores (such as NuGet, NPM, PIP, and Composer automations)
- compilation of .NET binaries
- generation of web.config (here is a Node.js example)
Generate these necessary files manually on your local machine, and then deploy them together with your app.
Enforce FTPS
For enhanced security, you should allow FTP over TLS/SSL only. You can also disable both FTP and FTPS if you don’t use FTP deployment.
In your app’s resource page in Azure portal, select Configuration > General settings from the left navigation.
To disable unencrypted FTP, select FTPS Only in FTP state. To disable both FTP and FTPS entirely, select Disabled. When finished, click Save. If using FTPS Only, you must enforce TLS 1.2 or higher by navigating to the TLS/SSL settings blade of your web app. TLS 1.0 and 1.1 are not supported with FTPS Only.
Run the az webapp config set command with the —ftps-state argument.
Possible values for —ftps-state are AllAllowed (FTP and FTPS enabled), Disabled (FTP and FTPs disabled), and FtpsOnly (FTPS only).
Run the Set-AzWebApp command with the -FtpsState parameter.
Possible values for —ftps-state are AllAllowed (FTP and FTPS enabled), Disabled (FTP and FTPs disabled), and FtpsOnly (FTPS only).
What happens to my app during deployment?
All the officially supported deployment methods make changes to the files in the /home/site/wwwroot folder of your app. These files are used to run your app. Therefore, the deployment can fail because of locked files. The app may also behave unpredictably during deployment, because not all the files updated at the same time. This is undesirable for a customer-facing app. There are a few different ways to avoid these issues:
- Run your app from the ZIP package directly without unpacking it.
- Stop your app or enable offline mode for your app during deployment. For more information, see Deal with locked files during deployment.
- Deploy to a staging slot with auto swap enabled.
Troubleshoot FTP deployment
How can I troubleshoot FTP deployment?
The first step for troubleshooting FTP deployment is isolating a deployment issue from a runtime application issue.
A deployment issue typically results in no files or wrong files deployed to your app. You can troubleshoot by investigating your FTP deployment or selecting an alternate deployment path (such as source control).
A runtime application issue typically results in the right set of files deployed to your app but incorrect app behavior. You can troubleshoot by focusing on code behavior at runtime and investigating specific failure paths.
To determine a deployment or runtime issue, see Deployment vs. runtime issues.
I’m not able to FTP and publish my code. How can I resolve the issue?
Check that you’ve entered the correct hostname and credentials. Check also that the following FTP ports on your machine are not blocked by a firewall:
- FTP control connection port: 21, 990
- FTP data connection port: 989, 10001-10300
How can I connect to FTP in Azure App Service via passive mode?
Azure App Service supports connecting via both Active and Passive mode. Passive mode is preferred because your deployment machines are usually behind a firewall (in the operating system or as part of a home or business network). See an example from the WinSCP documentation.
Создание и отслеживание FTP-файлов, а также управление ими с помощью Azure Logic Apps Create, monitor, and manage FTP files by using Azure Logic Apps
С помощью Azure Logic Apps и соединителя FTP можно создать автоматизированные задачи и рабочие процессы, которые создают, отслеживают, отправляют и получают файлы, а также управляют ими в вашей учетной записи, на сервере FTP. Они также выполняют и другие действия, например: With Azure Logic Apps and the FTP connector, you can create automated tasks and workflows that create, monitor, send, and receive files through your account on an FTP server, along with other actions, for example:
- мониторинг добавления или изменения файлов; Monitor when files are added or changed.
- получение, создание, копирование, перечисление, обновление и удаление файлов; Get, create, copy, update, list, and delete files.
- получение содержимого и метаданных файлов; Get file content and metadata.
- извлечение архивов в папки. Extract archives to folders.
Вы можете использовать триггеры, которые получают ответы из сервера FTP и делают выходные данные доступными для других действий. You can use triggers that get responses from your FTP server and make the output available to other actions. Вы можете использовать действия запуска в своих приложениях логики для управления файлами на сервере FTP. You can use run actions in your logic apps for managing files on your FTP server. Кроме того, выходные данные от действий FTP могут использоваться другими действиями. You can also have other actions use the output from FTP actions. Например, если вы регулярно извлекаете файлы с сервера FTP, вы можете отправлять сообщения об этих файлах и их содержимое с помощью соединителя Office 365 Outlook или соединителя Outlook.com. For example, if you regularly get files from your FTP server, you can send email about those files and their content by using the Office 365 Outlook connector or Outlook.com connector. Если вы не знакомы с приложениями логики, ознакомьтесь с Azure Logic Apps. If you’re new to logic apps, review What is Azure Logic Apps.
Ограничения Limitations
Соединитель FTP поддерживает только явный FTP через TLS/SSL (FTPS) и не совместим с неявным FTPS. The FTP connector supports only explicit FTP over TLS/SSL (FTPS) and isn’t compatible with implicit FTPS.
По умолчанию действия FTP могут считывать или записывать файлы размером 50 МБ или меньше. By default, FTP actions can read or write files that are 50 MB or smaller. Для работы с файлами, размер которых превышает 50 МБ, действия FTP поддерживают фрагментацию сообщений. To handle files larger than 50 MB, FTP actions support message chunking. Действие получить содержимое файла неявно использует фрагментацию. The Get file content action implicitly uses chunking.
Триггеры FTP не поддерживают фрагментацию. FTP triggers don’t support chunking. При запросе содержимого файла триггеры выбирают только файлы размером 50 МБ или меньше. When requesting file content, triggers select only files that are 50 MB or smaller. Чтобы получить файлы размером более 50 МБ, следуйте приведенному ниже шаблону: To get files larger than 50 MB, follow this pattern:
Используйте триггер FTP, возвращающий свойства файла, например при добавлении или изменении файла (только свойства). Use an FTP trigger that returns file properties, such as When a file is added or modified (properties only).
Выполните триггер с действием FTP Get File Content , которое считывает полный файл и неявно использует фрагментацию. Follow the trigger with the FTP Get file content action, which reads the complete file and implicitly uses chunking.
Если у вас есть локальный FTP-сервер, рассмотрите возможность создания среды службы интеграции (ISE) или использования гибридных подключений службы приложений Azure, которые позволяют получать доступ к локальным источникам данных без использования локального шлюза данных. If you have an on-premises FTP server, consider creating an integration service environment (ISE) or using Azure App Service Hybrid connections, which both let you access on-premises data sources without using an on-premises data gateway.
Как работают триггеры FTP How FTP triggers work
Триггеры FTP работают путем опроса файловой системы FTP и поиска файла, который был изменен с момента последнего опроса. FTP triggers work by polling the FTP file system and looking for any file that was changed since the last poll. При изменении файлов некоторые средства позволяют сохранить метку времени. Some tools let you preserve the timestamp when the files change. В этом случае необходимо отключить эту функцию, чтобы триггер мог работать. In these cases, you have to disable this feature so your trigger can work. Ниже приведены некоторые распространенные параметры: Here are some common settings:
Клиент SFTP SFTP client | Действие Action |
---|---|
Winscp Winscp | Последовательно выберите пункты Параметры > предпочтения > Перенос > изменить > сохранить метку > отключать . Go to Options > Preferences > Transfer > Edit > Preserve timestamp > Disable |
FileZilla FileZilla | Переход к передаче > сохранять метки времени для перенесенных файлов > Отключить Go to Transfer > Preserve timestamps of transferred files > Disable |
Найдя новый файл, триггер проверяет, записан ли файл полностью, а не частично. When a trigger finds a new file, the trigger checks that the new file is complete, and not partially written. Например, во время проверки файлового сервера триггером в файл могут вноситься изменения. For example, a file might have changes in progress when the trigger checks the file server. Чтобы избежать возврата частично записанного файла, триггер отмечает метку времени для файла с последними изменениями и не возвращает его сразу. To avoid returning a partially written file, the trigger notes the timestamp for the file that has recent changes, but doesn’t immediately return that file. Он возвращает его только при повторном опросе сервера. The trigger returns the file only when polling the server again. Иногда такое поведение может вызвать задержку, которая удваивает интервал опроса триггера. Sometimes, this behavior might cause a delay that is up to twice the trigger’s polling interval.
Предварительные требования Prerequisites
Подписка Azure. An Azure subscription. Если у вас еще нет подписки Azure, зарегистрируйтесь для получения бесплатной учетной записи Azure. If you don’t have an Azure subscription, sign up for a free Azure account.
Адрес сервера узла FTP и учетные данные учетной записи Your FTP host server address and account credentials
Для соединителя FTP требуется доступный через Интернет FTP-сервер, который настроен для работы в пассивном режиме. The FTP connector requires that your FTP server is accessible from the internet and set up to operate in passive mode. Ваши учетные данные позволяют приложению логики создавать подключение и предоставлять доступ к вашей учетной записи FTP. Your credentials let your logic app create a connection and access your FTP account.
Приложение логики, из которого необходимо получить доступ к учетной записи FTP. The logic app where you want to access your FTP account. Чтобы начать работу с триггером FTP, создайте пустое приложение логики. To start with an FTP trigger, create a blank logic app. Чтобы использовать действие FTP, запустите приложение логики с другим триггером, например триггером Периодичность. To use an FTP action, start your logic app with another trigger, for example, the Recurrence trigger.
Подключение к FTP Connect to FTP
При добавлении триггера или действия, которое подключается к службе или системе в первый раз, конструктор Logic App предлагает создать подключение, предоставив необходимые сведения с учетом этого подключения, например: When you add a trigger or action that connects to a service or system for the first time, the Logic App Designer prompts you to create a connection by providing the necessary information, which varies based on the connection, for example:
имя, которое вы хотите использовать для нового подключения; The name that you want to use for the new connection
имя для системы или сервера; The name for the system or server
учетные данные пользователя или учетной записи; Your user or account credentials
Тип проверки подлинности The authentication type to use
Войдите в портал Azureи откройте приложение логики в конструкторе приложений логики. Sign in to the Azure portal, and open your logic app in Logic App Designer.
Для пустых приложений логики в поле поиска введите ftp фильтр. For blank logic apps, in the search box, enter ftp as your filter. В списке триггеры выберите нужный триггер. From the Triggers list, select the trigger that you want.
Для существующих приложений логики на последнем шаге, где нужно добавить действие, выберите новый шаг, а затем щелкните Добавить действие. For existing logic apps, under the last step where you want to add an action, select New step, and then select Add an action. В поле поиска введите ftp в качестве фильтра. In the search box, enter ftp as your filter. В списке действия выберите нужное действие. From the Actions list, select the action that you want.
Чтобы добавить действие между шагами, переместите указатель на стрелку между шагами. To add an action between steps, move your pointer over the arrow between steps. Нажмите появившийся знак «плюс» ( + ), а затем выберите Добавить действие. Select the plus sign (+) that appears, and then select Add an action.
Укажите сведения о подключении и щелкните создать. Provide your connection information, and select Create.
Укажите сведения для выбранного триггера или действия и продолжайте создавать рабочий процесс приложения логики. Provide the information for your selected trigger or action and continue building your logic app’s workflow.
Примеры Examples
Добавление триггера FTP Add FTP trigger
Триггер при добавлении или изменении файла (только свойства) запускает рабочий процесс приложения логики, когда триггер обнаруживает, что файл добавлен или изменен на FTP-сервере. The When a file is added or modified (properties only) trigger starts a logic app workflow when the trigger detects that a file is added or changed on an FTP server. Например, можно добавить условие, которое проверяет содержимое файла и принимает решение, следует ли получать это содержимое в зависимости от того, соответствует ли это содержимое заданному условию. For example, you can add a condition that checks the file’s content and decides whether to get that content, based on whether that content meets a specified condition. Наконец, можно добавить действие, которое получает содержимое файла и поместить его в другую папку на SFTP-сервере. Finally, you can add an action that gets the file’s content, and put that content into a different folder on the SFTP server.
Например, с помощью этого триггера можно отслеживать папку FTP для новых файлов, описывающих заказы клиентов. For example, you can use this trigger to monitor an FTP folder for new files that describe customer orders. Затем можно использовать действие FTP, такое как Получение метаданных файла , чтобы получить свойства для нового файла, а затем использовать команду получить содержимое файла для получения содержимого из этого файла для дальнейшей обработки и сохранения этого порядка в базе данных Orders. You can then use an FTP action such as Get file metadata to get the properties for that new file, and then use Get file content to get the content from that file for further processing and store that order in an orders database.
Ниже приведен пример использования триггера при добавлении или изменении файла (только свойства) . Here is an example that shows how to use the When a file is added or modified (properties only) trigger.
Войдите на портал Azure и откройте свое приложение логики в конструкторе приложений логики, если оно еще не открыто. Sign in to the Azure portal, and open your logic app in Logic App Designer, if not open already.
Для пустых приложений логики в поле поиска введите ftp фильтр. For blank logic apps, in the search box, enter ftp as your filter. В списке триггеры выберите этот триггер: при добавлении или изменении архивирования (только свойства) . Under the triggers list, select this trigger: When a filed is added or modified (properties only)
Укажите необходимые сведения для подключения и нажмите кнопку создать. Provide the necessary details for your connection, and then select Create.
По умолчанию этот соединитель передает файлы в текстовом формате. By default, this connector transfers files in text format. Для передачи файлов в двоичном формате, например, когда и где используется кодирование, выберите Binary Transport (Двоичная транспортировка). To transfer files in binary format, for example, where and when encoding is used, select Binary Transport.
В поле Папка выберите значок папки, чтобы появился список. In the Folder box, select the folder icon so that a list appears. Чтобы найти папку, которую необходимо отслеживать для новых или измененных файлов, выберите правую стрелку угла ( > ), перейдите к этой папке, а затем выберите папку. To find the folder you want to monitor for new or edited files, select the right angle arrow (>), browse to that folder, and then select the folder.
Выбранная папка отображается в поле Folder. Your selected folder appears in the Folder box.
Сохраните приложение логики. Save your logic app. На панели инструментов конструктора щелкните Сохранить. On the designer toolbar, select Save.
После того как логическое приложение получило триггер, добавьте действия, которые необходимо запустить, когда логическое приложение находит новый или отредактированный файл. Now that your logic app has a trigger, add the actions you want to run when your logic app finds a new or edited file. В этом примере вы можете добавить действие FTP, которое получает новое или обновленное содержимое. For this example, you can add an FTP action that gets the new or updated content.
Добавление действия FTP Add FTP action
Действие получить метаданные файла Возвращает свойства файла, расположенного на FTP-сервере, и действие получить содержимое файла получает содержимое файла на основе сведений об этом файле на FTP-сервере. The Get file metadata action gets the properties for a file that’s on your FTP server and the Get file content action gets the file content based on the information about that file on your FTP server. Например, можно добавить триггер из предыдущего примера и эти действия, чтобы получить содержимое файла после добавления или изменения файла. For example, you can add the trigger from the previous example and these actions to get the file’s content after that file is added or edited.
Под триггером или любыми другими действиями выберите новый шаг. Under the trigger or any other actions, select New step.
В поле поиска введите ftp в качестве фильтра. In the search box, enter ftp as your filter. В списке действия выберите это действие: получить метаданные файла . Under the actions list, select this action: Get file metadata
Если у вас уже есть соединение с вашим FTP-сервером и учетной записью, перейдите к следующему шагу. If you already have a connection to your FTP server and account, go to the next step. В противном случае укажите необходимые сведения для этого подключения и нажмите кнопку создать. Otherwise, provide the necessary details for that connection, and then select Create.
После того как появится действие получить метаданные файла , щелкните внутри поля файла , чтобы появился список динамического содержимого. After the Get file metadata action appears, click inside the File box so that the dynamic content list appears. Теперь можно выбрать свойства для выходных данных из предыдущих шагов. You can now select properties for the outputs from previous steps. В списке динамическое содержимое в разделе Получение метаданных файла выберите свойство List of Files ID , которое ссылается на коллекцию, в которую был добавлен или обновлен файл. In the dynamic content list, under Get file metadata, select the List of Files Id property, which references the collection where the file was added or updated.
В поле файл теперь появится свойство список идентификаторов файлов . The List of Files Id property now appears in the File box.
Теперь добавьте это действие FTP: Получение содержимого файла Now add this FTP action: Get file content
После отображения действия получить содержимое файла щелкните внутри поля файла , чтобы появился список динамического содержимого. After the Get file content action appears, click inside the File box so that the dynamic content list appears. Теперь можно выбрать свойства для выходных данных из предыдущих шагов. You can now select properties for the outputs from previous steps. В списке динамическое содержимое в разделе Получение метаданных файла выберите свойство ID , которое ссылается на добавленный или обновленный файл. In the dynamic content list, under Get file metadata, select the Id property, which references the file that was added or updated.
Свойство ID теперь отображается в поле файл . The Id property now appears in the File box.
Сохраните приложение логики Save your logic app.
Тестирование приложения логики Test your logic app
Чтобы убедиться, что рабочий процесс возвращает предполагаемое содержимое, добавьте другое действие, которое отправляет содержимое из отправленного или обновленного файла. To check that your workflow returns the content that you expect, add another action that sends you the content from the uploaded or updated file.
В разделе действие » получить содержимое файла » добавьте действие, которое может отправить содержимое файла. Under the Get file content action, add an action that can send you the file’s contents. В этом примере добавляется действие Отправить сообщение электронной почты для Office 365 Outlook. This example adds the Send an email action for the Office 365 Outlook.
После появления действия укажите сведения и укажите свойства, которые требуется протестировать. After the action appears, provide the information and include the properties that you want to test. Например, включите свойство содержимое файла , которое отображается в списке динамическое содержимое после выбора в разделе получить содержимое файла . For example, include the File content property, which appears in the dynamic content list after you select See more in the Get file content section.
Сохраните приложение логики Save your logic app. Чтобы запустить и активировать приложение логики, на панели инструментов выберите выполнить, а затем добавьте файл в папку FTP, которую теперь отслеживает приложение логики. To run and trigger the logic app, on the toolbar, select Run, and then add a file to the FTP folder that your logic app now monitors.
Справочник по соединителям Connector reference
Дополнительные технические сведения об этом соединителе, такие как триггеры, действия и ограничения, описанные в файле Swagger соединителя, см. на странице справочника по соединителю. For more technical details about this connector, such as triggers, actions, and limits as described by the connector’s Swagger file, see the connector’s reference page.
Для приложений логики в среде службы интеграции (ISE)эта версия этого соединителя использует ограничения сообщений интегрированной среды сценариев. For logic apps in an integration service environment (ISE), this connector’s ISE-labeled version uses the ISE message limits instead.