membersound
membersound

Reputation: 86747

How to add custom script statements to a gitlab job template?

I want to create a common .deploy template.

Every job that inherits from this template should be able to add some custom script logic in between the script from the inherited template. But how?

Example:

.deploy
  stage: deploy
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
  before_script:
    - ...
  script:
    - touch .env
    - echo "SOME_COMMON_KEY=VALUE" >> .env
    - $$PSEUDOCODE / PLACE YOUR CUSTOM LOGIC HERE
    - ssh -i $SSH_ -o "StrictHostKeyChecking=no" $USER@$SERVER
    - scp -i $SSH docker-compose.yml .env $USER@$SERVER:~/test/
    - ssh -i $SSH $USER@$SERVER "docker-compose up"...
    
    
deploy_test:
  extends: .deploy
  variables:
    USER: test
    SERVER: test
  script:
    #TODO how to add custom statements in place of the $$PSEUDOCODE ?
    
    
deploy_prod:
  extends: .deploy
  variables:
    USER: prod
    SERVER: prod
  script:
    #TODO how to add custom statements in place of the $$PSEUDOCODE ?

So how could I add some custom statements in place of the $$PSEUDOCODE line?

Upvotes: 1

Views: 1767

Answers (2)

sytech
sytech

Reputation: 40891

One thing you can do is use eval on an environment variable.

.deploy:
  # ...
  variables:
    USER_SCRIPT:
      value: ""
      description: "The contents of this variable will be executed with `eval` during the job script."
  script:
    - touch .env
    - echo "SOME_COMMON_KEY=VALUE" >> .env
    - eval "${USER_SCRIPT}"
    # ...

Another way users can insert logic in an extended job before or after before_script and script: is to use a !reference tag.

For example, to insert logic after before_script: but before script:

another_job:
  extends: .deploy
  before_script:
    - echo "additional steps before before_script:"
    - !reference [.deploy, before_script]
    - echo "Additional step after before_script"
  script:
    - echo "Additional steps before script:"
    - !reference [.deploy, script]
    - echo "Additional steps after script:"

Upvotes: 3

Nicolas Pepinster
Nicolas Pepinster

Reputation: 6221

Could you have the same code shared by your 2 jobs ? If yes, you can do it using YAML anchors for script

In your example, it can give :

.pseudo_code: &pseudo_code
  - echo "Hello $USER on $SERVER"

.deploy:
  stage: deploy
  rules:
    - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH
  before_script:
    - ...
  script:
    - touch .env
    - echo "SOME_COMMON_KEY=VALUE" >> .env
    - *pseudo_code
    - ssh -i $SSH_ -o "StrictHostKeyChecking=no" $USER@$SERVER
    - scp -i $SSH docker-compose.yml .env $USER@$SERVER:~/test/
    - ssh -i $SSH $USER@$SERVER "docker-compose up"...

deploy_test:
  extends: .deploy
  variables:
    USER: test
    SERVER: test

deploy_prod:
  extends: .deploy
  variables:
    USER: prod
    SERVER: prod

Upvotes: 1

Related Questions