title: Best way to create and use new credential in Jenkins pipeline?
body: <p>So I'm constructing a Jenkins pipeline to provision (Terraform), configure (Ansible) and deploy a set of &quot;latest&quot;-tagged containers from our container registry.</p>
  <p>The first two stages are working perfectly. The host is provisioned and configured to run Docker containers. I have the CA cert, client cert and client key I need to create a DockerServerCredential, but am stuck on how to create that credential and use it in the pipeline. In other words, I don't want to end the pipeline after Ansible runs, manually add the credential to Jenkins, and then kick off another pipeline to deploy the containers using the new credential. I would like to use the CA, cert and key values to create a DockerServerCredential in my pipeline and then pass the name of that credential to docker.withServer().</p>
  <p>So I know I COULD add this to my Jenkinsfile:</p>
  <pre><code>stage('Deploy') {
      steps {
          script {
              def credName = &quot;Docker-Cert-${env.OUT_VM_NAME}&quot;
              
              domain = com.cloudbees.plugins.credentials.domains.Domain.global()
              store = Jenkins.instance.getExtensionList('com.cloudbees.plugins.credentials.SystemCredentialsProvider')[0].getStore()
  
              dockerCertCred = new DockerServerCredentials(
                  CredentialsScope.GLOBAL,
                  credName,
                  '',
                  env.OUT_DCKR_CRED_KEY,
                  env.OUT_DCKR_CRED_CERT,
                  env.OUT_DCKR_CRED_CA
              )
  
              store.addCredentials(domain, dockerCertCred)
              
              docker.withServer(&quot;tcp://${env.OUT_VM_NAME}:2376&quot;, credName) {
                  // things!
              }
          }
      }
  }
  </code></pre>
  <p>but I'm aware the best practice doco says to <a href="https://www.jenkins.io/doc/book/pipeline/pipeline-best-practices/#avoiding-calls-to-jenkins-getinstance" rel="nofollow noreferrer">avoid using Jenkins.getInstance in a pipeline</a>. <em>And</em> it would require me to add &quot;staticMethod com.cloudbees.plugins.credentials.domains.Domain global&quot; and &quot;staticMethod jenkins.model.Jenkins getInstance&quot; to Script Approvals, which I'm rather :/// on.</p>
  <p>So my question is: HOW WOULD YOU DO IT? What's the best practice here?</p>
  <p>P.S. I don't even need to persist the credential, so it'd be super-ideal if there was a wrapper that created a temporary credential, but I haven't been able to find one.</p>
  <p>P.P.S. Haven't created a plugin before and am hoping against hope I can avoid having to do that.</p>