skip to Main Content

I’ve tried to do a pipeline with Python, but I got these errors. Anyone can help me? I am trying to do a Pipeline (CI/CD) for a web app in Python, which needs the: -Web App Server,-Database,-SonarQube. I created the database separately and put the connection information in my code, but I know it’s not the best way to do it. I really appreciate any help you can provide. Follow you can see my Pipeline.yaml and the error that I got.

enter image description here

Here you can see my pipeline:

# # Python to Linux Web App on Azure
# Build your Python project and deploy it to Azure as a Linux Web App.
# Change the python version to one that is appropriate for your application.
# https://docs.microsoft.com/azure/devops/pipelines/languages/python

trigger:
- master

variables:
  # Azure Resource Manager connection created during pipeline creation
  azureServiceConnectionId: '*****************************'

  # Agent VM image name
  vmImageName: ubuntu-latest

  # Environment name
  environmentName: StudentWebappDev

  # Project root folder. Point to the folder containing manage.py file.
  projectRoot: C:codesStudentWebApp

  # Python version: 3.7
  pythonVersion: 3.7

stages:
- stage: Build
  displayName: Build stage
  jobs:
  - job: BuildJob
    pool:
      vmImage: ubuntu-latest
    steps:
    - task: UsePythonVersion@0
      inputs:
        versionSpec: '$(pythonVersion)'
      displayName: 'Use Python $(pythonVersion)'

    - script: |
        python -m venv antenv
        source antenv/bin/activate
        python -m pip install --upgrade pip
        pip install setup
        pip freeze > requirements.txt
        pip install -r requirements.txt
      workingDirectory: $(System.DefaultWorkingDirectory)
      displayName: "Install requirements"

    - task: ArchiveFiles@2
      displayName: 'Archive files'
      inputs:
        rootFolderOrFile: $(System.DefaultWorkingDirectory)
        includeRootFolder: false
        archiveType: zip
        archiveFile: $(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip
        replaceExistingArchive: true

#    - upload: $(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip
#      displayName: 'Upload package'
#      artifact: drop

    - task: PublishBuildArtifacts@1
      inputs:
        pathtoPublish: '$(Build.ArtifactStagingDirectory)'
        artifactName: drop
        publishLocation: 'Container'

    - task: DownloadBuildArtifacts@0
      inputs:
        artifactName: drop
        downloadPath: '$(System.DefaultWorkingDirectory)'

    - task: AzureWebApp@1
      inputs:
        package: $(System.DefaultWorkingDirectory)/**/*.zip  
        azureSubscription: 65e5170f-cbf2-4dc7-99a8-533049eea21d
        appName: AppServiceStudentWeb
      
- stage: Deploy
  displayName: 'Deploy Web App'
  dependsOn: Build
  condition: succeeded()
  jobs:
  - deployment: DeploymentJob
    pool:
      vmImage: ubuntu-latest
    environment: StudentWebappDev
    strategy:
      runOnce:
        deploy:
          steps:
          - task: UsePythonVersion@0
            inputs:
              versionSpec: '$(pythonVersion)'
            displayName: 'Use Python version'`

2

Answers


  1. Chosen as BEST ANSWER

    I fixed this issue but I don't know why my website Python code with flask doesn't work. The Pipeline (azuredevops) running without error but when I try to access the link there is an application error. I will post my code, my yaml and the error. If somebody can help me, I would appreciate it. Thanks in advance

    CODE: MAIN.PY
    
    from flask import Flask, render_template, request, redirect, url_for
    import mysql.connector
    
    
    app = Flask(__name__)
    
    # Database configuration
    db_config = {
        'host': '*************',
        'user': '**************',
        'password': '************',
        'database': '*************',
    }
    
    # Initialize the database connection
    db = mysql.connector.connect(**db_config)
    cursor = db.cursor()
    
    @app.route('/')
    def index():
        # Retrieve the list of students from the database
        cursor.execute("SELECT * FROM students")
        students = cursor.fetchall()
        return render_template('students.html', students=students)
    
    @app.route('/students', methods=['GET', 'POST'])
    def students():
        if request.method == 'POST':
            if 'cadastrar' in request.form:
                email = request.form['email']
                name = request.form['nome']
    
                # Insert the new student into the database
                insert_query = "INSERT INTO students (email, name) VALUES (%s, %s)"
                data = (email, name)
                cursor.execute(insert_query, data)
                db.commit()
    
            elif 'editar' in request.form:
                id = request.form['id']
                email = request.form['email']
                name = request.form['nome']
    
                # Update the student in the database
                update_query = "UPDATE students SET email=%s, name=%s WHERE id=%s"
                data = (email, name, id)
                cursor.execute(update_query, data)
                db.commit()
    
            elif 'excluir' in request.form:
                id = request.form['id']
    
                # Delete the student from the database
                delete_query = "DELETE FROM students WHERE id = %s"
                cursor.execute(delete_query, (id,))
                db.commit()
    
        # Retrieve the list of students from the database
        cursor.execute("SELECT * FROM students")
        students = cursor.fetchall()
        return render_template('students.html', students=students)
    
    if __name__ == '__main__':
        app.run(debug=True, host='0.0.0.0')
    
    PIPELINE.YAML
    trigger:
    - master
    
    variables:
      azureServiceConnectionId: '****************'
      vmImageName: 'ubuntu-latest'
      environmentName: 'StudentWebappDev'
      pythonVersion: '3.11'
      servicePrincipalId: '******************'
      servicePrincipalKey: '***************'
      tenantId: '********************'
      subscriptionId: '************************'
      webAppName: 'AppServiceStudentWeb'
      resourceGroupName: 'devops-rg'
      azureRegion: 'East US'
      projectRoot: $(System.DefaultWorkingDirectory)
    
    stages:
    - stage: Initial
      jobs:
      - job: InitialJob
        steps:
        - script: echo 'This is the initial stage'
          displayName: 'Initialize'
    
    - stage: Build
      displayName: Build stage
      dependsOn: Initial
      jobs:
      - job: BuildJob
        pool:
          vmImage: $(vmImageName)
        steps:
        - task: UsePythonVersion@0
          inputs:
            versionSpec: $(pythonVersion)
          displayName: 'Use Python $(pythonVersion)'
    
        - script: |
            python -m venv antenv
            source antenv/bin/activate
            pip install setup
            python -m pip install --upgrade pip
            pip install -r requirements.txt
          workingDirectory: $(projectRoot)
          displayName: "Install requirements"
    
        - task: ArchiveFiles@2
          displayName: 'Archive files'
          inputs:
            rootFolderOrFile: $(projectRoot)
            includeRootFolder: false
            archiveType: 'zip'
            archiveFile: $(Build.ArtifactStagingDirectory)/$(Build.BuildId).zip
            replaceExistingArchive: true
    
        - task: PublishBuildArtifacts@1
          inputs:
            PathtoPublish: $(Build.ArtifactStagingDirectory)
            ArtifactName: 'drop'
            publishLocation: 'Container'
    
        - task: DownloadBuildArtifacts@0
          inputs:
            artifactName: 'drop'
            downloadPath: $(projectRoot)
    
    - stage: Deploy
      displayName: Deploy stage
      dependsOn: Build
      jobs:
      - job: DeployJob
        steps:
        - task: AzureCLI@2
          inputs:
            azureSubscription: 'Visual Studio Enterprise Subscription (94f99625-f59c-45a5-a0d5-af8d26fd612c)'
            scriptType: 'bash'
            scriptLocation: 'inlineScript'
            inlineScript: |
              pwd
              ls -l
              az login --service-principal -u $(servicePrincipalId) -p $(servicePrincipalKey) --tenant $(tenantId)
              az account set --subscription $(subscriptionId)
              cd $(projectRoot)
              az webapp up --name $(webAppName) --resource-group $(resourceGroupName) --location "East US" --sku F1 --runtime "PYTHON|3.11"
              az webapp config set --python-version 3.11
              az webapp config appsettings set --name $(webAppName) --resource-group $(resourceGroupName) --settings FLASK_APP=main.py  
          displayName: 'Deploy Application'
    

    After running, I got this screen: image of error received

    LOGS: https://pastebin.com/uUfWUL1m

    Any help would be appreciated as I'm tired of trying to solve this problem alone and I can't, thank you very much.


  2. I copied your yaml, confirm Build stage part is working. Task AzureWebApp@1 is version 1.x(suggest to add appType as it’s required).

    Check your error screenshot, suppose the Azure App service deploy task(version 4.229.0) should exist in your Deploy stage, but i cannot find it in your yaml.

    Different stages will execute on different agents(machines). If drop.zip is created in Build stage, to use it in Deploy stage, you need to download the artifact on Deploy stage. Please notice the download path used.

    You can check the sample for your reference.

    If you still have queries, please show the completed yaml.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search