Okuqukethwe
- Isingeniso: Kungani usebenzisa i-SAM ukufaka i-API?
- Okudingekayo: Faka i-SAM CLI
– Isinyathelo 1: Qalisa i-SAM
- Isinyathelo sesi-2: Chaza iphoyinti lokugcina le-API
- Isinyathelo sesi-3: Yakha futhi Uhlole endaweni
- Isinyathelo sesi-4: Sebenzisa i-API
- Isinyathelo sesi-5: I-CI / CD Ngezenzo ze-Github
– Isiphetho
Isingeniso: Kungani Usebenzisa i-SAM Ukuze Ukhiphe i-API?
Ukukhipha i-API kusetshenziswa i-AWS Serverless Application Model (SAM) kuyindlela ephumelelayo nengakalayo yezinhlelo zokusebenza ezisekelwe emafini.
Yenza ukuphathwa kwengqalasizinda kube lula, inikeza ukwesekwa okwakhelwe ngaphakathi kwe-SSL/TLS, futhi ihlanganisa ngaphandle komthungo nezinsizakalo ze-AWS ezifana ne-CloudFormation, i-Lambda, i-S3, i-Route 53, ne-CloudWatch.
Ngokusebenzisa imodeli engenasiphakeli, abathuthukisi bangagxila ekubhaleni i-logic yohlelo lokusebenza kuyilapho i-AWS iphatha ukukala, ukuphepha, nokugcinwa, ikwenze kube yisixazululo esifanelekile sama-API anamuhla, atholakala kakhulu.
Lesi sifundo sizokuqondisa isinyathelo ngesinyathelo sendlela yokudala i-API elula, uyisebenzise usebenzisa i-AWS CloudFormation nge-SAM CLI, bese uthumela ngokuzenzakalelayo usebenzisa Izenzo ze-GitHub.
Nawu umdwebo onemininingwane eminingi yalokhu kuhamba komsebenzi:
Okudingekayo
- I-AWS CLI ne-SAM CLI ifakiwe.
- I-Node.js ifakiwe
- I-Docker yokuhlolwa kwendawo.
- I-akhawunti ye-GitHub .
Okudingekayo: Faka i-SAM CLI
Ngaphambi kokuthi ungene esifundweni, qinisekisa ukuthi i-AWS SAM CLI ifakiwe emshinini wakho. Ngezansi izinyathelo zokufaka ze-macOS neWindows:
Okwe-macOS
Faka i-Homebrew (uma ingafakiwe):
/bin/bash -c “$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
Engeza umpompi we-AWS bese ufaka i-SAM CLI :
brew tap aws/tapbrew install aws-sam-cli
Qinisekisa ukufakwa nge sam --version
OkweWindows
Landa isifaki se-SAM CLI :
- Iya ekhasini elisemthethweni le-AWS SAM CLI bese ulanda isifaki seWindows sakamuva.
Qalisa isifaki :
- Chofoza kabili ifayela
.exe
elilandiwe bese ulandela iwizadi yokufaka.
Engeza i-SAM CLI ku-PATH (uma kungengezwe ngokuzenzakalelayo):
- Vula imenyu yokuqala bese usesha “Okuguquguqukayo Kwemvelo.”
- Chofoza okuthi “Hlela okuguquguqukayo kwemvelo yesistimu.”
- Ngaphansi kokuthi “Izakhiwo Zesistimu,” chofoza inkinobho ethi “Okuguquguqukayo Kwendawo”.
- Kokuthi “Okuguquguqukayo Kwesistimu,” thola
Path
bese uchofoza okuthi "Hlela." - Engeza uhla lwemibhalo lapho kwafakwa khona i-SAM CLI (isb,
C:\Program Files\Amazon\AWS SAM CLI\bin
).
Qinisekisa ukufakwa : Vula umyalo bese ugijima sam --version
Isinyathelo 1: Qalisa i-SAM CLI
Dala indawo yokugcina entsha emshinini wakho: mkdir aws-serverless-api
Zulazulela kuhla lwemibhalo: cd aws-serverless-api
Qalisa uhlelo olusha lwe-SAM: sam init
bese uzocelwa ngezinketho ezimbalwa. Nakhu ukusethwa kwami:
- Khetha "1 - Izifanekiso Zokuqala Ezisheshayo ze-AWS."
- Khetha okuthi “7 — Serverless API” ukuze usebenzise i-Lambda-backed serverless API ku-API Gateway.”
- Khetha okuthi “Node.js 20.x”
- Khetha u-“N” noma Cha ukuze uthole umkhondo we-X-Ray njengoba sifuna ukwehlisa izindleko zethu, futhi lesi isibonelo esilula se-Hello World. Uma wenza i-API eyinkimbinkimbi edonsa kumasevisi ahlukene, ungase ufune ukunika amandla lokho ukuze usize ekususeni iphutha.
- Futhi ngikhetha okuthi “N” kokuqapha kwe-cloudwatch njengoba singazidingi izibalo zokusebenza kwalesi sibonelo se-Hello World.
- Futhi “N” yefomethi ye-json kulogi ye-lambda njengoba lesi isibonelo nje se-Hello World.
Manje, ake sifake i-cd kuhla lwemibhalo olukhiqizwe yi- sam init
; Ngikhethe ukuqamba iphrojekthi yami ngokuthi sam-hello-world
ngakho-ke asihambe:
cd sam-hello-world
Bese uvula iphrojekthi kukhodi code .
- uma uvula iphrojekthi ku-VSCode noma i-IDE oyikhonzile, kufanele usuvele ubone inqwaba yamafayela akhiqiziwe.
Ukuqonda Amafayela Akhiqiziwe
Nakhu okwenziwa yifayela ngalinye elikhiqizwe ku sam init
:
-
**template.yaml**
- Ichaza i-API Gateway yakho, i-Lambda, nezinye izinsiza ze-AWS. -
**src/handlers/**
– Iqukethe izibambi zesampula ze-Lambda. -
**events/**
- Izehlakalo zokuhlola eziyisampula zokuhlolwa kwendawo. -
**package.json**
– Ilawula ukuncika kwemisebenzi ye-Node.js Lambda. -
**.gitignore**
,**README.md**
- Amafayela okusetha ajwayelekile ephrojekthi.
Sizoshintsha futhi sisuse amanye alawa mafayela ukuze alingane ne-API yethu elula kakhulu ethi "hello world" .
Isinyathelo sesi-2: Chaza iphoyinti lokugcina le-API
Manje, vula template.yaml
bese ubuyisela izincazelo ezikhona ze-Lambda ngokulandelayo:
AWSTemplateFormatVersion: "2010-09-09" Transform: AWS::Serverless-2016-10-31 Description: AWS SAM template for deploying Node.js/Express API to Lambda Resources: HelloWorldFunction: Type: AWS::Serverless::Function Properties: Handler: src/app.lambdaHandler Runtime: nodejs20.x Events: HelloWorld: Type: Api Properties: Path: / Method: GET
Lokhu kuchaza umzila owodwa kumsuka we-API yethu oyisicelo se-GET
Buyekeza Umsebenzi we-Lambda
Kuhla lwemibhalo /src
, masidale ifayela elibizwa ngokuthi app.js
Ku src/app.js
, asibhale umsebenzi ukuze sikhiphe sawubona umhlaba emzileni wethu:
exports.lambdaHandler = async (event) => { return { statusCode: 200, body: JSON.stringify({ message: "Hello, World!" }) }; };
Susa Amafayela Angadingekile
Manje, ake sisuse izibambi ezengeziwe nemicimbi ekhiqizwe yi- sam init
esinyathelweni 1.
Vula i-terminal kumkhombandlela wephrojekthi bese ukhipha le miyalo :
rm -rf src/handlers/get-all-items.mjs src/handlers/get-by-id.mjs src/handlers/put-item.mjs
rm -rf events/
Isinyathelo sesi-3: Yakha futhi Uhlole endaweni
Vula i-terminal kumkhombandlela wephrojekthi bese ulandela lezi zinyathelo ezingezansi:
- Yakha uhlelo lokusebenza :
-
sam build
kufanele ubone okukhiphayo okufana nalokhu:
- Qala iseva yendawo ye-API :
sam local start-api
— Qaphela uzodinga ukuthi ufake idocker ukuze usebenzise lokhu endaweni. Uma uphumelele, kufanele ubone isiqukathi esidalelwe i-API yethu kudeskithophu yedokhu.
- Vula isiphequluli noma usebenzise
curl
kutheminali ukuze uhlole iphoyinti lokugcina:
- Vula isiphequluli noma usebenzise
curl [http://127.0.0.1:3000/](http://127.0.0.1:3000/)
Uma ubona i-JSON ibuyile endaweni yethu yokugcina, lapho-ke usuqalise ngempumelelo i-API endaweni! 🚀
Isinyathelo sesi-4: Sebenzisa i-API
Phakamisa futhi usebenzise i-API usebenzisa i-SAM : Manje njengoba sesiqinisekisile ukuthi i-API yethu iyasebenza endaweni, masiyisebenzise ku-AWS sisebenzisa
sam deploy --guided
Lokhu kuthunyelwa okuqondisiwe kuzokuvumela ukuthi:
1. Khetha igama lakho lesitaki; owami ngu sam-hello-world
2. Khetha Isifunda se-AWS; eyami ithi us-east-1
3. Qinisekisa izinguquko ngaphambi kokuthunyelwa; Ngakhetha Y
4. Vumela Ukudalwa Kwendima Ye-SAM-CLI, Y
5. Khubaza i-Rollback, khetha okuthi N
sifuna ithuluzi lokuhlanza noma yiziphi izinsiza ezihlulekile
6. I-HelloWorldFunction ayinakho ukuqinisekiswa; kulungile lokhu? Ngenhloso yalesi sifundo Y
7. Londoloza izimpikiswano efayelini lokumisa elingu Y
8. Ifayela lokumisa i samconfig.toml
9. Imvelo yokucushwa kwe-SAM — shiya lokhu njengokumisiwe
Uma ukuthunyelwa kwakho kuphumelele, kufanele ubone izinsiza ezidalwe ngempumelelo ngale ndlela:
Uma ukuthunyelwa kuphumelela, ngena ngemvume ku-akhawunti yakho ye-AWS bese usesha isevisi ye-API Gateway. Iya kuzilungiselelo ze-API, kopisha isizinda sakho sinamathisele kokokufaka kwe-URL ewindini lesiphequluli sakho, bese wengeza `/Prod` ekugcineni kwe-URL yakho ukuze ufinyelele ekugcineni kwe-API yakho esetshenzisiwe.
I-URL yami ibukeka kanje:
Ungaphinda useshe i-Lambda kukhonsoli ye-AWS ukuze ubuke umsebenzi wakho we-Lambda ongasebenzi, lapho kuhlala khona ikhodi esiyibhalele lesi siphetho.
Kufanele futhi ubone ibhakede le-S3 elakhiwe, eliphethe inqwaba yekhodi yethu. Manje njengoba sesikhiphe ngempumelelo i-API yethu, masiguqule le nqubo ngokuzenzakalelayo nge-GitHub ukuze noma nini lapho sifuna ukuthuthukisa i-API yethu, ukuthunyelwa kungaqala ngokuzenzakalelayo ngokuzibophezela egatsheni le-MAIN noma le-MASTER.
Isinyathelo sesi-5: I-CI/CD Ngezenzo ze-Github
Qalisa i-Git Repo Yakho bese Uphushela Egatsheni Lakho Eliyinhloko
Okokuqala, sizoqalisa inqolobane ye-git kunkomba yephrojekthi yethu nge git init
Bese, ake sengeze lawa mafayela ku .gitignore
yethu njengoba singafuni ukuwenza.
echo "node_modules/\n.aws-sam/\nsamconfig.toml" >> .gitignore
Manje, siphephile ukufaka kusiteji wonke amafayela kuphrojekthi: git add .
bese senza isivumelwano sethu sokuqala:
git commit -m "Initial commit - AWS SAM API setup"
Lesi sinyathelo esilandelayo sithatha ukuthi une-GitHub CLI efakiwe - Lesi sinyathelo ukuze sikwazi ukudala i-repo ye-GitHub kusuka kumkhombandlela wethu wamanje:
gh repo create aws-sam-cli-tutorial --public --source=. --remote=origin
Uma ungenayo i-GitHub CLI, ungakha i-repo ngesandla ku-GitHub bese ukhomba uhla lwemibhalo ku-repo yakho ngalo myalo:
git remote add origin https://github.com/YOUR_USERNAME/YOUR_REPO_NAME.git
Ekugcineni, masiphushele ikhodi yethu ku-GitHub git push -u origin master
Setha Izenzo ze-GitHub ze-CI/CD
Masidale ifayela lokuhamba komsebenzi le-GitHub:
mkdir -p .github/workflows
touch .github/workflows/deploy.yml
Vula lelo fayela le deploy.yml
ku-vscode bese unamathisela ukulungiselelwa okulandelayo kwe-yaml:
name: Deploy API to AWS CloudFormation on: push: branches: - master jobs: deploy: runs-on: ubuntu-latest steps: - name: Checkout Code uses: actions/checkout@v3 - name: Install AWS SAM CLI uses: aws-actions/setup-sam@v2 - name: Configure AWS CLI uses: aws-actions/configure-aws-credentials@v2 with: aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} aws-region: us-east-1 - name: Build and Deploy API run: | sam build sam deploy \ --stack-name sam-hello-world \ --s3-bucket ${{ secrets.AWS_S3_BUCKET }} \ --capabilities CAPABILITY_IAM \ --region ${{ secrets.AWS_REGION }} \ --no-confirm-changeset \ --no-fail-on-empty-changeset
Kuleli fayela le-.yaml ukuze lisetshenziswe ngokuzenzakalelayo, sithembele kumakhosombe e-AWS-Actions avela ku-GitHub: https://github.com/orgs/aws-actions/repositories ukuze kufakwe i-SAM CLI futhi silungise imininingwane yethu — lezi zindawo zokugcina ze-AWS zingashintsha eminyakeni embalwa, ngakho-ke buyekeza njengoba kudingeka.
Manje, asiye ku-github.com — iya kumakhosombe akho, chofoza inqolobane esiyenzele le phrojekthi, hamba kuzilungiselelo, izenzo, futhi uzobona lesi sikrini ukuze wengeze indawo kanye nezimfihlo zokugcina.
Sizofuna ukwengeza izimfihlo ze-Repository ze:
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
AWS_REGION
AWS_S3_BUCKET
Ukuze uthole lawa manani, hamba kukhonsoli yakho ye-AWS. Ku -AWS_REGION, uzofuna ukusebenzisa isifunda esifanayo osisebenzise emshinini wangakini. Uma ungaqiniseki ngesifunda, sesha i-cloudformation futhi uthole isitaki osidalile, chofoza kuso, futhi kufanele ubone isifunda ku-URL.
Mayelana ne -AWS_S3_BUCKET, sesha i-S3 kukhonsoli ye-AWS bese ukhetha ibhakede eladalwa ngesikhathi silikhipha emshinini wethu Esinyathelweni sesi-4. Sebenzisa i-ID yaleli bhakede ngevelu yakho; eyami iboniswa kusithombe-skrini esingezansi.
Nge- AWS_ACCESS_KEY_ID
ne AWS_SECRET_ACCESS_KEY,
hamba kusevisi ye-IAM kukhonsoli ye-AWS:
Kusukela lapha, dala umsebenzisi we-IAM uma ungakabi nayo enokufinyelela ofuna ukukusebenzisa, futhi wengeze okungenani lezi zikophu zemvume kumsebenzisi:
AWSLambdaFullAccess
IAMFullAccess AmazonS3FullAccess
CloudFormationFullAccess
AmazonAPIGatewayAdministrator
Ungakwazi futhi ukwengeza i-AdministratorAccess uma ukhululekile ngalokho. Ngemuva kwalokho, sizofuna ukudala ukhiye wokufinyelela kanye nemfihlo yalo msebenzisi. Khetha i-CLI njengendawo yokusebenzisa ukhiye wokufinyelela. Qiniseka ukuthi ukopisha imfihlo yakho ngoba ngeke ukwazi ukuyibona futhi.
Manje, buyela ku-GitHub bese wengeza izimfihlo zakho zenqolobane:
Kulungile, isinyathelo sokugcina ukuhlola ukuthi yonke into iyasebenza! Buyekeza i-app.js yakho ukuze usho okunye; Ngashintsha eyami yaba yi-"What up, World!"
exports.lambdaHandler = async (event) => { return { statusCode: 200, body: JSON.stringify({ message: "What up, World!" }), }; };
Bese, cindezela izinguquko zakho egatsheni lakho eliyinhloko. git add .
git commit -m 'updated message'
git push
- qiniseka ukuthi usegatsheni eliyinhloko lapho uphusha.
Ku-repo yakho ye-GitHub, kufanele ubone isenzo sisebenza futhi usebenzise ngempumelelo:
Ekugcineni, buyela emuva kusiphequluli sakho sewebhu bese unamathisele i-URL esuka ku-API Gateway esiyimisile. Eyami ithi: https://tt40c6vgm3.execute-api.us-east-1.amazonaws.com/Prod — futhi uqinisekise ukuthi umlayezo ushintshiwe.
Isiphetho
Siyakuhalalisela! Usanda kwakha ipayipi lokuthumela le-CI/CD le-AWS Stack engenasiphakeli; manje, ungaba matasa ngokwakha i-API yakho ngamasevisi awusizo. Ngazise uma lesi sihloko besiwusizo noma unemibuzo noma iziphakamiso zokuthuthukisa!