Ví dụ về tempfile python

Ứng dụng của bạn phải ghi dữ liệu vào một tệp tạm thời để xử lý lại chúng trước khi hiển thị cho người dùng. Tệp sẽ được tạo tạm thời và quét của chúng tôi khi ứng dụng khởi động lại hoặc tắt. Làm thế nào để chúng tôi tạo ra một tập tin như vậy?

Mục lục

Giới thiệu bối cảnh

Trong hướng dẫn này, chúng ta sẽ tìm hiểu cách tạo một tệp tạm thời trong Java. Có hai phương thức tĩnh

var assert = require['assert'];
var AWS = require['aws-sdk'];
var http = require['http'];

exports.handler = function[event, context] {

    var codepipeline = new AWS.CodePipeline[];
    
    // Retrieve the Job ID from the Lambda action
    var jobId = event["CodePipeline.job"].id;
    
    // Retrieve the value of UserParameters from the Lambda action configuration in CodePipeline, in this case a URL which will be
    // health checked by this function.
    var url = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; 
    
    // Notify CodePipeline of a successful job
    var putJobSuccess = function[message] {
        var params = {
            jobId: jobId
        };
        codepipeline.putJobSuccessResult[params, function[err, data] {
            if[err] {
                context.fail[err];      
            } else {
                context.succeed[message];      
            }
        }];
    };
    
    // Notify CodePipeline of a failed job
    var putJobFailure = function[message] {
        var params = {
            jobId: jobId,
            failureDetails: {
                message: JSON.stringify[message],
                type: 'JobFailed',
                externalExecutionId: context.awsRequestId
            }
        };
        codepipeline.putJobFailureResult[params, function[err, data] {
            context.fail[message];      
        }];
    };
    
    // Validate the URL passed in UserParameters
    if[!url || url.indexOf['//'] === -1] {
        putJobFailure['The UserParameters field must contain a valid URL address to test, including // or //'];  
        return;
    }
    
    // Helper function to make a HTTP GET request to the page.
    // The helper will test the response and succeed or fail the job accordingly 
    var getPage = function[url, callback] {
        var pageObject = {
            body: '',
            statusCode: 0,
            contains: function[search] {
                return this.body.indexOf[search] > -1;    
            }
        };
        http.get[url, function[response] {
            pageObject.body = '';
            pageObject.statusCode = response.statusCode;
            
            response.on['data', function [chunk] {
                pageObject.body += chunk;
            }];
            
            response.on['end', function [] {
                callback[pageObject];
            }];
            
            response.resume[]; 
        }].on['error', function[error] {
            // Fail the job if our request failed
            putJobFailure[error];    
        }];           
    };
    
    getPage[url, function[returnedPage] {
        try {
            // Check if the HTTP response has a 200 status
            assert[returnedPage.statusCode === 200];
            // Check if the page contains the text "Congratulations"
            // You can change this to check for different text, or add other tests as required
            assert[returnedPage.contains['Congratulations']];  
            
            // Succeed the job
            putJobSuccess["Tests passed."];
        } catch [ex] {
            // If any of the assertions failed then fail the job
            putJobFailure[ex];    
        }
    }];     
};
1 trong lớp Tệp Java, phương thức này sẽ giúp tạo tệp tạm thời trên vị trí thư mục TEMP mặc định và một phương thức khác được sử dụng để tạo tệp tạm thời trên vị trí thư mục đã chỉ định

Làm thế nào để thực hiện

Tôi trình bày một triển khai giới thiệu bằng một số ngôn ngữ được sử dụng rộng rãi. Việc triển khai chi tiết có thể hơi khác một chút

Tạo tập tin tạm thời

Java

Trong ví dụ dưới đây, chúng tôi đã tạo hai tệp tạm thời. Trong cuộc gọi phương thức đầu tiên, tệp tạm thời được tạo trên vị trí thư mục TEMP mặc định của cửa sổ. Trong cuộc gọi phương thức thứ hai, chúng tôi đã chỉ định thư mục mà tệp sẽ được tạo

package com.itersdesktop.javatechs;
 
import java.io.File;
import java.io.IOException;
 
public class TempFileExample {
    public static void main[String[] args] {
        File tempFile = new File[]
        try {
            File tempFile = File.createTempFile["my-data-file", ".dat"];
            System.out.println["Temp file On Default Location: " + tempFile.getAbsolutePath[]];
            tempFile = File.createTempFile["my-data-file", ".dat", new File["C:/Users/tom/Temp"]];
            System.out.println["Temp file On Specified Location: " + tempFile.getAbsolutePath[]];
        } catch [IOException e] {
            e.printStackTrace[];
        } finally {
            tempFile.deleteOnExit[];
            System.out.println["Exit!"]; 
        }
    }
}

hấp dẫn

Hãy cùng xem một ví dụ dưới đây. Có vẻ dễ dàng và rõ ràng

File statFile = File.createTempFile["organismStat", ".csv"]
statFile  -1;    
            }
        };
        http.get[url, function[response] {
            pageObject.body = '';
            pageObject.statusCode = response.statusCode;
            
            response.on['data', function [chunk] {
                pageObject.body += chunk;
            }];
            
            response.on['end', function [] {
                callback[pageObject];
            }];
            
            response.resume[]; 
        }].on['error', function[error] {
            // Fail the job if our request failed
            putJobFailure[error];    
        }];           
    };
    
    getPage[url, function[returnedPage] {
        try {
            // Check if the HTTP response has a 200 status
            assert[returnedPage.statusCode === 200];
            // Check if the page contains the text "Congratulations"
            // You can change this to check for different text, or add other tests as required
            assert[returnedPage.contains['Congratulations']];  
            
            // Succeed the job
            putJobSuccess["Tests passed."];
        } catch [ex] {
            // If any of the assertions failed then fail the job
            putJobFailure[ex];    
        }
    }];     
};
2 để tạo một tệp có tên là
var assert = require['assert'];
var AWS = require['aws-sdk'];
var http = require['http'];

exports.handler = function[event, context] {

    var codepipeline = new AWS.CodePipeline[];
    
    // Retrieve the Job ID from the Lambda action
    var jobId = event["CodePipeline.job"].id;
    
    // Retrieve the value of UserParameters from the Lambda action configuration in CodePipeline, in this case a URL which will be
    // health checked by this function.
    var url = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; 
    
    // Notify CodePipeline of a successful job
    var putJobSuccess = function[message] {
        var params = {
            jobId: jobId
        };
        codepipeline.putJobSuccessResult[params, function[err, data] {
            if[err] {
                context.fail[err];      
            } else {
                context.succeed[message];      
            }
        }];
    };
    
    // Notify CodePipeline of a failed job
    var putJobFailure = function[message] {
        var params = {
            jobId: jobId,
            failureDetails: {
                message: JSON.stringify[message],
                type: 'JobFailed',
                externalExecutionId: context.awsRequestId
            }
        };
        codepipeline.putJobFailureResult[params, function[err, data] {
            context.fail[message];      
        }];
    };
    
    // Validate the URL passed in UserParameters
    if[!url || url.indexOf['//'] === -1] {
        putJobFailure['The UserParameters field must contain a valid URL address to test, including // or //'];  
        return;
    }
    
    // Helper function to make a HTTP GET request to the page.
    // The helper will test the response and succeed or fail the job accordingly 
    var getPage = function[url, callback] {
        var pageObject = {
            body: '',
            statusCode: 0,
            contains: function[search] {
                return this.body.indexOf[search] > -1;    
            }
        };
        http.get[url, function[response] {
            pageObject.body = '';
            pageObject.statusCode = response.statusCode;
            
            response.on['data', function [chunk] {
                pageObject.body += chunk;
            }];
            
            response.on['end', function [] {
                callback[pageObject];
            }];
            
            response.resume[]; 
        }].on['error', function[error] {
            // Fail the job if our request failed
            putJobFailure[error];    
        }];           
    };
    
    getPage[url, function[returnedPage] {
        try {
            // Check if the HTTP response has a 200 status
            assert[returnedPage.statusCode === 200];
            // Check if the page contains the text "Congratulations"
            // You can change this to check for different text, or add other tests as required
            assert[returnedPage.contains['Congratulations']];  
            
            // Succeed the job
            putJobSuccess["Tests passed."];
        } catch [ex] {
            // If any of the assertions failed then fail the job
            putJobFailure[ex];    
        }
    }];     
};
3 có thể được tìm thấy tại vị trí
var assert = require['assert'];
var AWS = require['aws-sdk'];
var http = require['http'];

exports.handler = function[event, context] {

    var codepipeline = new AWS.CodePipeline[];
    
    // Retrieve the Job ID from the Lambda action
    var jobId = event["CodePipeline.job"].id;
    
    // Retrieve the value of UserParameters from the Lambda action configuration in CodePipeline, in this case a URL which will be
    // health checked by this function.
    var url = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; 
    
    // Notify CodePipeline of a successful job
    var putJobSuccess = function[message] {
        var params = {
            jobId: jobId
        };
        codepipeline.putJobSuccessResult[params, function[err, data] {
            if[err] {
                context.fail[err];      
            } else {
                context.succeed[message];      
            }
        }];
    };
    
    // Notify CodePipeline of a failed job
    var putJobFailure = function[message] {
        var params = {
            jobId: jobId,
            failureDetails: {
                message: JSON.stringify[message],
                type: 'JobFailed',
                externalExecutionId: context.awsRequestId
            }
        };
        codepipeline.putJobFailureResult[params, function[err, data] {
            context.fail[message];      
        }];
    };
    
    // Validate the URL passed in UserParameters
    if[!url || url.indexOf['//'] === -1] {
        putJobFailure['The UserParameters field must contain a valid URL address to test, including // or //'];  
        return;
    }
    
    // Helper function to make a HTTP GET request to the page.
    // The helper will test the response and succeed or fail the job accordingly 
    var getPage = function[url, callback] {
        var pageObject = {
            body: '',
            statusCode: 0,
            contains: function[search] {
                return this.body.indexOf[search] > -1;    
            }
        };
        http.get[url, function[response] {
            pageObject.body = '';
            pageObject.statusCode = response.statusCode;
            
            response.on['data', function [chunk] {
                pageObject.body += chunk;
            }];
            
            response.on['end', function [] {
                callback[pageObject];
            }];
            
            response.resume[]; 
        }].on['error', function[error] {
            // Fail the job if our request failed
            putJobFailure[error];    
        }];           
    };
    
    getPage[url, function[returnedPage] {
        try {
            // Check if the HTTP response has a 200 status
            assert[returnedPage.statusCode === 200];
            // Check if the page contains the text "Congratulations"
            // You can change this to check for different text, or add other tests as required
            assert[returnedPage.contains['Congratulations']];  
            
            // Succeed the job
            putJobSuccess["Tests passed."];
        } catch [ex] {
            // If any of the assertions failed then fail the job
            putJobFailure[ex];    
        }
    }];     
};
4

con trăn

Để tạo một tệp tạm thời trong Python3. 7, chúng ta có thể sử dụng mô-đun

var assert = require['assert'];
var AWS = require['aws-sdk'];
var http = require['http'];

exports.handler = function[event, context] {

    var codepipeline = new AWS.CodePipeline[];
    
    // Retrieve the Job ID from the Lambda action
    var jobId = event["CodePipeline.job"].id;
    
    // Retrieve the value of UserParameters from the Lambda action configuration in CodePipeline, in this case a URL which will be
    // health checked by this function.
    var url = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; 
    
    // Notify CodePipeline of a successful job
    var putJobSuccess = function[message] {
        var params = {
            jobId: jobId
        };
        codepipeline.putJobSuccessResult[params, function[err, data] {
            if[err] {
                context.fail[err];      
            } else {
                context.succeed[message];      
            }
        }];
    };
    
    // Notify CodePipeline of a failed job
    var putJobFailure = function[message] {
        var params = {
            jobId: jobId,
            failureDetails: {
                message: JSON.stringify[message],
                type: 'JobFailed',
                externalExecutionId: context.awsRequestId
            }
        };
        codepipeline.putJobFailureResult[params, function[err, data] {
            context.fail[message];      
        }];
    };
    
    // Validate the URL passed in UserParameters
    if[!url || url.indexOf['//'] === -1] {
        putJobFailure['The UserParameters field must contain a valid URL address to test, including // or //'];  
        return;
    }
    
    // Helper function to make a HTTP GET request to the page.
    // The helper will test the response and succeed or fail the job accordingly 
    var getPage = function[url, callback] {
        var pageObject = {
            body: '',
            statusCode: 0,
            contains: function[search] {
                return this.body.indexOf[search] > -1;    
            }
        };
        http.get[url, function[response] {
            pageObject.body = '';
            pageObject.statusCode = response.statusCode;
            
            response.on['data', function [chunk] {
                pageObject.body += chunk;
            }];
            
            response.on['end', function [] {
                callback[pageObject];
            }];
            
            response.resume[]; 
        }].on['error', function[error] {
            // Fail the job if our request failed
            putJobFailure[error];    
        }];           
    };
    
    getPage[url, function[returnedPage] {
        try {
            // Check if the HTTP response has a 200 status
            assert[returnedPage.statusCode === 200];
            // Check if the page contains the text "Congratulations"
            // You can change this to check for different text, or add other tests as required
            assert[returnedPage.contains['Congratulations']];  
            
            // Succeed the job
            putJobSuccess["Tests passed."];
        } catch [ex] {
            // If any of the assertions failed then fail the job
            putJobFailure[ex];    
        }
    }];     
};
5. Mô-đun này tạo các tệp và thư mục tạm thời. Nó hoạt động trên tất cả các nền tảng được hỗ trợ. , , và là các giao diện cấp cao cung cấp tính năng dọn dẹp tự động và có thể được sử dụng làm trình quản lý bối cảnh. và  là các chức năng cấp thấp hơn yêu cầu dọn dẹp thủ công

>>> import tempfile

# create a temporary file and write some data to it
>>> fp = tempfile.TemporaryFile[]
>>> fp.write[b'Hello world!']
# read data from file
>>> fp.seek[0]
>>> fp.read[]
b'Hello world!'
# close the file, it will be removed
>>> fp.close[]

# create a temporary file using a context manager
>>> with tempfile.TemporaryFile[] as fp:
..     fp.write[b'Hello world!']
..     fp.seek[0]
..     fp.read[]
b'Hello world!'
>>>
# file is now closed and removed

# create a temporary directory using the context manager
>>> with tempfile.TemporaryDirectory[] as tmpdirname:
..     print['created temporary directory', tmpdirname]
>>>
# directory and contents have been removed
Tóm tắt

Tôi đã chỉ cho bạn một số triển khai mẫu để tạo tệp tạm thời trong Java, Groovy và Python. Mẹo này có thể giúp bạn tăng tốc công việc của mình bằng cách nào đó. Mã hóa vui vẻ

AWS Lambda là dịch vụ điện toán cho phép bạn chạy mã mà không cần cung cấp hoặc quản lý máy chủ. Bạn có thể tạo các hàm Lambda và thêm chúng dưới dạng hành động trong quy trình của mình. Vì Lambda cho phép bạn viết các hàm để thực hiện hầu hết mọi tác vụ, nên bạn có thể tùy chỉnh cách thức hoạt động của đường dẫn của mình

Không ghi nhật ký sự kiện JSON mà CodePipeline gửi tới Lambda vì điều này có thể dẫn đến thông tin đăng nhập của người dùng được ghi vào Nhật ký CloudWatch. Vai trò CodePipeline sử dụng sự kiện JSON để chuyển thông tin đăng nhập tạm thời cho Lambda trong trường

var assert = require['assert'];
var AWS = require['aws-sdk'];
var http = require['http'];

exports.handler = function[event, context] {

    var codepipeline = new AWS.CodePipeline[];
    
    // Retrieve the Job ID from the Lambda action
    var jobId = event["CodePipeline.job"].id;
    
    // Retrieve the value of UserParameters from the Lambda action configuration in CodePipeline, in this case a URL which will be
    // health checked by this function.
    var url = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; 
    
    // Notify CodePipeline of a successful job
    var putJobSuccess = function[message] {
        var params = {
            jobId: jobId
        };
        codepipeline.putJobSuccessResult[params, function[err, data] {
            if[err] {
                context.fail[err];      
            } else {
                context.succeed[message];      
            }
        }];
    };
    
    // Notify CodePipeline of a failed job
    var putJobFailure = function[message] {
        var params = {
            jobId: jobId,
            failureDetails: {
                message: JSON.stringify[message],
                type: 'JobFailed',
                externalExecutionId: context.awsRequestId
            }
        };
        codepipeline.putJobFailureResult[params, function[err, data] {
            context.fail[message];      
        }];
    };
    
    // Validate the URL passed in UserParameters
    if[!url || url.indexOf['//'] === -1] {
        putJobFailure['The UserParameters field must contain a valid URL address to test, including // or //'];  
        return;
    }
    
    // Helper function to make a HTTP GET request to the page.
    // The helper will test the response and succeed or fail the job accordingly 
    var getPage = function[url, callback] {
        var pageObject = {
            body: '',
            statusCode: 0,
            contains: function[search] {
                return this.body.indexOf[search] > -1;    
            }
        };
        http.get[url, function[response] {
            pageObject.body = '';
            pageObject.statusCode = response.statusCode;
            
            response.on['data', function [chunk] {
                pageObject.body += chunk;
            }];
            
            response.on['end', function [] {
                callback[pageObject];
            }];
            
            response.resume[]; 
        }].on['error', function[error] {
            // Fail the job if our request failed
            putJobFailure[error];    
        }];           
    };
    
    getPage[url, function[returnedPage] {
        try {
            // Check if the HTTP response has a 200 status
            assert[returnedPage.statusCode === 200];
            // Check if the page contains the text "Congratulations"
            // You can change this to check for different text, or add other tests as required
            assert[returnedPage.contains['Congratulations']];  
            
            // Succeed the job
            putJobSuccess["Tests passed."];
        } catch [ex] {
            // If any of the assertions failed then fail the job
            putJobFailure[ex];    
        }
    }];     
};
6. Đối với một sự kiện ví dụ, xem

Dưới đây là một số cách có thể sử dụng hàm Lambda trong quy trình

  • Để tạo tài nguyên theo yêu cầu trong một giai đoạn của quy trình sử dụng AWS CloudFormation và xóa chúng trong một giai đoạn khác

  • Để triển khai các phiên bản ứng dụng mà không có thời gian ngừng hoạt động trong AWS Elastic Beanstalk với hàm Lambda hoán đổi giá trị CNAME

  • Để triển khai cho các phiên bản Amazon ECS Docker

  • Để sao lưu tài nguyên trước khi xây dựng hoặc triển khai bằng cách tạo ảnh chụp nhanh AMI

  • Để thêm tích hợp với các sản phẩm của bên thứ ba vào quy trình của bạn, chẳng hạn như đăng thông báo lên ứng dụng khách IRC

Việc tạo và chạy các hàm Lambda có thể khiến tài khoản AWS của bạn bị tính phí. Để biết thêm thông tin, xem Giá cả

Chủ đề này giả định rằng bạn đã quen thuộc với AWS CodePipeline và AWS Lambda, đồng thời biết cách tạo quy trình, chức năng cũng như các chính sách và vai trò IAM mà chúng phụ thuộc vào. Chủ đề này chỉ cho bạn cách

  • Tạo một hàm Lambda để kiểm tra xem một trang web đã được triển khai thành công chưa

  • Định cấu hình vai trò thực thi CodePipeline và Lambda cũng như các quyền cần thiết để chạy chức năng như một phần của quy trình

  • Chỉnh sửa quy trình bán hàng để thêm chức năng Lambda dưới dạng hành động

  • Kiểm tra hành động bằng cách phát hành thay đổi theo cách thủ công

Chủ đề này bao gồm các hàm mẫu để minh họa tính linh hoạt khi làm việc với các hàm Lambda trong CodePipeline

    • Tạo hàm Lambda cơ bản để sử dụng với CodePipeline

    • Trả về kết quả thành công hoặc thất bại cho CodePipeline trong liên kết Chi tiết cho hành động

    • Sử dụng tham số người dùng được mã hóa JSON để chuyển nhiều giá trị cấu hình cho hàm [

      var assert = require['assert'];
      var AWS = require['aws-sdk'];
      var http = require['http'];
      
      exports.handler = function[event, context] {
      
          var codepipeline = new AWS.CodePipeline[];
          
          // Retrieve the Job ID from the Lambda action
          var jobId = event["CodePipeline.job"].id;
          
          // Retrieve the value of UserParameters from the Lambda action configuration in CodePipeline, in this case a URL which will be
          // health checked by this function.
          var url = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; 
          
          // Notify CodePipeline of a successful job
          var putJobSuccess = function[message] {
              var params = {
                  jobId: jobId
              };
              codepipeline.putJobSuccessResult[params, function[err, data] {
                  if[err] {
                      context.fail[err];      
                  } else {
                      context.succeed[message];      
                  }
              }];
          };
          
          // Notify CodePipeline of a failed job
          var putJobFailure = function[message] {
              var params = {
                  jobId: jobId,
                  failureDetails: {
                      message: JSON.stringify[message],
                      type: 'JobFailed',
                      externalExecutionId: context.awsRequestId
                  }
              };
              codepipeline.putJobFailureResult[params, function[err, data] {
                  context.fail[message];      
              }];
          };
          
          // Validate the URL passed in UserParameters
          if[!url || url.indexOf['//'] === -1] {
              putJobFailure['The UserParameters field must contain a valid URL address to test, including // or //'];  
              return;
          }
          
          // Helper function to make a HTTP GET request to the page.
          // The helper will test the response and succeed or fail the job accordingly 
          var getPage = function[url, callback] {
              var pageObject = {
                  body: '',
                  statusCode: 0,
                  contains: function[search] {
                      return this.body.indexOf[search] > -1;    
                  }
              };
              http.get[url, function[response] {
                  pageObject.body = '';
                  pageObject.statusCode = response.statusCode;
                  
                  response.on['data', function [chunk] {
                      pageObject.body += chunk;
                  }];
                  
                  response.on['end', function [] {
                      callback[pageObject];
                  }];
                  
                  response.resume[]; 
              }].on['error', function[error] {
                  // Fail the job if our request failed
                  putJobFailure[error];    
              }];           
          };
          
          getPage[url, function[returnedPage] {
              try {
                  // Check if the HTTP response has a 200 status
                  assert[returnedPage.statusCode === 200];
                  // Check if the page contains the text "Congratulations"
                  // You can change this to check for different text, or add other tests as required
                  assert[returnedPage.contains['Congratulations']];  
                  
                  // Succeed the job
                  putJobSuccess["Tests passed."];
              } catch [ex] {
                  // If any of the assertions failed then fail the job
                  putJobFailure[ex];    
              }
          }];     
      };
      7]

    • Tương tác với. zip hiện vật trong thùng hiện vật [

      var assert = require['assert'];
      var AWS = require['aws-sdk'];
      var http = require['http'];
      
      exports.handler = function[event, context] {
      
          var codepipeline = new AWS.CodePipeline[];
          
          // Retrieve the Job ID from the Lambda action
          var jobId = event["CodePipeline.job"].id;
          
          // Retrieve the value of UserParameters from the Lambda action configuration in CodePipeline, in this case a URL which will be
          // health checked by this function.
          var url = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; 
          
          // Notify CodePipeline of a successful job
          var putJobSuccess = function[message] {
              var params = {
                  jobId: jobId
              };
              codepipeline.putJobSuccessResult[params, function[err, data] {
                  if[err] {
                      context.fail[err];      
                  } else {
                      context.succeed[message];      
                  }
              }];
          };
          
          // Notify CodePipeline of a failed job
          var putJobFailure = function[message] {
              var params = {
                  jobId: jobId,
                  failureDetails: {
                      message: JSON.stringify[message],
                      type: 'JobFailed',
                      externalExecutionId: context.awsRequestId
                  }
              };
              codepipeline.putJobFailureResult[params, function[err, data] {
                  context.fail[message];      
              }];
          };
          
          // Validate the URL passed in UserParameters
          if[!url || url.indexOf['//'] === -1] {
              putJobFailure['The UserParameters field must contain a valid URL address to test, including // or //'];  
              return;
          }
          
          // Helper function to make a HTTP GET request to the page.
          // The helper will test the response and succeed or fail the job accordingly 
          var getPage = function[url, callback] {
              var pageObject = {
                  body: '',
                  statusCode: 0,
                  contains: function[search] {
                      return this.body.indexOf[search] > -1;    
                  }
              };
              http.get[url, function[response] {
                  pageObject.body = '';
                  pageObject.statusCode = response.statusCode;
                  
                  response.on['data', function [chunk] {
                      pageObject.body += chunk;
                  }];
                  
                  response.on['end', function [] {
                      callback[pageObject];
                  }];
                  
                  response.resume[]; 
              }].on['error', function[error] {
                  // Fail the job if our request failed
                  putJobFailure[error];    
              }];           
          };
          
          getPage[url, function[returnedPage] {
              try {
                  // Check if the HTTP response has a 200 status
                  assert[returnedPage.statusCode === 200];
                  // Check if the page contains the text "Congratulations"
                  // You can change this to check for different text, or add other tests as required
                  assert[returnedPage.contains['Congratulations']];  
                  
                  // Succeed the job
                  putJobSuccess["Tests passed."];
              } catch [ex] {
                  // If any of the assertions failed then fail the job
                  putJobFailure[ex];    
              }
          }];     
      };
      8]

    • Sử dụng mã thông báo tiếp tục để giám sát quy trình không đồng bộ đang chạy trong thời gian dài [

      var assert = require['assert'];
      var AWS = require['aws-sdk'];
      var http = require['http'];
      
      exports.handler = function[event, context] {
      
          var codepipeline = new AWS.CodePipeline[];
          
          // Retrieve the Job ID from the Lambda action
          var jobId = event["CodePipeline.job"].id;
          
          // Retrieve the value of UserParameters from the Lambda action configuration in CodePipeline, in this case a URL which will be
          // health checked by this function.
          var url = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; 
          
          // Notify CodePipeline of a successful job
          var putJobSuccess = function[message] {
              var params = {
                  jobId: jobId
              };
              codepipeline.putJobSuccessResult[params, function[err, data] {
                  if[err] {
                      context.fail[err];      
                  } else {
                      context.succeed[message];      
                  }
              }];
          };
          
          // Notify CodePipeline of a failed job
          var putJobFailure = function[message] {
              var params = {
                  jobId: jobId,
                  failureDetails: {
                      message: JSON.stringify[message],
                      type: 'JobFailed',
                      externalExecutionId: context.awsRequestId
                  }
              };
              codepipeline.putJobFailureResult[params, function[err, data] {
                  context.fail[message];      
              }];
          };
          
          // Validate the URL passed in UserParameters
          if[!url || url.indexOf['//'] === -1] {
              putJobFailure['The UserParameters field must contain a valid URL address to test, including // or //'];  
              return;
          }
          
          // Helper function to make a HTTP GET request to the page.
          // The helper will test the response and succeed or fail the job accordingly 
          var getPage = function[url, callback] {
              var pageObject = {
                  body: '',
                  statusCode: 0,
                  contains: function[search] {
                      return this.body.indexOf[search] > -1;    
                  }
              };
              http.get[url, function[response] {
                  pageObject.body = '';
                  pageObject.statusCode = response.statusCode;
                  
                  response.on['data', function [chunk] {
                      pageObject.body += chunk;
                  }];
                  
                  response.on['end', function [] {
                      callback[pageObject];
                  }];
                  
                  response.resume[]; 
              }].on['error', function[error] {
                  // Fail the job if our request failed
                  putJobFailure[error];    
              }];           
          };
          
          getPage[url, function[returnedPage] {
              try {
                  // Check if the HTTP response has a 200 status
                  assert[returnedPage.statusCode === 200];
                  // Check if the page contains the text "Congratulations"
                  // You can change this to check for different text, or add other tests as required
                  assert[returnedPage.contains['Congratulations']];  
                  
                  // Succeed the job
                  putJobSuccess["Tests passed."];
              } catch [ex] {
                  // If any of the assertions failed then fail the job
                  putJobFailure[ex];    
              }
          }];     
      };
      9]. Điều này cho phép hành động tiếp tục và chức năng thành công ngay cả khi vượt quá thời gian chạy mười lăm phút [giới hạn trong Lambda]

Mỗi chức năng mẫu bao gồm thông tin về các quyền mà bạn phải thêm vào vai trò. Để biết thông tin về giới hạn trong AWS Lambda, hãy xem Giới hạn trong Hướng dẫn dành cho nhà phát triển AWS Lambda

Mã mẫu, vai trò và chính sách có trong chủ đề này chỉ là ví dụ và được cung cấp nguyên trạng

Bước 1. Tạo một đường ống dẫn

Trong bước này, bạn tạo một đường dẫn để sau này bạn thêm hàm Lambda vào đó. Đây là cùng một quy trình bạn đã tạo trong hướng dẫn CodePipeline. Nếu đường dẫn đó vẫn được định cấu hình cho tài khoản của bạn và ở cùng Khu vực mà bạn định tạo hàm Lambda, thì bạn có thể bỏ qua bước này

Để tạo đường ống

  1. Thực hiện theo ba bước đầu tiên trong Hướng dẫn. Tạo quy trình đơn giản [bộ chứa S3] để tạo bộ chứa Amazon S3, tài nguyên CodeDeploy và quy trình hai giai đoạn. Chọn tùy chọn Amazon Linux cho các loại phiên bản của bạn. Bạn có thể sử dụng bất kỳ tên nào bạn muốn cho đường dẫn, nhưng các bước trong chủ đề này sử dụng MyLambdaTestPipeline

  2. Trên trang trạng thái cho quy trình của bạn, trong hành động CodeDeploy, hãy chọn Chi tiết. Trên trang chi tiết triển khai cho nhóm triển khai, hãy chọn một ID phiên bản từ danh sách

  3. Ví dụ: trong bảng điều khiển Amazon EC2, trên tab Chi tiết, hãy sao chép địa chỉ IP trong Địa chỉ IPv4 công khai [ví dụ:

    var assert = require['assert'];
    var AWS = require['aws-sdk'];
    var http = require['http'];
    
    exports.handler = function[event, context] {
    
        var codepipeline = new AWS.CodePipeline[];
        
        // Retrieve the Job ID from the Lambda action
        var jobId = event["CodePipeline.job"].id;
        
        // Retrieve the value of UserParameters from the Lambda action configuration in CodePipeline, in this case a URL which will be
        // health checked by this function.
        var url = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; 
        
        // Notify CodePipeline of a successful job
        var putJobSuccess = function[message] {
            var params = {
                jobId: jobId
            };
            codepipeline.putJobSuccessResult[params, function[err, data] {
                if[err] {
                    context.fail[err];      
                } else {
                    context.succeed[message];      
                }
            }];
        };
        
        // Notify CodePipeline of a failed job
        var putJobFailure = function[message] {
            var params = {
                jobId: jobId,
                failureDetails: {
                    message: JSON.stringify[message],
                    type: 'JobFailed',
                    externalExecutionId: context.awsRequestId
                }
            };
            codepipeline.putJobFailureResult[params, function[err, data] {
                context.fail[message];      
            }];
        };
        
        // Validate the URL passed in UserParameters
        if[!url || url.indexOf['//'] === -1] {
            putJobFailure['The UserParameters field must contain a valid URL address to test, including // or //'];  
            return;
        }
        
        // Helper function to make a HTTP GET request to the page.
        // The helper will test the response and succeed or fail the job accordingly 
        var getPage = function[url, callback] {
            var pageObject = {
                body: '',
                statusCode: 0,
                contains: function[search] {
                    return this.body.indexOf[search] > -1;    
                }
            };
            http.get[url, function[response] {
                pageObject.body = '';
                pageObject.statusCode = response.statusCode;
                
                response.on['data', function [chunk] {
                    pageObject.body += chunk;
                }];
                
                response.on['end', function [] {
                    callback[pageObject];
                }];
                
                response.resume[]; 
            }].on['error', function[error] {
                // Fail the job if our request failed
                putJobFailure[error];    
            }];           
        };
        
        getPage[url, function[returnedPage] {
            try {
                // Check if the HTTP response has a 200 status
                assert[returnedPage.statusCode === 200];
                // Check if the page contains the text "Congratulations"
                // You can change this to check for different text, or add other tests as required
                assert[returnedPage.contains['Congratulations']];  
                
                // Succeed the job
                putJobSuccess["Tests passed."];
            } catch [ex] {
                // If any of the assertions failed then fail the job
                putJobFailure[ex];    
            }
        }];     
    };
    0]. Bạn sử dụng địa chỉ này làm đích của hàm trong AWS Lambda

Chính sách vai trò dịch vụ mặc định cho CodePipeline bao gồm các quyền Lambda cần thiết để gọi chức năng. Tuy nhiên, nếu bạn đã sửa đổi vai trò dịch vụ mặc định hoặc chọn một vai trò khác, hãy đảm bảo rằng chính sách dành cho vai trò đó cho phép các quyền

var assert = require['assert'];
var AWS = require['aws-sdk'];
var http = require['http'];

exports.handler = function[event, context] {

    var codepipeline = new AWS.CodePipeline[];
    
    // Retrieve the Job ID from the Lambda action
    var jobId = event["CodePipeline.job"].id;
    
    // Retrieve the value of UserParameters from the Lambda action configuration in CodePipeline, in this case a URL which will be
    // health checked by this function.
    var url = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; 
    
    // Notify CodePipeline of a successful job
    var putJobSuccess = function[message] {
        var params = {
            jobId: jobId
        };
        codepipeline.putJobSuccessResult[params, function[err, data] {
            if[err] {
                context.fail[err];      
            } else {
                context.succeed[message];      
            }
        }];
    };
    
    // Notify CodePipeline of a failed job
    var putJobFailure = function[message] {
        var params = {
            jobId: jobId,
            failureDetails: {
                message: JSON.stringify[message],
                type: 'JobFailed',
                externalExecutionId: context.awsRequestId
            }
        };
        codepipeline.putJobFailureResult[params, function[err, data] {
            context.fail[message];      
        }];
    };
    
    // Validate the URL passed in UserParameters
    if[!url || url.indexOf['//'] === -1] {
        putJobFailure['The UserParameters field must contain a valid URL address to test, including // or //'];  
        return;
    }
    
    // Helper function to make a HTTP GET request to the page.
    // The helper will test the response and succeed or fail the job accordingly 
    var getPage = function[url, callback] {
        var pageObject = {
            body: '',
            statusCode: 0,
            contains: function[search] {
                return this.body.indexOf[search] > -1;    
            }
        };
        http.get[url, function[response] {
            pageObject.body = '';
            pageObject.statusCode = response.statusCode;
            
            response.on['data', function [chunk] {
                pageObject.body += chunk;
            }];
            
            response.on['end', function [] {
                callback[pageObject];
            }];
            
            response.resume[]; 
        }].on['error', function[error] {
            // Fail the job if our request failed
            putJobFailure[error];    
        }];           
    };
    
    getPage[url, function[returnedPage] {
        try {
            // Check if the HTTP response has a 200 status
            assert[returnedPage.statusCode === 200];
            // Check if the page contains the text "Congratulations"
            // You can change this to check for different text, or add other tests as required
            assert[returnedPage.contains['Congratulations']];  
            
            // Succeed the job
            putJobSuccess["Tests passed."];
        } catch [ex] {
            // If any of the assertions failed then fail the job
            putJobFailure[ex];    
        }
    }];     
};
1 và
var assert = require['assert'];
var AWS = require['aws-sdk'];
var http = require['http'];

exports.handler = function[event, context] {

    var codepipeline = new AWS.CodePipeline[];
    
    // Retrieve the Job ID from the Lambda action
    var jobId = event["CodePipeline.job"].id;
    
    // Retrieve the value of UserParameters from the Lambda action configuration in CodePipeline, in this case a URL which will be
    // health checked by this function.
    var url = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; 
    
    // Notify CodePipeline of a successful job
    var putJobSuccess = function[message] {
        var params = {
            jobId: jobId
        };
        codepipeline.putJobSuccessResult[params, function[err, data] {
            if[err] {
                context.fail[err];      
            } else {
                context.succeed[message];      
            }
        }];
    };
    
    // Notify CodePipeline of a failed job
    var putJobFailure = function[message] {
        var params = {
            jobId: jobId,
            failureDetails: {
                message: JSON.stringify[message],
                type: 'JobFailed',
                externalExecutionId: context.awsRequestId
            }
        };
        codepipeline.putJobFailureResult[params, function[err, data] {
            context.fail[message];      
        }];
    };
    
    // Validate the URL passed in UserParameters
    if[!url || url.indexOf['//'] === -1] {
        putJobFailure['The UserParameters field must contain a valid URL address to test, including // or //'];  
        return;
    }
    
    // Helper function to make a HTTP GET request to the page.
    // The helper will test the response and succeed or fail the job accordingly 
    var getPage = function[url, callback] {
        var pageObject = {
            body: '',
            statusCode: 0,
            contains: function[search] {
                return this.body.indexOf[search] > -1;    
            }
        };
        http.get[url, function[response] {
            pageObject.body = '';
            pageObject.statusCode = response.statusCode;
            
            response.on['data', function [chunk] {
                pageObject.body += chunk;
            }];
            
            response.on['end', function [] {
                callback[pageObject];
            }];
            
            response.resume[]; 
        }].on['error', function[error] {
            // Fail the job if our request failed
            putJobFailure[error];    
        }];           
    };
    
    getPage[url, function[returnedPage] {
        try {
            // Check if the HTTP response has a 200 status
            assert[returnedPage.statusCode === 200];
            // Check if the page contains the text "Congratulations"
            // You can change this to check for different text, or add other tests as required
            assert[returnedPage.contains['Congratulations']];  
            
            // Succeed the job
            putJobSuccess["Tests passed."];
        } catch [ex] {
            // If any of the assertions failed then fail the job
            putJobFailure[ex];    
        }
    }];     
};
2. Mặt khác, các đường ống bao gồm các hành động Lambda không thành công

Bước 2. Tạo hàm Lambda

Trong bước này, bạn tạo một hàm Lambda để thực hiện yêu cầu HTTP và kiểm tra một dòng văn bản trên trang web. Trong bước này, bạn cũng phải tạo chính sách IAM và vai trò thực thi Lambda. Để biết thêm thông tin, hãy xem trong Hướng dẫn dành cho nhà phát triển AWS Lambda

Để tạo vai trò thực thi

  1. Đăng nhập vào Bảng điều khiển quản lý AWS và mở bảng điều khiển IAM tại https. // bảng điều khiển. aws. amazon. com/iam/

  2. Chọn Chính sách, rồi chọn Tạo Chính sách. Chọn tab JSON, sau đó dán chính sách sau vào trường

    {
      "Version": "2012-10-17", 
      "Statement": [
        {
          "Action": [ 
            "logs:*"
          ],
          "Effect": "Allow", 
          "Resource": "arn:aws:logs:*:*:*"
        },
        {
          "Action": [
            "codepipeline:PutJobSuccessResult",
            "codepipeline:PutJobFailureResult"
            ],
            "Effect": "Allow",
            "Resource": "*"
         }
      ]
    } 
  3. Chọn Đánh giá chính sách

  4. Trên trang Xem lại chính sách, trong Tên, hãy nhập tên cho chính sách [ví dụ:

    var assert = require['assert'];
    var AWS = require['aws-sdk'];
    var http = require['http'];
    
    exports.handler = function[event, context] {
    
        var codepipeline = new AWS.CodePipeline[];
        
        // Retrieve the Job ID from the Lambda action
        var jobId = event["CodePipeline.job"].id;
        
        // Retrieve the value of UserParameters from the Lambda action configuration in CodePipeline, in this case a URL which will be
        // health checked by this function.
        var url = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; 
        
        // Notify CodePipeline of a successful job
        var putJobSuccess = function[message] {
            var params = {
                jobId: jobId
            };
            codepipeline.putJobSuccessResult[params, function[err, data] {
                if[err] {
                    context.fail[err];      
                } else {
                    context.succeed[message];      
                }
            }];
        };
        
        // Notify CodePipeline of a failed job
        var putJobFailure = function[message] {
            var params = {
                jobId: jobId,
                failureDetails: {
                    message: JSON.stringify[message],
                    type: 'JobFailed',
                    externalExecutionId: context.awsRequestId
                }
            };
            codepipeline.putJobFailureResult[params, function[err, data] {
                context.fail[message];      
            }];
        };
        
        // Validate the URL passed in UserParameters
        if[!url || url.indexOf['//'] === -1] {
            putJobFailure['The UserParameters field must contain a valid URL address to test, including // or //'];  
            return;
        }
        
        // Helper function to make a HTTP GET request to the page.
        // The helper will test the response and succeed or fail the job accordingly 
        var getPage = function[url, callback] {
            var pageObject = {
                body: '',
                statusCode: 0,
                contains: function[search] {
                    return this.body.indexOf[search] > -1;    
                }
            };
            http.get[url, function[response] {
                pageObject.body = '';
                pageObject.statusCode = response.statusCode;
                
                response.on['data', function [chunk] {
                    pageObject.body += chunk;
                }];
                
                response.on['end', function [] {
                    callback[pageObject];
                }];
                
                response.resume[]; 
            }].on['error', function[error] {
                // Fail the job if our request failed
                putJobFailure[error];    
            }];           
        };
        
        getPage[url, function[returnedPage] {
            try {
                // Check if the HTTP response has a 200 status
                assert[returnedPage.statusCode === 200];
                // Check if the page contains the text "Congratulations"
                // You can change this to check for different text, or add other tests as required
                assert[returnedPage.contains['Congratulations']];  
                
                // Succeed the job
                putJobSuccess["Tests passed."];
            } catch [ex] {
                // If any of the assertions failed then fail the job
                putJobFailure[ex];    
            }
        }];     
    };
    3]. Trong Mô tả, nhập
    var assert = require['assert'];
    var AWS = require['aws-sdk'];
    var http = require['http'];
    
    exports.handler = function[event, context] {
    
        var codepipeline = new AWS.CodePipeline[];
        
        // Retrieve the Job ID from the Lambda action
        var jobId = event["CodePipeline.job"].id;
        
        // Retrieve the value of UserParameters from the Lambda action configuration in CodePipeline, in this case a URL which will be
        // health checked by this function.
        var url = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; 
        
        // Notify CodePipeline of a successful job
        var putJobSuccess = function[message] {
            var params = {
                jobId: jobId
            };
            codepipeline.putJobSuccessResult[params, function[err, data] {
                if[err] {
                    context.fail[err];      
                } else {
                    context.succeed[message];      
                }
            }];
        };
        
        // Notify CodePipeline of a failed job
        var putJobFailure = function[message] {
            var params = {
                jobId: jobId,
                failureDetails: {
                    message: JSON.stringify[message],
                    type: 'JobFailed',
                    externalExecutionId: context.awsRequestId
                }
            };
            codepipeline.putJobFailureResult[params, function[err, data] {
                context.fail[message];      
            }];
        };
        
        // Validate the URL passed in UserParameters
        if[!url || url.indexOf['//'] === -1] {
            putJobFailure['The UserParameters field must contain a valid URL address to test, including // or //'];  
            return;
        }
        
        // Helper function to make a HTTP GET request to the page.
        // The helper will test the response and succeed or fail the job accordingly 
        var getPage = function[url, callback] {
            var pageObject = {
                body: '',
                statusCode: 0,
                contains: function[search] {
                    return this.body.indexOf[search] > -1;    
                }
            };
            http.get[url, function[response] {
                pageObject.body = '';
                pageObject.statusCode = response.statusCode;
                
                response.on['data', function [chunk] {
                    pageObject.body += chunk;
                }];
                
                response.on['end', function [] {
                    callback[pageObject];
                }];
                
                response.resume[]; 
            }].on['error', function[error] {
                // Fail the job if our request failed
                putJobFailure[error];    
            }];           
        };
        
        getPage[url, function[returnedPage] {
            try {
                // Check if the HTTP response has a 200 status
                assert[returnedPage.statusCode === 200];
                // Check if the page contains the text "Congratulations"
                // You can change this to check for different text, or add other tests as required
                assert[returnedPage.contains['Congratulations']];  
                
                // Succeed the job
                putJobSuccess["Tests passed."];
            } catch [ex] {
                // If any of the assertions failed then fail the job
                putJobFailure[ex];    
            }
        }];     
    };
    4

    Chọn Tạo chính sách

    Đây là những quyền tối thiểu cần thiết để một chức năng Lambda có thể tương tác với CodePipeline và Amazon CloudWatch. Nếu muốn mở rộng chính sách này để cho phép các hàm tương tác với các tài nguyên AWS khác, bạn nên sửa đổi chính sách này để cho phép các hành động mà các hàm Lambda đó yêu cầu

  5. Trên trang bảng điều khiển chính sách, chọn Vai trò rồi chọn Tạo vai trò

  6. Trên trang Tạo vai trò, chọn dịch vụ AWS. Chọn Lambda rồi chọn Tiếp theo. Quyền

  7. Trên trang Đính kèm chính sách quyền, chọn hộp kiểm bên cạnh CodePipelineLambdaExecPolicy, sau đó chọn Tiếp theo. thẻ. Chọn tiếp theo. Ôn tập

  8. Trên trang Xem lại, trong Tên vai trò, hãy nhập tên rồi chọn Tạo vai trò

Cách tạo hàm Lambda mẫu để sử dụng với CodePipeline

  1. Đăng nhập vào Bảng điều khiển quản lý AWS và mở bảng điều khiển AWS Lambda tại https. // bảng điều khiển. aws. amazon. com/lambda/

  2. Trên trang Chức năng, chọn Tạo chức năng

    Nếu bạn thấy trang Chào mừng thay vì trang Lambda, hãy chọn Bắt đầu ngay

  3. Trên trang Tạo chức năng, chọn Tác giả từ đầu. Trong Tên hàm, hãy nhập tên cho hàm Lambda của bạn [ví dụ:

    var assert = require['assert'];
    var AWS = require['aws-sdk'];
    var http = require['http'];
    
    exports.handler = function[event, context] {
    
        var codepipeline = new AWS.CodePipeline[];
        
        // Retrieve the Job ID from the Lambda action
        var jobId = event["CodePipeline.job"].id;
        
        // Retrieve the value of UserParameters from the Lambda action configuration in CodePipeline, in this case a URL which will be
        // health checked by this function.
        var url = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; 
        
        // Notify CodePipeline of a successful job
        var putJobSuccess = function[message] {
            var params = {
                jobId: jobId
            };
            codepipeline.putJobSuccessResult[params, function[err, data] {
                if[err] {
                    context.fail[err];      
                } else {
                    context.succeed[message];      
                }
            }];
        };
        
        // Notify CodePipeline of a failed job
        var putJobFailure = function[message] {
            var params = {
                jobId: jobId,
                failureDetails: {
                    message: JSON.stringify[message],
                    type: 'JobFailed',
                    externalExecutionId: context.awsRequestId
                }
            };
            codepipeline.putJobFailureResult[params, function[err, data] {
                context.fail[message];      
            }];
        };
        
        // Validate the URL passed in UserParameters
        if[!url || url.indexOf['//'] === -1] {
            putJobFailure['The UserParameters field must contain a valid URL address to test, including // or //'];  
            return;
        }
        
        // Helper function to make a HTTP GET request to the page.
        // The helper will test the response and succeed or fail the job accordingly 
        var getPage = function[url, callback] {
            var pageObject = {
                body: '',
                statusCode: 0,
                contains: function[search] {
                    return this.body.indexOf[search] > -1;    
                }
            };
            http.get[url, function[response] {
                pageObject.body = '';
                pageObject.statusCode = response.statusCode;
                
                response.on['data', function [chunk] {
                    pageObject.body += chunk;
                }];
                
                response.on['end', function [] {
                    callback[pageObject];
                }];
                
                response.resume[]; 
            }].on['error', function[error] {
                // Fail the job if our request failed
                putJobFailure[error];    
            }];           
        };
        
        getPage[url, function[returnedPage] {
            try {
                // Check if the HTTP response has a 200 status
                assert[returnedPage.statusCode === 200];
                // Check if the page contains the text "Congratulations"
                // You can change this to check for different text, or add other tests as required
                assert[returnedPage.contains['Congratulations']];  
                
                // Succeed the job
                putJobSuccess["Tests passed."];
            } catch [ex] {
                // If any of the assertions failed then fail the job
                putJobFailure[ex];    
            }
        }];     
    };
    5]. Trong Thời gian chạy, chọn Nút. js 14. x

  4. Trong Vai trò, hãy chọn Chọn một vai trò hiện có. Trong Vai trò hiện có, hãy chọn vai trò của bạn rồi chọn Tạo chức năng

    Trang chi tiết cho chức năng đã tạo của bạn sẽ mở ra

  5. Copy đoạn mã sau vào ô Mã chức năng

    Đối tượng sự kiện, trong CodePipeline. phím công việc, chứa các chi tiết công việc. Để biết ví dụ đầy đủ về sự kiện JSON mà CodePipeline trả về Lambda, hãy xem

    var assert = require['assert'];
    var AWS = require['aws-sdk'];
    var http = require['http'];
    
    exports.handler = function[event, context] {
    
        var codepipeline = new AWS.CodePipeline[];
        
        // Retrieve the Job ID from the Lambda action
        var jobId = event["CodePipeline.job"].id;
        
        // Retrieve the value of UserParameters from the Lambda action configuration in CodePipeline, in this case a URL which will be
        // health checked by this function.
        var url = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; 
        
        // Notify CodePipeline of a successful job
        var putJobSuccess = function[message] {
            var params = {
                jobId: jobId
            };
            codepipeline.putJobSuccessResult[params, function[err, data] {
                if[err] {
                    context.fail[err];      
                } else {
                    context.succeed[message];      
                }
            }];
        };
        
        // Notify CodePipeline of a failed job
        var putJobFailure = function[message] {
            var params = {
                jobId: jobId,
                failureDetails: {
                    message: JSON.stringify[message],
                    type: 'JobFailed',
                    externalExecutionId: context.awsRequestId
                }
            };
            codepipeline.putJobFailureResult[params, function[err, data] {
                context.fail[message];      
            }];
        };
        
        // Validate the URL passed in UserParameters
        if[!url || url.indexOf['//'] === -1] {
            putJobFailure['The UserParameters field must contain a valid URL address to test, including // or //'];  
            return;
        }
        
        // Helper function to make a HTTP GET request to the page.
        // The helper will test the response and succeed or fail the job accordingly 
        var getPage = function[url, callback] {
            var pageObject = {
                body: '',
                statusCode: 0,
                contains: function[search] {
                    return this.body.indexOf[search] > -1;    
                }
            };
            http.get[url, function[response] {
                pageObject.body = '';
                pageObject.statusCode = response.statusCode;
                
                response.on['data', function [chunk] {
                    pageObject.body += chunk;
                }];
                
                response.on['end', function [] {
                    callback[pageObject];
                }];
                
                response.resume[]; 
            }].on['error', function[error] {
                // Fail the job if our request failed
                putJobFailure[error];    
            }];           
        };
        
        getPage[url, function[returnedPage] {
            try {
                // Check if the HTTP response has a 200 status
                assert[returnedPage.statusCode === 200];
                // Check if the page contains the text "Congratulations"
                // You can change this to check for different text, or add other tests as required
                assert[returnedPage.contains['Congratulations']];  
                
                // Succeed the job
                putJobSuccess["Tests passed."];
            } catch [ex] {
                // If any of the assertions failed then fail the job
                putJobFailure[ex];    
            }
        }];     
    };
  6. Để Trình xử lý ở giá trị mặc định và để Vai trò ở giá trị mặc định,

    var assert = require['assert'];
    var AWS = require['aws-sdk'];
    var http = require['http'];
    
    exports.handler = function[event, context] {
    
        var codepipeline = new AWS.CodePipeline[];
        
        // Retrieve the Job ID from the Lambda action
        var jobId = event["CodePipeline.job"].id;
        
        // Retrieve the value of UserParameters from the Lambda action configuration in CodePipeline, in this case a URL which will be
        // health checked by this function.
        var url = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; 
        
        // Notify CodePipeline of a successful job
        var putJobSuccess = function[message] {
            var params = {
                jobId: jobId
            };
            codepipeline.putJobSuccessResult[params, function[err, data] {
                if[err] {
                    context.fail[err];      
                } else {
                    context.succeed[message];      
                }
            }];
        };
        
        // Notify CodePipeline of a failed job
        var putJobFailure = function[message] {
            var params = {
                jobId: jobId,
                failureDetails: {
                    message: JSON.stringify[message],
                    type: 'JobFailed',
                    externalExecutionId: context.awsRequestId
                }
            };
            codepipeline.putJobFailureResult[params, function[err, data] {
                context.fail[message];      
            }];
        };
        
        // Validate the URL passed in UserParameters
        if[!url || url.indexOf['//'] === -1] {
            putJobFailure['The UserParameters field must contain a valid URL address to test, including // or //'];  
            return;
        }
        
        // Helper function to make a HTTP GET request to the page.
        // The helper will test the response and succeed or fail the job accordingly 
        var getPage = function[url, callback] {
            var pageObject = {
                body: '',
                statusCode: 0,
                contains: function[search] {
                    return this.body.indexOf[search] > -1;    
                }
            };
            http.get[url, function[response] {
                pageObject.body = '';
                pageObject.statusCode = response.statusCode;
                
                response.on['data', function [chunk] {
                    pageObject.body += chunk;
                }];
                
                response.on['end', function [] {
                    callback[pageObject];
                }];
                
                response.resume[]; 
            }].on['error', function[error] {
                // Fail the job if our request failed
                putJobFailure[error];    
            }];           
        };
        
        getPage[url, function[returnedPage] {
            try {
                // Check if the HTTP response has a 200 status
                assert[returnedPage.statusCode === 200];
                // Check if the page contains the text "Congratulations"
                // You can change this to check for different text, or add other tests as required
                assert[returnedPage.contains['Congratulations']];  
                
                // Succeed the job
                putJobSuccess["Tests passed."];
            } catch [ex] {
                // If any of the assertions failed then fail the job
                putJobFailure[ex];    
            }
        }];     
    };
    6

  7. Trong Cài đặt cơ bản, đối với Thời gian chờ, hãy nhập

    var assert = require['assert'];
    var AWS = require['aws-sdk'];
    var http = require['http'];
    
    exports.handler = function[event, context] {
    
        var codepipeline = new AWS.CodePipeline[];
        
        // Retrieve the Job ID from the Lambda action
        var jobId = event["CodePipeline.job"].id;
        
        // Retrieve the value of UserParameters from the Lambda action configuration in CodePipeline, in this case a URL which will be
        // health checked by this function.
        var url = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; 
        
        // Notify CodePipeline of a successful job
        var putJobSuccess = function[message] {
            var params = {
                jobId: jobId
            };
            codepipeline.putJobSuccessResult[params, function[err, data] {
                if[err] {
                    context.fail[err];      
                } else {
                    context.succeed[message];      
                }
            }];
        };
        
        // Notify CodePipeline of a failed job
        var putJobFailure = function[message] {
            var params = {
                jobId: jobId,
                failureDetails: {
                    message: JSON.stringify[message],
                    type: 'JobFailed',
                    externalExecutionId: context.awsRequestId
                }
            };
            codepipeline.putJobFailureResult[params, function[err, data] {
                context.fail[message];      
            }];
        };
        
        // Validate the URL passed in UserParameters
        if[!url || url.indexOf['//'] === -1] {
            putJobFailure['The UserParameters field must contain a valid URL address to test, including // or //'];  
            return;
        }
        
        // Helper function to make a HTTP GET request to the page.
        // The helper will test the response and succeed or fail the job accordingly 
        var getPage = function[url, callback] {
            var pageObject = {
                body: '',
                statusCode: 0,
                contains: function[search] {
                    return this.body.indexOf[search] > -1;    
                }
            };
            http.get[url, function[response] {
                pageObject.body = '';
                pageObject.statusCode = response.statusCode;
                
                response.on['data', function [chunk] {
                    pageObject.body += chunk;
                }];
                
                response.on['end', function [] {
                    callback[pageObject];
                }];
                
                response.resume[]; 
            }].on['error', function[error] {
                // Fail the job if our request failed
                putJobFailure[error];    
            }];           
        };
        
        getPage[url, function[returnedPage] {
            try {
                // Check if the HTTP response has a 200 status
                assert[returnedPage.statusCode === 200];
                // Check if the page contains the text "Congratulations"
                // You can change this to check for different text, or add other tests as required
                assert[returnedPage.contains['Congratulations']];  
                
                // Succeed the job
                putJobSuccess["Tests passed."];
            } catch [ex] {
                // If any of the assertions failed then fail the job
                putJobFailure[ex];    
            }
        }];     
    };
    7 giây

  8. Chọn Lưu

Bước 3. Thêm hàm Lambda vào quy trình trong bảng điều khiển CodePipeline

Trong bước này, bạn thêm một giai đoạn mới vào quy trình bán hàng của mình, sau đó thêm một hành động Lambda để gọi hàm của bạn đến giai đoạn đó

Để thêm một giai đoạn

  1. Đăng nhập vào Bảng điều khiển quản lý AWS và mở bảng điều khiển CodePipeline tại http. // bảng điều khiển. aws. amazon. com/codesuite/codepipeline/home

  2. Trên trang Chào mừng, hãy chọn quy trình bạn đã tạo

  3. Trên trang xem quy trình, chọn Chỉnh sửa

  4. Trên trang Chỉnh sửa, chọn + Thêm giai đoạn để thêm giai đoạn sau giai đoạn triển khai bằng hành động CodeDeploy. Nhập tên cho giai đoạn [ví dụ:

    var assert = require['assert'];
    var AWS = require['aws-sdk'];
    var http = require['http'];
    
    exports.handler = function[event, context] {
    
        var codepipeline = new AWS.CodePipeline[];
        
        // Retrieve the Job ID from the Lambda action
        var jobId = event["CodePipeline.job"].id;
        
        // Retrieve the value of UserParameters from the Lambda action configuration in CodePipeline, in this case a URL which will be
        // health checked by this function.
        var url = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; 
        
        // Notify CodePipeline of a successful job
        var putJobSuccess = function[message] {
            var params = {
                jobId: jobId
            };
            codepipeline.putJobSuccessResult[params, function[err, data] {
                if[err] {
                    context.fail[err];      
                } else {
                    context.succeed[message];      
                }
            }];
        };
        
        // Notify CodePipeline of a failed job
        var putJobFailure = function[message] {
            var params = {
                jobId: jobId,
                failureDetails: {
                    message: JSON.stringify[message],
                    type: 'JobFailed',
                    externalExecutionId: context.awsRequestId
                }
            };
            codepipeline.putJobFailureResult[params, function[err, data] {
                context.fail[message];      
            }];
        };
        
        // Validate the URL passed in UserParameters
        if[!url || url.indexOf['//'] === -1] {
            putJobFailure['The UserParameters field must contain a valid URL address to test, including // or //'];  
            return;
        }
        
        // Helper function to make a HTTP GET request to the page.
        // The helper will test the response and succeed or fail the job accordingly 
        var getPage = function[url, callback] {
            var pageObject = {
                body: '',
                statusCode: 0,
                contains: function[search] {
                    return this.body.indexOf[search] > -1;    
                }
            };
            http.get[url, function[response] {
                pageObject.body = '';
                pageObject.statusCode = response.statusCode;
                
                response.on['data', function [chunk] {
                    pageObject.body += chunk;
                }];
                
                response.on['end', function [] {
                    callback[pageObject];
                }];
                
                response.resume[]; 
            }].on['error', function[error] {
                // Fail the job if our request failed
                putJobFailure[error];    
            }];           
        };
        
        getPage[url, function[returnedPage] {
            try {
                // Check if the HTTP response has a 200 status
                assert[returnedPage.statusCode === 200];
                // Check if the page contains the text "Congratulations"
                // You can change this to check for different text, or add other tests as required
                assert[returnedPage.contains['Congratulations']];  
                
                // Succeed the job
                putJobSuccess["Tests passed."];
            } catch [ex] {
                // If any of the assertions failed then fail the job
                putJobFailure[ex];    
            }
        }];     
    };
    8] rồi chọn Thêm giai đoạn

    Bạn cũng có thể chọn thêm hành động Lambda của mình vào một giai đoạn hiện có. Vì mục đích trình diễn, chúng tôi sẽ thêm chức năng Lambda làm hành động duy nhất trong một giai đoạn để cho phép bạn dễ dàng xem tiến trình của nó khi các thành phần tạo tác tiến triển thông qua một quy trình

  5. Chọn + Thêm nhóm hành động. Trong Chỉnh sửa hành động, trong Tên hành động, hãy nhập tên cho hành động Lambda của bạn [ví dụ:

    var assert = require['assert'];
    var AWS = require['aws-sdk'];
    var http = require['http'];
    
    exports.handler = function[event, context] {
    
        var codepipeline = new AWS.CodePipeline[];
        
        // Retrieve the Job ID from the Lambda action
        var jobId = event["CodePipeline.job"].id;
        
        // Retrieve the value of UserParameters from the Lambda action configuration in CodePipeline, in this case a URL which will be
        // health checked by this function.
        var url = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; 
        
        // Notify CodePipeline of a successful job
        var putJobSuccess = function[message] {
            var params = {
                jobId: jobId
            };
            codepipeline.putJobSuccessResult[params, function[err, data] {
                if[err] {
                    context.fail[err];      
                } else {
                    context.succeed[message];      
                }
            }];
        };
        
        // Notify CodePipeline of a failed job
        var putJobFailure = function[message] {
            var params = {
                jobId: jobId,
                failureDetails: {
                    message: JSON.stringify[message],
                    type: 'JobFailed',
                    externalExecutionId: context.awsRequestId
                }
            };
            codepipeline.putJobFailureResult[params, function[err, data] {
                context.fail[message];      
            }];
        };
        
        // Validate the URL passed in UserParameters
        if[!url || url.indexOf['//'] === -1] {
            putJobFailure['The UserParameters field must contain a valid URL address to test, including // or //'];  
            return;
        }
        
        // Helper function to make a HTTP GET request to the page.
        // The helper will test the response and succeed or fail the job accordingly 
        var getPage = function[url, callback] {
            var pageObject = {
                body: '',
                statusCode: 0,
                contains: function[search] {
                    return this.body.indexOf[search] > -1;    
                }
            };
            http.get[url, function[response] {
                pageObject.body = '';
                pageObject.statusCode = response.statusCode;
                
                response.on['data', function [chunk] {
                    pageObject.body += chunk;
                }];
                
                response.on['end', function [] {
                    callback[pageObject];
                }];
                
                response.resume[]; 
            }].on['error', function[error] {
                // Fail the job if our request failed
                putJobFailure[error];    
            }];           
        };
        
        getPage[url, function[returnedPage] {
            try {
                // Check if the HTTP response has a 200 status
                assert[returnedPage.statusCode === 200];
                // Check if the page contains the text "Congratulations"
                // You can change this to check for different text, or add other tests as required
                assert[returnedPage.contains['Congratulations']];  
                
                // Succeed the job
                putJobSuccess["Tests passed."];
            } catch [ex] {
                // If any of the assertions failed then fail the job
                putJobFailure[ex];    
            }
        }];     
    };
    9]. Trong Nhà cung cấp, chọn AWS Lambda. Trong Tên hàm, hãy chọn hoặc nhập tên hàm Lambda của bạn [ví dụ:
    var assert = require['assert'];
    var AWS = require['aws-sdk'];
    var http = require['http'];
    
    exports.handler = function[event, context] {
    
        var codepipeline = new AWS.CodePipeline[];
        
        // Retrieve the Job ID from the Lambda action
        var jobId = event["CodePipeline.job"].id;
        
        // Retrieve the value of UserParameters from the Lambda action configuration in CodePipeline, in this case a URL which will be
        // health checked by this function.
        var url = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; 
        
        // Notify CodePipeline of a successful job
        var putJobSuccess = function[message] {
            var params = {
                jobId: jobId
            };
            codepipeline.putJobSuccessResult[params, function[err, data] {
                if[err] {
                    context.fail[err];      
                } else {
                    context.succeed[message];      
                }
            }];
        };
        
        // Notify CodePipeline of a failed job
        var putJobFailure = function[message] {
            var params = {
                jobId: jobId,
                failureDetails: {
                    message: JSON.stringify[message],
                    type: 'JobFailed',
                    externalExecutionId: context.awsRequestId
                }
            };
            codepipeline.putJobFailureResult[params, function[err, data] {
                context.fail[message];      
            }];
        };
        
        // Validate the URL passed in UserParameters
        if[!url || url.indexOf['//'] === -1] {
            putJobFailure['The UserParameters field must contain a valid URL address to test, including // or //'];  
            return;
        }
        
        // Helper function to make a HTTP GET request to the page.
        // The helper will test the response and succeed or fail the job accordingly 
        var getPage = function[url, callback] {
            var pageObject = {
                body: '',
                statusCode: 0,
                contains: function[search] {
                    return this.body.indexOf[search] > -1;    
                }
            };
            http.get[url, function[response] {
                pageObject.body = '';
                pageObject.statusCode = response.statusCode;
                
                response.on['data', function [chunk] {
                    pageObject.body += chunk;
                }];
                
                response.on['end', function [] {
                    callback[pageObject];
                }];
                
                response.resume[]; 
            }].on['error', function[error] {
                // Fail the job if our request failed
                putJobFailure[error];    
            }];           
        };
        
        getPage[url, function[returnedPage] {
            try {
                // Check if the HTTP response has a 200 status
                assert[returnedPage.statusCode === 200];
                // Check if the page contains the text "Congratulations"
                // You can change this to check for different text, or add other tests as required
                assert[returnedPage.contains['Congratulations']];  
                
                // Succeed the job
                putJobSuccess["Tests passed."];
            } catch [ex] {
                // If any of the assertions failed then fail the job
                putJobFailure[ex];    
            }
        }];     
    };
    5]. Trong Tham số người dùng, hãy chỉ định địa chỉ IP cho phiên bản Amazon EC2 mà bạn đã sao chép trước đó [ví dụ:
    var assert = require['assert'];
    var AWS = require['aws-sdk'];
    var http = require['http'];
    
    exports.handler = function[event, context] {
    
        var codepipeline = new AWS.CodePipeline[];
        
        // Retrieve the Job ID from the Lambda action
        var jobId = event["CodePipeline.job"].id;
        
        // Retrieve the value of UserParameters from the Lambda action configuration in CodePipeline, in this case a URL which will be
        // health checked by this function.
        var url = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; 
        
        // Notify CodePipeline of a successful job
        var putJobSuccess = function[message] {
            var params = {
                jobId: jobId
            };
            codepipeline.putJobSuccessResult[params, function[err, data] {
                if[err] {
                    context.fail[err];      
                } else {
                    context.succeed[message];      
                }
            }];
        };
        
        // Notify CodePipeline of a failed job
        var putJobFailure = function[message] {
            var params = {
                jobId: jobId,
                failureDetails: {
                    message: JSON.stringify[message],
                    type: 'JobFailed',
                    externalExecutionId: context.awsRequestId
                }
            };
            codepipeline.putJobFailureResult[params, function[err, data] {
                context.fail[message];      
            }];
        };
        
        // Validate the URL passed in UserParameters
        if[!url || url.indexOf['//'] === -1] {
            putJobFailure['The UserParameters field must contain a valid URL address to test, including // or //'];  
            return;
        }
        
        // Helper function to make a HTTP GET request to the page.
        // The helper will test the response and succeed or fail the job accordingly 
        var getPage = function[url, callback] {
            var pageObject = {
                body: '',
                statusCode: 0,
                contains: function[search] {
                    return this.body.indexOf[search] > -1;    
                }
            };
            http.get[url, function[response] {
                pageObject.body = '';
                pageObject.statusCode = response.statusCode;
                
                response.on['data', function [chunk] {
                    pageObject.body += chunk;
                }];
                
                response.on['end', function [] {
                    callback[pageObject];
                }];
                
                response.resume[]; 
            }].on['error', function[error] {
                // Fail the job if our request failed
                putJobFailure[error];    
            }];           
        };
        
        getPage[url, function[returnedPage] {
            try {
                // Check if the HTTP response has a 200 status
                assert[returnedPage.statusCode === 200];
                // Check if the page contains the text "Congratulations"
                // You can change this to check for different text, or add other tests as required
                assert[returnedPage.contains['Congratulations']];  
                
                // Succeed the job
                putJobSuccess["Tests passed."];
            } catch [ex] {
                // If any of the assertions failed then fail the job
                putJobFailure[ex];    
            }
        }];     
    };
    0], sau đó chọn Xong

    Chủ đề này sử dụng địa chỉ IP, nhưng trong trường hợp thực tế, bạn có thể cung cấp tên trang web đã đăng ký của mình [ví dụ:

    File statFile = File.createTempFile["organismStat", ".csv"]
    statFile  fp = tempfile.TemporaryFile[]
    >>> fp.write[b'Hello world!']
    # read data from file
    >>> fp.seek[0]
    >>> fp.read[]
    b'Hello world!'
    # close the file, it will be removed
    >>> fp.close[]
    
    # create a temporary file using a context manager
    >>> with tempfile.TemporaryFile[] as fp:
    ..     fp.write[b'Hello world!']
    ..     fp.seek[0]
    ..     fp.read[]
    b'Hello world!'
    >>>
    # file is now closed and removed
    
    # create a temporary directory using the context manager
    >>> with tempfile.TemporaryDirectory[] as tmpdirname:
    ..     print['created temporary directory', tmpdirname]
    >>>
    # directory and contents have been removed
    63 trong AWS CloudFormation, Amazon S3 và CodePipeline, như thể hiện trong chính sách mẫu này

    >>> import tempfile
    
    # create a temporary file and write some data to it
    >>> fp = tempfile.TemporaryFile[]
    >>> fp.write[b'Hello world!']
    # read data from file
    >>> fp.seek[0]
    >>> fp.read[]
    b'Hello world!'
    # close the file, it will be removed
    >>> fp.close[]
    
    # create a temporary file using a context manager
    >>> with tempfile.TemporaryFile[] as fp:
    ..     fp.write[b'Hello world!']
    ..     fp.seek[0]
    ..     fp.read[]
    b'Hello world!'
    >>>
    # file is now closed and removed
    
    # create a temporary directory using the context manager
    >>> with tempfile.TemporaryDirectory[] as tmpdirname:
    ..     print['created temporary directory', tmpdirname]
    >>>
    # directory and contents have been removed
    6

    Để tạo mẫu AWS CloudFormation, hãy mở bất kỳ trình soạn thảo văn bản thuần túy nào rồi sao chép và dán đoạn mã sau

    >>> import tempfile
    
    # create a temporary file and write some data to it
    >>> fp = tempfile.TemporaryFile[]
    >>> fp.write[b'Hello world!']
    # read data from file
    >>> fp.seek[0]
    >>> fp.read[]
    b'Hello world!'
    # close the file, it will be removed
    >>> fp.close[]
    
    # create a temporary file using a context manager
    >>> with tempfile.TemporaryFile[] as fp:
    ..     fp.write[b'Hello world!']
    ..     fp.seek[0]
    ..     fp.read[]
    b'Hello world!'
    >>>
    # file is now closed and removed
    
    # create a temporary directory using the context manager
    >>> with tempfile.TemporaryDirectory[] as tmpdirname:
    ..     print['created temporary directory', tmpdirname]
    >>>
    # directory and contents have been removed
    8

    Lưu tệp này dưới dạng tệp JSON có tên

    >>> import tempfile
    
    # create a temporary file and write some data to it
    >>> fp = tempfile.TemporaryFile[]
    >>> fp.write[b'Hello world!']
    # read data from file
    >>> fp.seek[0]
    >>> fp.read[]
    b'Hello world!'
    # close the file, it will be removed
    >>> fp.close[]
    
    # create a temporary file using a context manager
    >>> with tempfile.TemporaryFile[] as fp:
    ..     fp.write[b'Hello world!']
    ..     fp.seek[0]
    ..     fp.read[]
    b'Hello world!'
    >>>
    # file is now closed and removed
    
    # create a temporary directory using the context manager
    >>> with tempfile.TemporaryDirectory[] as tmpdirname:
    ..     print['created temporary directory', tmpdirname]
    >>>
    # directory and contents have been removed
    64 trong thư mục có tên
    >>> import tempfile
    
    # create a temporary file and write some data to it
    >>> fp = tempfile.TemporaryFile[]
    >>> fp.write[b'Hello world!']
    # read data from file
    >>> fp.seek[0]
    >>> fp.read[]
    b'Hello world!'
    # close the file, it will be removed
    >>> fp.close[]
    
    # create a temporary file using a context manager
    >>> with tempfile.TemporaryFile[] as fp:
    ..     fp.write[b'Hello world!']
    ..     fp.seek[0]
    ..     fp.read[]
    b'Hello world!'
    >>>
    # file is now closed and removed
    
    # create a temporary directory using the context manager
    >>> with tempfile.TemporaryDirectory[] as tmpdirname:
    ..     print['created temporary directory', tmpdirname]
    >>>
    # directory and contents have been removed
    65. Tạo một nén [. zip] của thư mục này và tệp có tên
    >>> import tempfile
    
    # create a temporary file and write some data to it
    >>> fp = tempfile.TemporaryFile[]
    >>> fp.write[b'Hello world!']
    # read data from file
    >>> fp.seek[0]
    >>> fp.read[]
    b'Hello world!'
    # close the file, it will be removed
    >>> fp.close[]
    
    # create a temporary file using a context manager
    >>> with tempfile.TemporaryFile[] as fp:
    ..     fp.write[b'Hello world!']
    ..     fp.seek[0]
    ..     fp.read[]
    b'Hello world!'
    >>>
    # file is now closed and removed
    
    # create a temporary directory using the context manager
    >>> with tempfile.TemporaryDirectory[] as tmpdirname:
    ..     print['created temporary directory', tmpdirname]
    >>>
    # directory and contents have been removed
    66, đồng thời tải tệp nén lên bộ chứa Amazon S3 đã được phiên bản. Nếu bạn đã định cấu hình bộ chứa cho quy trình của mình, thì bạn có thể sử dụng bộ chứa đó. Tiếp theo, hãy chỉnh sửa quy trình của bạn để thêm hành động nguồn truy xuất. tập tin nén. Đặt tên cho đầu ra cho hành động này là
    >>> import tempfile
    
    # create a temporary file and write some data to it
    >>> fp = tempfile.TemporaryFile[]
    >>> fp.write[b'Hello world!']
    # read data from file
    >>> fp.seek[0]
    >>> fp.read[]
    b'Hello world!'
    # close the file, it will be removed
    >>> fp.close[]
    
    # create a temporary file using a context manager
    >>> with tempfile.TemporaryFile[] as fp:
    ..     fp.write[b'Hello world!']
    ..     fp.seek[0]
    ..     fp.read[]
    b'Hello world!'
    >>>
    # file is now closed and removed
    
    # create a temporary directory using the context manager
    >>> with tempfile.TemporaryDirectory[] as tmpdirname:
    ..     print['created temporary directory', tmpdirname]
    >>>
    # directory and contents have been removed
    67. Để biết thêm thông tin, hãy xem Chỉnh sửa quy trình trong CodePipeline

    Hàm Lambda mẫu mong đợi các tên tệp và cấu trúc nén này. Tuy nhiên, bạn có thể thay thế mẫu AWS CloudFormation của riêng mình cho mẫu này. Nếu bạn sử dụng mẫu của riêng mình, hãy đảm bảo bạn sửa đổi chính sách cho vai trò thực thi Lambda để cho phép mọi chức năng bổ sung mà mẫu AWS CloudFormation của bạn yêu cầu

    Để thêm đoạn mã sau làm hàm trong Lambda

    1. Mở bảng điều khiển Lambda và chọn Tạo chức năng

    2. Trên trang Tạo chức năng, chọn Tác giả từ đầu. Trong Tên hàm, hãy nhập tên cho hàm Lambda của bạn

    3. Trong Thời gian chạy, chọn Python 2. 7

    4. Trong phần Chọn hoặc tạo vai trò thực thi, hãy chọn Sử dụng vai trò hiện có. Trong Vai trò hiện có, hãy chọn vai trò của bạn rồi chọn Tạo chức năng

      Trang chi tiết cho chức năng đã tạo của bạn sẽ mở ra

    5. Copy đoạn mã sau vào ô Mã chức năng

      var assert = require['assert'];
      var AWS = require['aws-sdk'];
      var http = require['http'];
      
      exports.handler = function[event, context] {
      
          var codepipeline = new AWS.CodePipeline[];
          
          // Retrieve the Job ID from the Lambda action
          var jobId = event["CodePipeline.job"].id;
          
          // Retrieve the value of UserParameters from the Lambda action configuration in CodePipeline, in this case a URL which will be
          // health checked by this function.
          var url = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; 
          
          // Notify CodePipeline of a successful job
          var putJobSuccess = function[message] {
              var params = {
                  jobId: jobId
              };
              codepipeline.putJobSuccessResult[params, function[err, data] {
                  if[err] {
                      context.fail[err];      
                  } else {
                      context.succeed[message];      
                  }
              }];
          };
          
          // Notify CodePipeline of a failed job
          var putJobFailure = function[message] {
              var params = {
                  jobId: jobId,
                  failureDetails: {
                      message: JSON.stringify[message],
                      type: 'JobFailed',
                      externalExecutionId: context.awsRequestId
                  }
              };
              codepipeline.putJobFailureResult[params, function[err, data] {
                  context.fail[message];      
              }];
          };
          
          // Validate the URL passed in UserParameters
          if[!url || url.indexOf['//'] === -1] {
              putJobFailure['The UserParameters field must contain a valid URL address to test, including // or //'];  
              return;
          }
          
          // Helper function to make a HTTP GET request to the page.
          // The helper will test the response and succeed or fail the job accordingly 
          var getPage = function[url, callback] {
              var pageObject = {
                  body: '',
                  statusCode: 0,
                  contains: function[search] {
                      return this.body.indexOf[search] > -1;    
                  }
              };
              http.get[url, function[response] {
                  pageObject.body = '';
                  pageObject.statusCode = response.statusCode;
                  
                  response.on['data', function [chunk] {
                      pageObject.body += chunk;
                  }];
                  
                  response.on['end', function [] {
                      callback[pageObject];
                  }];
                  
                  response.resume[]; 
              }].on['error', function[error] {
                  // Fail the job if our request failed
                  putJobFailure[error];    
              }];           
          };
          
          getPage[url, function[returnedPage] {
              try {
                  // Check if the HTTP response has a 200 status
                  assert[returnedPage.statusCode === 200];
                  // Check if the page contains the text "Congratulations"
                  // You can change this to check for different text, or add other tests as required
                  assert[returnedPage.contains['Congratulations']];  
                  
                  // Succeed the job
                  putJobSuccess["Tests passed."];
              } catch [ex] {
                  // If any of the assertions failed then fail the job
                  putJobFailure[ex];    
              }
          }];     
      };
      3
    6. Để lại Trình xử lý ở giá trị mặc định và để lại Vai trò ở tên bạn đã chọn hoặc tạo trước đó,

      var assert = require['assert'];
      var AWS = require['aws-sdk'];
      var http = require['http'];
      
      exports.handler = function[event, context] {
      
          var codepipeline = new AWS.CodePipeline[];
          
          // Retrieve the Job ID from the Lambda action
          var jobId = event["CodePipeline.job"].id;
          
          // Retrieve the value of UserParameters from the Lambda action configuration in CodePipeline, in this case a URL which will be
          // health checked by this function.
          var url = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; 
          
          // Notify CodePipeline of a successful job
          var putJobSuccess = function[message] {
              var params = {
                  jobId: jobId
              };
              codepipeline.putJobSuccessResult[params, function[err, data] {
                  if[err] {
                      context.fail[err];      
                  } else {
                      context.succeed[message];      
                  }
              }];
          };
          
          // Notify CodePipeline of a failed job
          var putJobFailure = function[message] {
              var params = {
                  jobId: jobId,
                  failureDetails: {
                      message: JSON.stringify[message],
                      type: 'JobFailed',
                      externalExecutionId: context.awsRequestId
                  }
              };
              codepipeline.putJobFailureResult[params, function[err, data] {
                  context.fail[message];      
              }];
          };
          
          // Validate the URL passed in UserParameters
          if[!url || url.indexOf['//'] === -1] {
              putJobFailure['The UserParameters field must contain a valid URL address to test, including // or //'];  
              return;
          }
          
          // Helper function to make a HTTP GET request to the page.
          // The helper will test the response and succeed or fail the job accordingly 
          var getPage = function[url, callback] {
              var pageObject = {
                  body: '',
                  statusCode: 0,
                  contains: function[search] {
                      return this.body.indexOf[search] > -1;    
                  }
              };
              http.get[url, function[response] {
                  pageObject.body = '';
                  pageObject.statusCode = response.statusCode;
                  
                  response.on['data', function [chunk] {
                      pageObject.body += chunk;
                  }];
                  
                  response.on['end', function [] {
                      callback[pageObject];
                  }];
                  
                  response.resume[]; 
              }].on['error', function[error] {
                  // Fail the job if our request failed
                  putJobFailure[error];    
              }];           
          };
          
          getPage[url, function[returnedPage] {
              try {
                  // Check if the HTTP response has a 200 status
                  assert[returnedPage.statusCode === 200];
                  // Check if the page contains the text "Congratulations"
                  // You can change this to check for different text, or add other tests as required
                  assert[returnedPage.contains['Congratulations']];  
                  
                  // Succeed the job
                  putJobSuccess["Tests passed."];
              } catch [ex] {
                  // If any of the assertions failed then fail the job
                  putJobFailure[ex];    
              }
          }];     
      };
      6

    7. Trong Cài đặt cơ bản, đối với Thời gian chờ, hãy thay thế mặc định là 3 giây bằng

      var assert = require['assert'];
      var AWS = require['aws-sdk'];
      var http = require['http'];
      
      exports.handler = function[event, context] {
      
          var codepipeline = new AWS.CodePipeline[];
          
          // Retrieve the Job ID from the Lambda action
          var jobId = event["CodePipeline.job"].id;
          
          // Retrieve the value of UserParameters from the Lambda action configuration in CodePipeline, in this case a URL which will be
          // health checked by this function.
          var url = event["CodePipeline.job"].data.actionConfiguration.configuration.UserParameters; 
          
          // Notify CodePipeline of a successful job
          var putJobSuccess = function[message] {
              var params = {
                  jobId: jobId
              };
              codepipeline.putJobSuccessResult[params, function[err, data] {
                  if[err] {
                      context.fail[err];      
                  } else {
                      context.succeed[message];      
                  }
              }];
          };
          
          // Notify CodePipeline of a failed job
          var putJobFailure = function[message] {
              var params = {
                  jobId: jobId,
                  failureDetails: {
                      message: JSON.stringify[message],
                      type: 'JobFailed',
                      externalExecutionId: context.awsRequestId
                  }
              };
              codepipeline.putJobFailureResult[params, function[err, data] {
                  context.fail[message];      
              }];
          };
          
          // Validate the URL passed in UserParameters
          if[!url || url.indexOf['//'] === -1] {
              putJobFailure['The UserParameters field must contain a valid URL address to test, including // or //'];  
              return;
          }
          
          // Helper function to make a HTTP GET request to the page.
          // The helper will test the response and succeed or fail the job accordingly 
          var getPage = function[url, callback] {
              var pageObject = {
                  body: '',
                  statusCode: 0,
                  contains: function[search] {
                      return this.body.indexOf[search] > -1;    
                  }
              };
              http.get[url, function[response] {
                  pageObject.body = '';
                  pageObject.statusCode = response.statusCode;
                  
                  response.on['data', function [chunk] {
                      pageObject.body += chunk;
                  }];
                  
                  response.on['end', function [] {
                      callback[pageObject];
                  }];
                  
                  response.resume[]; 
              }].on['error', function[error] {
                  // Fail the job if our request failed
                  putJobFailure[error];    
              }];           
          };
          
          getPage[url, function[returnedPage] {
              try {
                  // Check if the HTTP response has a 200 status
                  assert[returnedPage.statusCode === 200];
                  // Check if the page contains the text "Congratulations"
                  // You can change this to check for different text, or add other tests as required
                  assert[returnedPage.contains['Congratulations']];  
                  
                  // Succeed the job
                  putJobSuccess["Tests passed."];
              } catch [ex] {
                  // If any of the assertions failed then fail the job
                  putJobFailure[ex];    
              }
          }];     
      };
      7

    8. Chọn Lưu

    9. Từ bảng điều khiển CodePipeline, hãy chỉnh sửa quy trình để thêm chức năng dưới dạng hành động trong một giai đoạn trong quy trình của bạn. Chọn Chỉnh sửa cho giai đoạn quy trình bạn muốn thay đổi và chọn Thêm nhóm hành động. Trên trang Chỉnh sửa hành động, trong Tên hành động, hãy nhập tên cho hành động của bạn. Trong Nhà cung cấp hành động, chọn Lambda

      Trong Phần tạo tác đầu vào, chọn

      >>> import tempfile
      
      # create a temporary file and write some data to it
      >>> fp = tempfile.TemporaryFile[]
      >>> fp.write[b'Hello world!']
      # read data from file
      >>> fp.seek[0]
      >>> fp.read[]
      b'Hello world!'
      # close the file, it will be removed
      >>> fp.close[]
      
      # create a temporary file using a context manager
      >>> with tempfile.TemporaryFile[] as fp:
      ..     fp.write[b'Hello world!']
      ..     fp.seek[0]
      ..     fp.read[]
      b'Hello world!'
      >>>
      # file is now closed and removed
      
      # create a temporary directory using the context manager
      >>> with tempfile.TemporaryDirectory[] as tmpdirname:
      ..     print['created temporary directory', tmpdirname]
      >>>
      # directory and contents have been removed
      67. Trong UserParameters, bạn phải cung cấp một chuỗi JSON có ba tham số

      • tên ngăn xếp

      • Tên mẫu AWS CloudFormation và đường dẫn đến tệp

      • Đầu vào tạo tác

      Sử dụng dấu ngoặc nhọn [{ }] và phân tách các tham số bằng dấu phẩy. Ví dụ: để tạo một ngăn xếp có tên là

      >>> import tempfile
      
      # create a temporary file and write some data to it
      >>> fp = tempfile.TemporaryFile[]
      >>> fp.write[b'Hello world!']
      # read data from file
      >>> fp.seek[0]
      >>> fp.read[]
      b'Hello world!'
      # close the file, it will be removed
      >>> fp.close[]
      
      # create a temporary file using a context manager
      >>> with tempfile.TemporaryFile[] as fp:
      ..     fp.write[b'Hello world!']
      ..     fp.seek[0]
      ..     fp.read[]
      b'Hello world!'
      >>>
      # file is now closed and removed
      
      # create a temporary directory using the context manager
      >>> with tempfile.TemporaryDirectory[] as tmpdirname:
      ..     print['created temporary directory', tmpdirname]
      >>>
      # directory and contents have been removed
      81, đối với một đường ống có tạo phẩm đầu vào là
      >>> import tempfile
      
      # create a temporary file and write some data to it
      >>> fp = tempfile.TemporaryFile[]
      >>> fp.write[b'Hello world!']
      # read data from file
      >>> fp.seek[0]
      >>> fp.read[]
      b'Hello world!'
      # close the file, it will be removed
      >>> fp.close[]
      
      # create a temporary file using a context manager
      >>> with tempfile.TemporaryFile[] as fp:
      ..     fp.write[b'Hello world!']
      ..     fp.seek[0]
      ..     fp.read[]
      b'Hello world!'
      >>>
      # file is now closed and removed
      
      # create a temporary directory using the context manager
      >>> with tempfile.TemporaryDirectory[] as tmpdirname:
      ..     print['created temporary directory', tmpdirname]
      >>>
      # directory and contents have been removed
      67, trong UserParameters, hãy nhập. {"cây rơm". "
      >>> import tempfile
      
      # create a temporary file and write some data to it
      >>> fp = tempfile.TemporaryFile[]
      >>> fp.write[b'Hello world!']
      # read data from file
      >>> fp.seek[0]
      >>> fp.read[]
      b'Hello world!'
      # close the file, it will be removed
      >>> fp.close[]
      
      # create a temporary file using a context manager
      >>> with tempfile.TemporaryFile[] as fp:
      ..     fp.write[b'Hello world!']
      ..     fp.seek[0]
      ..     fp.read[]
      b'Hello world!'
      >>>
      # file is now closed and removed
      
      # create a temporary directory using the context manager
      >>> with tempfile.TemporaryDirectory[] as tmpdirname:
      ..     print['created temporary directory', tmpdirname]
      >>>
      # directory and contents have been removed
      81","tệp". "gói mẫu/mẫu. json","tạo phẩm". "______267"}

      Mặc dù bạn đã chỉ định cấu phần phần mềm đầu vào trong UserParameters, nhưng bạn cũng phải chỉ định cấu phần phần mềm đầu vào này cho hành động trong Cấu phần phần mềm đầu vào

    10. Lưu các thay đổi của bạn vào quy trình bán hàng, sau đó phát hành một thay đổi theo cách thủ công để kiểm tra hành động và chức năng Lambda

Chủ Đề