Víctor
Víctor

Reputation: 3039

Inline PythonScript Azure Pipelines task in external file

I am developing a Azure task template, and I have a large .py file that I want to be executed in one step

  - task: PythonScript@0
    displayName: 'Run a Python script'
    inputs:
      scriptSource: inline
      script: |
        ... really long python code

It's possible to store the code in another file, at the same level of the yml template, and consume it from there? Or what would be the best approach to keep the template clean?

I know that it's possible to use scriptSource

  - task: PythonScript@0
    displayName: 'Run a Python script'
    inputs:
      scriptSource: 'filePath'
      scriptPath: 'my_python.py'
      arguments: '${{ parameters.my_param }}'

But as the template is in another repository than the repository ran in the pipeline, I don't think that I can reach that my_python.py without downloading it with a wget, or cloning, or doing additional steps. I am right?

Regards!

Upvotes: 2

Views: 2827

Answers (1)

Krzysztof Madej
Krzysztof Madej

Reputation: 40613

To use a template from another repo you need to define repository source like here:

# Repo: Contoso/LinuxProduct
# File: azure-pipelines.yml
resources:
  repositories:
    - repository: templates
      type: github
      name: Contoso/BuildTemplates

steps:
- template: common.yml@templates  # Template reference

Once you have you need to just checkout this repo:

# Repo: Contoso/LinuxProduct
# File: azure-pipelines.yml
resources:
  repositories:
    - repository: templates
      type: github
      name: Contoso/BuildTemplates

steps:
- checkout: self
- checkout: templates #this download whole repo
- template: common.yml@templates  # Template reference

Now you need to figure out where it is downloaded ;)

Multiple repositories: If you have multiple checkout steps in your job, your source code is checked out into directories named after the repositories as a subfolder of s in (Agent.BuildDirectory). If (Agent.BuildDirectory) is C:\agent\_work\1 and your repositories are named tools and code, your code is checked out to C:\agent\_work\1\s\tools and C:\agent\_work\1\s\code.

So if you have script in scripts folder in templates repo you will find it in $(Agent.BuildDirectory)\templates\scripts\script.py.

So then you can use it like this:

  - task: PythonScript@0
    displayName: 'Run a Python script'
    inputs:
      scriptSource: 'filePath'
      scriptPath: '$(Agent.BuildDirectory)\templates\scripts\script.py'
      arguments: '${{ parameters.my_param }}'

Upvotes: 1

Related Questions