Fix token generation. 50/15750/4
authorAric Gardner <agardner@linuxfoundation.org>
Thu, 23 May 2019 16:36:25 +0000 (12:36 -0400)
committerAric Gardner <agardner@linuxfoundation.org>
Tue, 28 May 2019 14:53:47 +0000 (14:53 +0000)
Remove legacy method of token generation.

username and password come from global section of lftools.ini.
[global]
username = lfid
password =

url comes from -s section of jenkins_jobs.ini
eg: [jenkins.acumos.org/sandbox]
url=jenkins.acumos.org/sandbox

example command
lftools jenkins -s 'jenkins.acumos.org/sandbox' token change

option --name set token name default is token-created-by-lftools

changeApiToken no longer exists, so we must allways generate a
new token.

NOTE: token print and token change now do the same thing.
That is generate a new token and return it to console.
I could remove one of them but Im wary of breaking any
legacy scripts that may exist.

NOTE: This will not work with SAML Plugin jenkins.
But I need it for automation before we switch all
jenkins to SAML

ISSUE: RELENG-2046
Signed-off-by: Aric Gardner <agardner@linuxfoundation.org>
Change-Id: I075c530f6e9fad7b477383867d52b83bba745662

lftools/cli/jenkins/token.py
lftools/jenkins/token.py

index a673b5f..d0e9b64 100644 (file)
@@ -32,8 +32,10 @@ def token(ctx):
 
 
 @click.command()
+@click.option('--name', type=str, default="token-created-by-lftools",
+              help='set token name')
 @click.pass_context
-def change(ctx):
+def change(ctx, name):
     """Generate a new API token."""
     jenkins = ctx.obj['jenkins']
     username = ctx.obj['username']
@@ -43,7 +45,7 @@ def change(ctx):
         log.error('Username or password not set.')
         sys.exit(1)
 
-    log.info(get_token(jenkins.url, change=True,
+    log.info(get_token(name, jenkins.url, change=True,
                        username=username, password=password))
 
 
index 42c25ed..eb33bcb 100644 (file)
@@ -18,7 +18,7 @@ import jenkins
 log = logging.getLogger(__name__)
 
 
-def get_token(url, username, password, change=False):
+def get_token(name, url, username, password, change=False):
     """Get API token.
 
     This function uses the global username / password for Jenkins from
@@ -36,15 +36,15 @@ def get_token(url, username, password, change=False):
         password=password)
 
     get_token = """
+import hudson.model.*
+import jenkins.model.*
 import jenkins.security.*
+import jenkins.security.apitoken.*
 User u = User.get("{}")
 ApiTokenProperty t = u.getProperty(ApiTokenProperty.class)
-if ({}) {{
-    t.changeApiToken()
-}}
-def token = t.getApiToken()
-println "$token"
-""".format(username, str(change).lower())
+def token = t.tokenStore.generateNewToken("{}")
+println token.plainValue
+""".format(username, name)
 
     token = server.run_script(get_token)
     return token