在 Jenkins 中通过 Okta API 创建 Okta 用户

Create Okta user via Okta API in Jenkins

问题

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

如何在 Jenkins 中完成此操作?

初始设置

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

安装上述插件后,您需要 create an Okta API Token and save it in Jenkin's Credential Manager 类型的 Secret Text(并为其指定一个 ID okta-api-代币).

概念验证

The following is a proof-of-concept Jenkinsfile that will use the following plugins to create a user in 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 域。