Peter Boomsma
Peter Boomsma

Reputation: 9808

Create a json file during Azure DevOps build pipeline

I have a Azure DevOps build pipeline that runs a Cypress test. In that Cypress test we have a test user login with a e-mail and password. On my local system I have the password in a cypress.env.json file.

On the Azure build pipeline I get the message that the password is undefined which makes sense since we put the cypress.env.json file in the .gitignore not to expose it to the repo.

I've created a Azure variable to represent the password: $(ACCOUNT_PASSWORD)

So I think I need to create the cypress.env.json file in the build pipeline and use Azure variables for it, but I can't figure out how to create a file during the build step.

I have this task:

- task: CmdLine@2
  displayName: 'run Cypress'
  inputs:
    script: |
      npm run ci

So I need to add a task before this that creates the cypress.env.json file with the variable that represents the password:

{
  "ACCOUNT_PASSWORD": $(ACCOUNT_PASSWORD)
}

Upvotes: 10

Views: 8738

Answers (2)

OctaviaLo
OctaviaLo

Reputation: 1396

If you want to create a json file using Azure Pipeline's Bash@3 for linux environments, you can do

steps:
  - task: Bash@3
    inputs:
      targetType: "inline"
      script: |
        echo '{"ACCOUNT_PASSWORD": "$(ACCOUNT_PASSWORD)"}' > server/cypress.env.json
        cd server
        echo $(ls)
        cat git-tag.json
  - task: Docker@2
    inputs:
      command: buildAndPush
      ...

The cd echo and cat commands are not necessary. They are only there to log stuff to the console so you can see where the file is and the contents. This task may seem trivial to many but for someone like me with little bash experience even something simple like this task took quite a while to figure out how to debug and get right.

Azure Pipelines runs this bash script in the Build.SourcesDirectory, which is the root of your project. In this example above I have a /server folder which is where I want to put the .json file.

Later on, I run the Docker@2 task which builds my server. The Docker@2 task looks at my Dockerfile which has the instruction COPY . ./ I could be wrong here being new to docker, but my assumption is the Azure VM running the pipeline executes the docker COPY command and copies the file from the Build.SourcesDirectory to a destination inside the docker container.

Upvotes: 2

Shayki Abramczyk
Shayki Abramczyk

Reputation: 41545

You can add a simple PS script that creates the file:

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
      $json = '{
       "ACCOUNT_PASSWORD": $(ACCOUNT_PASSWORD)
      }'
        
      $json | Out-File cypress.env.json
    workingDirectory: '$(Build.SourcesDirectory)'
    pwsh: true # For Linux

In the workingDirectory set the path to where you want the file to be created.

Upvotes: 10

Related Questions