In azure function .NET 8 isolated worker on linux flex consumption plan, is it possible to execute bash script in code by invoking .sh file stored in project?
1
Follow below steps to achieve your requirement:
Create a .sh
file under scripts folder in root directory.
./Scripts/myscript.sh
:
#!/bin/bash
echo "Hello from myscript.sh!"
echo "This is a test file created by the script." > /tmp/testfile.txt
cat /tmp/testfile.txt
exit 0
Use below function code in .NET 8.0 Isolated Azure functions to execute bash script by invoking .sh
file in the function code.
Code Snippet:
[Function("Function1")]
public IActionResult Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post")] HttpRequest req)
{
_logger.LogInformation("C# HTTP trigger function processed a request.");
_logger.LogInformation(Directory.GetCurrentDirectory());
string scriptPath = Path.Combine("/home", "site", "wwwroot", "scripts", "myscript.sh");
if (!File.Exists(scriptPath))
{
_logger.LogError($"Script file not found at {scriptPath}");
}
var startInfo = new ProcessStartInfo
{
FileName = "/bin/bash",
Arguments = scriptPath,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
try
{
using (var process = Process.Start(startInfo))
{
if (process != null)
{
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
_logger.LogInformation($"Output: {output}");
if (!string.IsNullOrEmpty(error))
{
_logger.LogError($"Error: {error}");
}
process.WaitForExitAsync();
}
}
}
catch (Exception ex)
{
_logger.LogError($"An error occurred while executing the script: {ex.Message}");
}
return new OkObjectResult("Success!");
}
Deploy the function to Azure function App with flex consumption plan.
Console Output:
Run the function and you will be able to execute the script using Azure function. Check the invocation logs for detailed output as below.
2024-12-13T10:52:30Z [Information] Executing 'Functions.Function1' (Reason='This function was programmatically called via the host APIs.', Id=58d00ce3-f7cb-4dad-9f2c-479e622cbed4)
2024-12-13T10:52:30Z [Information] C# HTTP trigger function processed a request.
2024-12-13T10:52:30Z [Information] /tmp/functionsstandbywwwroot
2024-12-13T10:52:30Z [Information] Output: Hello from myscript.sh!
This is a test file created by the script.
2024-12-13T10:52:30Z [Information] Executing OkObjectResult, writing value of type 'System.String'.
2024-12-13T10:52:30Z [Information] Executed 'Functions.Function1' (Succeeded, Id=c726dfa3-52f2-43b1-8121-5184c01cf74b, Duration=20ms)