Here's a step-by-step guide to creating a GoLang gRPC service that runs Ansible playbooks, streams the output to the client, and supports pagination (splitting output into multiple pages). This example assumes you have basic knowledge of Go, gRPC, and Ansible.
Prerequisites
Go (>= 1.16): Installed on your system.
gRPC and Protobuf tools: Install using go install google.golang.org/protobuf/cmd/protoc@v1.28 and go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.2
Ansible (>= 2.9): Installed on the system running the gRPC server, with playbooks configured.
Step 1: Define the gRPC Service (.proto file)
Create a file named ansible_service.proto:
protobuf
syntax = "proto3";
package ansible;
// gRPC service definition for running Ansible playbooks
service AnsibleService {
// Run an Ansible playbook and stream the output
rpc RunPlaybook(PlaybookRequest) returns (stream PlaybookOutput) {}
}
// Request message for running a playbook
message PlaybookRequest {
string playbook_path = 1; // Path to the Ansible playbook
repeated string extra_vars = 2; // Optional: Extra variables for the playbook
int32 page_size = 3; // Number of output lines per page
int32 page_token = 4; // Token for the next page (0 for the first page)
}
// Response message for playbook output
message PlaybookOutput {
string output_line = 1; // Single line of output
bool end_of_output = 2; // Indicates the end of the output stream
int32 next_page_token = 3; // Token for the next page (0 if no more pages)
}
package main
import (
"context"
"fmt"
"io"
"log"
"os/exec"
"strings"
"google.golang.org/grpc"
"your/module/path/ansible" // Import generated protobuf package
)
// ansibleService implements the AnsibleServiceServer interface
type ansibleService struct {
ansible.UnimplementedAnsibleServiceServer
}
// RunPlaybook runs an Ansible playbook and streams the output to the client
func (s *ansibleService) RunPlaybook(req *ansible.PlaybookRequest, stream ansible.AnsibleService_RunPlaybookServer) error {
ctx := stream.Context()
// Construct the Ansible playbook command
playbookCmd := exec.Command("ansible-playbook", req.PlaybookPath)
// Add extra variables if provided
for _, varStr := range req.ExtraVars {
playbookCmd.Args = append(playbookCmd.Args, "-e", varStr)
}
// Setup output pipe
output, err := playbookCmd.StdoutPipe()
if err != nil {
return err
}
defer output.Close()
// Start the command
if err := playbookCmd.Start(); err != nil {
return err
}
// Stream output
outputScanner := newScanner(output, req.PageSize)
for outputScanner.Scan() {
select {
case <-ctx.Done():
return ctx.Err()
default:
outputLine := outputScanner.Text()
if outputLine == "" {
// End of output
if err := stream.Send(&ansible.PlaybookOutput{EndOfOutput: true}); err != nil {
return err
}
return playbookCmd.Wait()
}
// Send output line with next page token if necessary
nextPageToken := int32(0)
if outputScanner.LinesRead >= int(req.PageSize) {
nextPageToken = int32(outputScanner.LinesRead)
outputScanner.LinesRead = 0 // Reset for next page
}
if err := stream.Send(&ansible.PlaybookOutput{
OutputLine: outputLine,
NextPageToken: nextPageToken,
}); err != nil {
return err
}
}
}
return playbookCmd.Wait()
}
// scanner wraps strings.Scanner to track lines read
type scanner struct {
*strings.Scanner
LinesRead int
}
// newScanner returns a scanner for reading output lines with pagination
func newScanner(r io.Reader, pageSize int) *scanner {
s := &scanner{
Scanner: strings.NewScanner(r),
LinesRead: 0,
}
s.Split(bufio.ScanLines)
return s
}
func main() {
// Listen on port 50051
lis, err := net.Listen("tcp", "localhost:50051")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
// Create and start the gRPC server
s := grpc.NewServer()
ansible.RegisterAnsibleServiceServer(s, &ansibleService{})
log.Printf("gRPC server listening on port 50051")
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
Step 4: Client Code to Consume the Service
Create a client file named client.go:
go
package main
import (
"context"
"fmt"
"log"
"google.golang.org/grpc"
"your/module/path/ansible" // Import generated protobuf package
)
func main() {
// Connect to the gRPC server
conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
client := ansible.NewAnsibleServiceClient(conn)
// Request to run a playbook
req := &ansible.PlaybookRequest{
PlaybookPath: "/path/to/your/playbook.yml",
PageSize: 10, // Lines per page
}
// Initiate the playbook run and stream output
stream, err := client.RunPlaybook(context.Background(), req)
if err != nil {
log.Fatalf("could not run playbook: %v", err)
}
for {
resp, err := stream.Recv()
if err == io.EOF {
break
}
if err != nil {
log.Fatalf("could not receive output: %v", err)
}
if resp.EndOfOutput {
log.Println("End of playbook output.")
break
}
fmt.Println(resp.OutputLine)
// Fetch next page if needed
if resp.NextPageToken > 0 {
req.PageToken = resp.NextPageToken
stream, err = client.RunPlaybook(context.Background(), req)
if err != nil {
log.Fatalf("could not continue to next page: %v", err)
}
}
}
}
Running the Service and Client
Run the gRPC Service:
bash
go run ansible_service.go
In a new terminal, run the Client:
bash
go run client.go
Note:
Ensure you replace "your/module/path/ansible" with the actual path to the generated protobuf package in your Go environment.
Update the playbook_path in client.go to point to a valid Ansible playbook on your system.
This example uses insecure gRPC connections. For production, consider enabling TLS.
The pageSize and pagination logic are simplified for demonstration. You might want to enhance this based on your specific requirements, such as handling errors during pagination more robustly. The nextPageToken is used to track pagination, allowing the client to fetch subsequent pages of output.