AWS CodeBuild执行go get失败:无法找到Go子包
It looks like the issue stems from a conflict between traditional GOPATH-based workflows and modern Go Modules (the standard for Go 1.11+). Even though you copied files to the correct GOPATH location, if your project uses a go.mod file, Go will prioritize module mode over GOPATH—leading to the package-not-found errors you’re seeing.
Here are two solutions, with the first being the recommended modern approach:
Recommended: Use Go Modules (No GOPATH Required)
Go Modules eliminate the need for strict GOPATH structure and work seamlessly with AWS CodeBuild. Adjust your buildspec.yml like this:
version: 0.2 phases: install: commands: # Work directly from CodeBuild's source directory - cd ${CODEBUILD_SRC_DIR} # Fetch dependencies defined in your go.mod file - go mod download build: commands: # Build the application in the source directory - go build -o application post_build: commands: - aws cloudformation package --template-file template.yml --output-template-file serverless.yml --s3-bucket some-bucket artifacts: files: - serverless.yml - application # Include the built binary in your output (you were missing this before)
Key Adjustments:
- Removed all GOPATH-related directory setup and file copying—CodeBuild can work directly from
CODEBUILD_SRC_DIR. - Replaced
go get ./...withgo mod downloadto fetch dependencies properly via Go Modules. - Added the built
applicationbinary to your artifacts (since you’re generating it, you’ll likely want to include it in the final output).
Make sure your project has a go.mod and go.sum file (run go mod init github.com/user/package locally if you haven’t already) before pushing to your source repository.
Alternative: Fix the GOPATH-Based Workflow
If you need to stick with the traditional GOPATH approach, you’ll need to disable Go Modules explicitly and enforce GOPATH lookup rules:
version: 0.2 env: variables: PACKAGE: "github.com/user/package" GO111MODULE: "off" # Force Go to use GOPATH mode phases: install: commands: - mkdir -p ${GOPATH}/src/${PACKAGE} - cp -a ${CODEBUILD_SRC_DIR}/. ${GOPATH}/src/${PACKAGE} - cd ${GOPATH}/src/${PACKAGE} && go get ./... build: commands: - cd ${GOPATH}/src/${PACKAGE} && go build -o ${CODEBUILD_SRC_DIR}/application post_build: commands: - aws cloudformation package --template-file template.yml --output-template-file serverless.yml --s3-bucket some-bucket artifacts: files: - serverless.yml - application
The root cause of your original error was likely Go running in module mode (even though you tried to use GOPATH), so it was searching for packages in CODEBUILD_SRC_DIR instead of the GOPATH location you copied files to. Disabling modules forces Go to use traditional GOPATH lookup logic.
内容的提问来源于stack exchange,提问作者Ben

