Pass array of files into the parameter of AWSCLI@1 task

Viewed 1049
  • I'm using yaml pipelines
  • I need to run aws cloudformation validate-template '--template-body "file://xxx' command
  • I don't know in advance the filenames to validate
  • So I need to do some kind of 'dir /L' and pass the results into the task
  • this is the task which I'm using
  - task: AWSCLI@1
    displayName: Validate Template
    inputs:
        awsCommand: cloudformation
        awsSubCommand: validate-template
        awsArguments: '--template-body "file://$(Build.ArtifactStagingDirectory)/ec2.yml"'
        awsCredentials: $(awsCredentials)
        failOnStandardError: true
        regionName: eu-west-1

This task validates only one file, how to do 'foreach' loop here?

1 Answers

Pass array of files into the parameter of AWSCLI@1 task

We are passing value to template parameters, so you can't build the - test1 - test2 dynamically.

As a workaround, we can create another pipeline. In this pipeline, we add two powershell tasks. In the first task, we set a variable with tables as the value.

- task: PowerShell@2
     inputs:
       targetType: 'inline'
       script: 'Write-Host "##vso[task.setvariable variable=filenames]files1,files2,files3"'

In the second task, we use rest api to trigger the pipeline.yml pipeline. In the request body, we use the variable set in the first task as the value of the template parameter.

- task: PowerShell@2
  inputs:
    targetType: 'inline'
    script: |
      $token = "PAT"
      $url="https://dev.azure.com/{org}/{pro}/_apis/pipelines/{pipelineId}/runs?api-version=5.1-preview"
      $token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
      
      $JSON = @'
      {
        "templateParameters": {
          "file":"[$(filenames)]"
         },
      }
      '@
      
      $response = Invoke-RestMethod -Uri $url -Headers @{Authorization = "Basic $token"} -Method Post -Body $JSON -ContentType application/json

Below is my test sample:

### pipeline.yml ###
parameters:
  - name: file
    type: object
    default: {}

pool:
  vmImage: 'ubuntu-latest'

steps:  
- template: template1.yml
  parameters:
    files: ${{ parameters.file}}

template.yml:

### template1.yml ###
parameters:
  - name: "files"
    type: object
    default: {}
 
steps:
   - ${{ each file in parameters.files}}:
      - task: PowerShell@2
        inputs:
          targetType: 'inline'
          script: echo "${{ file}}"

Then we run the newly created pipeline to trigger the pipeline.yml pipeline, get the result:

enter image description here

Related