首页 > 解决方案 > 在 Jenkins 中通过 Okta API 创建 Okta 用户

问题描述

问题

我正在运行 Jenkins 以实现工作自动化并使用 Okta 进行身份验证。我想创建一个可以按需运行以在 Okta 中创建用户的 Jenkins 作业。用户将具有Okta 所需的属性:电子邮件、用户名等。

我怎样才能在詹金斯做到这一点?

标签: jenkinsautomationoktajenkins-cliokta-api

解决方案


初始设置

我编写了一个 Jenkinsfile,它将通过 Okta API 文档创建一个 Okta 用户。在运行此脚本之前,您需要在 Jenkins 中安装以下插件。

安装上述插件后,您需要创建一个 Okta API 令牌并将其保存在 Jenkins 的Secret Text凭证管理器中(并为其提供okta-api-token的 ID )。

概念验证

以下是概念验证 Jenkinsfile,它将使用以下插件在 Okta 中创建用户

pipeline {
    
    agent {
        label 'master'
    }
    
    options {
        buildDiscarder( logRotator( numToKeepStr: "30" ) )
    }
        
    parameters { 
        string(name: 'firstName', description: 'New users first name') 
        string(name: 'lastName', description: 'New users last name') 
        string(name: 'email', description: 'New users email') 
        string(name: 'mobilePhone', description: 'New users phone') 
        password(name: 'password', description: 'Enter Password')
    }
    
    environment {
        oktaDomain = "yourdomain.com"
    }
    
    stages {
        
        stage('Execute') { 
            steps {
                script {
                    
                    // Create payload based on https://developer.okta.com/docs/reference/api/users/#request-example-3
                    def payload = """
                        { "profile":{"firstname": "$firstName","lastNAme": "$lastName","email": "$email","login": "$email","mobilePhone": "$mobilePhone"}, "credentials": { "password:{ "value": "$password"}}}
                    """
                    
                    // Send HTTP Post request with API Token saved in credential manager
                    withCredentials([string(credentialsId: 'apiToken', variable: 'okta-api-token')]) {
                        def response = httpRequest( 
                                        acceptType: 'APPLICATION_JSON', 
                                        contentType: 'APPLICATION_JSON', 
                                        httpMode: 'POST', 
                                        requestBody: payload, 
                                        url: "https://${oktaDomain}/api/v1/users?activate=true", 
                                        customHeaders: [[Authentication: "SSWS ${apiToken}"]]
                                    )
                    }
                    
                    def json = readJSON text: response.content
                    
                    echo json['id']
                        
                }
            }
        }
    }
    
    
    post {
        changed {
            emailext subject: 'Your Okta user has been created',
                body: 'Your Okta user has been created',
                replyTo: '$DEFAULT_REPLYTO',
                to: "$email"
        }
    }
}

假设您按照上面列出的步骤操作,您只需要将oktaDomain变量更改为您的 Okta 域。


推荐阅读