Github Actions运行Python Boto3报NoCredentialsError无法定位AWS凭证问题
提问内容
我尝试通过Github Actions运行基于AWS SDK的Python脚本,Boto3可正常安装,但脚本执行时出现如下报错:
报错信息:
Run python3 s3.py Traceback (most recent call last): File "s3.py", line 5, in <module> response = s3.list_buckets() File "/opt/hostedtoolcache/Python/3.8.6/x64/lib/python3.8/site-packages/botocore/client.py", File "/opt/hostedtoolcache/Python/3.8.6/x64/lib/python3.8/site-packages/botocore/signers.py", line 162, in sign auth.add_auth(request) File "/opt/hostedtoolcache/Python/3.8.6/x64/lib/python3.8/site-packages/botocore/auth.py", line 357, in add_auth raise NoCredentialsError botocore.exceptions.NoCredentialsError: Unable to locate credentials Error: Process completed with exit code 1.
目前已完成的配置如下:ListS3bucket.yml
name: Python package on: [push] jobs: deploy: name: sample code runs-on: ubuntu-latest steps: - name: checkout repo content uses: actions/checkout@v2 # checkout the repository content to github runner. - name: setup python uses: actions/setup-python@v2 with: python-version: 3.8 - name: Upgrade PIP run: | /opt/hostedtoolcache/Python/3.8.6/x64/bin/python -m pip install --upgrade pip - name: install boto3 run: | python -m pip install boto3 - name: execute script env: aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} aws-region: us-east-1 run: | python3 s3.py
s3.py
import boto3 # Retrieve the list of existing buckets s3 = boto3.client('s3') response = s3.list_buckets() # Output the bucket names print('Existing buckets:') for bucket in response['Buckets']: print(f' {bucket["Name"]}')
问题解决方案
报错根源
GitHub Actions步骤中定义的环境变量名称不符合boto3的默认识别规则。boto3仅会读取全大写、无横杠的标准AWS环境变量名:AWS_ACCESS_KEY_ID、AWS_SECRET_ACCESS_KEY、AWS_REGION,当前配置的带横杠小写变量名无法被识别,因此触发找不到凭证的报错。
修改步骤
- 调整
ListS3bucket.yml中execute script步骤的环境变量名,替换为标准格式:
- name: execute script env: AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} AWS_REGION: us-east-1 run: | python3 s3.py
- 确认两项前置配置正常:
- 已在GitHub仓库的
Settings > Secrets路径下正确添加AWS_ACCESS_KEY_ID和AWS_SECRET_ACCESS_KEY两个密钥,且对应IAM账号拥有S3list_buckets操作权限 - 未在代码仓库中硬编码AWS明文凭证,所有密钥仅通过GitHub Secrets调用
- 可选优化方案:使用官方
aws-actions/configure-aws-credentials动作统一配置AWS凭证,降低手动定义变量的出错概率。在install boto3步骤后、execute script步骤前添加如下配置,即可删除原有execute script步骤里的env定义:
- name: Configure AWS credentials 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
内容的提问来源于stack exchange,提问作者Jiya
相关产品推荐
相关产品推荐

