From 9565c01c757b2930159c3b1792e6ca02a82fbae6 Mon Sep 17 00:00:00 2001 From: Aric Gardner Date: Thu, 23 May 2019 12:36:25 -0400 Subject: [PATCH] Fix token generation. 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 Change-Id: I075c530f6e9fad7b477383867d52b83bba745662 --- lftools/cli/jenkins/token.py | 6 ++++-- lftools/jenkins/token.py | 14 +++++++------- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/lftools/cli/jenkins/token.py b/lftools/cli/jenkins/token.py index a673b5fc..d0e9b649 100644 --- a/lftools/cli/jenkins/token.py +++ b/lftools/cli/jenkins/token.py @@ -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)) diff --git a/lftools/jenkins/token.py b/lftools/jenkins/token.py index 42c25ed7..eb33bcbd 100644 --- a/lftools/jenkins/token.py +++ b/lftools/jenkins/token.py @@ -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 -- 2.16.6