如何通过命令行创建NuGet ApiKey,实现Jenkins自动化NuGet包部署
Great question—you're right that the NuGet CLI doesn't have a built-in command to create API keys directly, but we can leverage NuGet's REST API to automate this process fully within Jenkins, avoiding manual UI steps and hardcoding credentials. Here's a step-by-step solution tailored to your workflow:
Step 1: Authenticate with NuGet from Jenkins
First, we'll use the username/password parameters passed to Jenkins to generate a valid authentication header for the NuGet API. This replaces manual login to the NuGet portal.
Step 2: Call the NuGet REST API to Create an API Key
NuGet exposes a dedicated endpoint for creating API keys programmatically. We can use PowerShell or curl in a Jenkins Pipeline to send a POST request to this endpoint with our desired key configuration.
Example PowerShell Script for Jenkins Pipeline
This script will:
- Grab the Jenkins-provided username/password
- Authenticate with NuGet
- Create an API key restricted to pushing your project's packages
- Store the key securely in Jenkins credentials for future use
# Retrieve credentials from Jenkins environment variables $nugetUsername = "${env:NUGET_USERNAME}" $nugetPassword = "${env:NUGET_PASSWORD}" # Encode credentials for Basic Authentication $base64Auth = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$nugetUsername:$nugetPassword")) $authHeader = @{ "Authorization" = "Basic $base64Auth" } # Define API key settings: customize description, package scope, and expiration as needed $apiKeyConfig = @{ Description = "Auto-generated key for Jenkins deployment of MyProject packages" Scopes = @( @{ Resource = "package/YourCompany.YourProject*" # Restrict to your package IDs Actions = @("push") # Only allow pushing packages } ) # Optional: Set an expiration date (ISO 8601 format) # Expiration = "2025-12-31T23:59:59Z" } | ConvertTo-Json -Compress # Send request to create API key $apiResponse = Invoke-RestMethod -Uri "https://api.nuget.org/v2-apikey/create" ` -Method Post ` -Headers $authHeader ` -ContentType "application/json" ` -Body $apiKeyConfig # Extract the new API key from the response $newApiKey = $apiResponse.ApiKey # Store the key in Jenkins Credentials (requires Jenkins CLI or Credentials Binding plugin) # Example using Jenkins CLI (adjust Jenkins server URL and path to jenkins-cli.jar as needed) java -jar jenkins-cli.jar -s http://your-jenkins-url/ create-credentials-by-xml system::system::jenkins _ << EOF <com.cloudbees.plugins.credentials.impl.StringCredentialsImpl> <scope>GLOBAL</scope> <id>nuget-auto-deploy-key</id> <description>Auto-generated API key for NuGet package pushes</description> <secret>$newApiKey</secret> </com.cloudbees.plugins.credentials.impl.StringCredentialsImpl> EOF
Step 3: Use the Stored API Key for Future Deployments
Once the key is saved in Jenkins credentials, you can reference it in your deployment pipeline without exposing sensitive data. For example, using the Credentials Binding plugin to inject the key as an environment variable:
pipeline { agent any environment { NUGET_API_KEY = credentials('nuget-auto-deploy-key') } stages { stage('Push NuGet Package') { steps { sh 'dotnet nuget push "**/*.nupkg" --api-key $NUGET_API_KEY --source https://api.nuget.org/v3/index.json' } } } }
Key Notes for Security & Reliability
- Restrict API Key Scope: Always limit the key to only the actions and packages it needs (e.g., only
pushaccess for your specific package IDs) to minimize risk if the key is compromised. - Expiration: Set an expiration date for the key if possible, and automate periodic rotation using the same workflow.
- Avoid Logging Sensitive Data: Jenkins credentials are masked in logs by default, but ensure your script doesn't print the API key to console output.
- Permissions: Ensure the NuGet account used has permission to create API keys (this is enabled by default for individual accounts; for organization accounts, the user needs appropriate admin rights).
内容的提问来源于stack exchange,提问作者Kristiyan Goleminov

