Search code examples
dockersyntaxgitlabsingle-quotes

Creating parameterized GitLab personal access token from CLI


Based on this example:

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

I've created an equivalent working command for docker that creates the personalised access token from the 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! \"")"

However, when trying to parameterize that command, I am experiencing slight difficulties with the single quote. For example, when I try:

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! \"")"

It returns:

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

Hence, I would like to ask, how can I substitute 'root' with a variable $gitlab_username that has value root?


Solution

  • I believe the error was, unlike I had assumed incorrectly, not necessarily in the command, but mostly in the variables that I passed into the command. The username contained a newline character, which broke up the command. Hence, I included a trim function that removes the newline characters from the incoming variables. The following function successfully creates a personal access token in 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', expires_at: 365.days.from_now); token.set_token('$personal_access_token'); token.save! \"")"
        
    }