从 CLI 创建参数化的 GitLab 个人访问令牌

Creating parameterized GitLab personal access token from CLI

基于this示例:

sudo gitlab-rails runner "token = User.find_by_username('automation-bot').personal_access_tokens.create(scopes: [:read_user, :read_repository], name: 'Automation token'); token.set_token('token-string-here123'); token.save!"

我已经为 docker 创建了一个等效的工作命令,它从 CLI 创建个性化访问令牌:

output="$(sudo docker exec -i 5303124d7b87 bash -c "gitlab-rails runner \"token = User.find_by_username('root').personal_access_tokens.create(scopes: [:read_user, :read_repository], name: 'Automation token'); token.set_token('token-string-here123'); token.save! \"")"

但是,在尝试参数化该命令时,我在使用单引号时遇到了一些困难。例如,当我尝试:

output="$(sudo docker exec -i 5303124d7b87 bash -c "gitlab-rails runner \"token = User.find_by_username($gitlab_username).personal_access_tokens.create(scopes: [:read_user, :read_repository], name: 'Automation-token'); token.set_token('token-string-here123'); token.save! \"")"

它returns:

undefined local variable or method `root' for main:Object

因此,我想问一下,如何将'root'替换为一个值为root的变量$gitlab_username

我相信错误是,与我假设错误不同,错误不一定在命令中,但主要是在我传递给命令的变量中。用户名包含一个换行符,它打断了命令。因此,我包含了一个 trim 函数,用于从传入变量中删除换行符。以下函数在 GitLab 中成功创建个人访问令牌:

create_gitlab_personal_access_token() {
    docker_container_id=$(get_docker_container_id_of_gitlab_server)
    
    # trim newlines
    personal_access_token=$(echo $GITLAB_PERSONAL_ACCESS_TOKEN | tr -d '\r')
    gitlab_username=$(echo $gitlab_server_account | tr -d '\r')
    token_name=$(echo $GITLAB_PERSONAL_ACCESS_TOKEN_NAME | tr -d '\r')
    
        
    # Create a personal access token    
    output="$(sudo docker exec -i $docker_container_id bash -c "gitlab-rails runner \"token = User.find_by_username('$gitlab_username').personal_access_tokens.create(scopes: [:read_user, :read_repository], name: '$token_name'); token.set_token('$personal_access_token'); token.save! \"")"
    
}