在shell脚本中读取/保存Azure DevOps管道变量

rpppsulh  于 2022-11-17  发布在  Shell
关注(0)|答案(4)|浏览(184)

我正在使用Azure DevOps进行一些应用程序部署。我需要有一个保存的可变内部版本号,每次成功进行构建时都会更新,并将apk/ipa发送到商店。
现在,从我在Azure文档和StackOverflow上的其他帖子中读到的内容来看,我是这样设置脚本的。
这是我的管道变量x1c 0d1x
这是我当前的脚本

输出为:

所以,它似乎更新了我的局部变量,但不是我的管道变量。我不确定为什么,因为这是在任何地方提供的示例。
资料来源:

谢谢你的帮助!
编辑1:好的,看起来有一个变量/函数叫做counter。我还没有弄清楚如何使用它,但是正在研究它。
编辑2:更新我的azure-pipelines.yml

variables:
  major: 1
  minor: 0
  patch: 0
  build: $[counter(variables['patch'], 1)]

在我的管道上,它看起来像

而我的快速通道(Ruby脚本)通道看起来像这样

lane :tf do
        `echo $major`
        `echo $minor`
        `echo $patch`
        `echo $build` # Nothing
        `echo $MAJOR`
        `echo $MINOR`
        `echo $PATCH`
        `echo $BUILD` # Nothing
        `echo $(major)` # fails
end

那些什么也没显示。
这个Azure DevOps非常令人沮丧。它在这里说我可以对这个变量进行bash调用。x1c4d 1x

vmdwslir

vmdwslir1#

与宏语法一起使用变量在执行任务之前会在运行时扩展,这就是为什么最后一个日志中有值'1',即使该值在上一步中设置为'2'
https://learn.microsoft.com/en-us/azure/devops/pipelines/process/variables?view=azure-devops&tabs=yaml%2Cbatch#runtime-expression-syntax
请尝试改用运行时表达式,它在运行时扩展

q8l4jmvw

q8l4jmvw2#

两个解决方案。

1.使用计数器表达式。

counter(<prefix>, <feed>)
计数器表达式用于管道,它有两个参数:prefix和seed。seed基于prefix。
当前缀被设置并且第一次运行时,计数器结果将从馈送值开始。但是对于基于相同前缀的后续运行,计数器结果将忽略馈送值,它将是“上次计数器结果+ 1”

2,直接更改管道定义。

例如,我可以使用下面的python代码来获取和更改经典管道的变量:

import json
import requests

org_name = "xxx"
project_name = "xxx"
pipeline_definition_id = "xxx"
personal_access_token = "xxx"

key = 'variables'
var_name = 'BUILDNUMBER'

url = "https://dev.azure.com/"+org_name+"/"+project_name+"/_apis/build/definitions/"+pipeline_definition_id+"?api-version=6.0"

payload={}
headers = {
  'Authorization': 'Basic '+personal_access_token
}

response = requests.request("GET", url, headers=headers, data=payload)
print(response.text)
json_content = response.text
def get_content_of_json(json_content, key, var_name):
    data = json.loads(json_content)
    return data[key][var_name].get('value')

def change_content_of_json(json_content, key, var_name):
    data = json.loads(json_content)
    data[key][var_name]['value'] = str(int(get_content_of_json(json_content,key,var_name)) + 1)
    return data

json_data = change_content_of_json(json_content, key, var_name)

url2 = "https://dev.azure.com/"+org_name+"/"+project_name+"/_apis/build/definitions/"+pipeline_definition_id+"?api-version=6.0"

payload2 = json.dumps(json_data)
headers2 = {
  'Authorization': 'Basic '+personal_access_token,
  'Content-Type': 'application/json'
}

response2 = requests.request("PUT", url2, headers=headers2, data=payload2)

为您编写一个JSON演示,您可以将其导入到DevOps中,并在此基础上设计自己的经典管道:

{
    "options": [
        {
            "enabled": false,
            "definition": {
                "id": "5d58cc01-7c75-450c-be18-a388ddb129ec"
            },
            "inputs": {
                "branchFilters": "[\"+refs/heads/*\"]",
                "additionalFields": "{}"
            }
        },
        {
            "enabled": false,
            "definition": {
                "id": "a9db38f9-9fdc-478c-b0f9-464221e58316"
            },
            "inputs": {
                "workItemType": "Bug",
                "assignToRequestor": "true",
                "additionalFields": "{}"
            }
        }
    ],
    "variables": {
        "BUILDNUMBER": {
            "value": "7"
        },
        "system.debug": {
            "value": "false",
            "allowOverride": true
        }
    },
    "properties": {},
    "tags": [],
    "_links": {
        "self": {
            "href": "https://dev.azure.com/BowmanCP/c6358b04-e91a-4bd1-a894-1adb543134d6/_apis/build/Definitions/359?revision=11"
        },
        "web": {
            "href": "https://dev.azure.com/BowmanCP/c6358b04-e91a-4bd1-a894-1adb543134d6/_build/definition?definitionId=359"
        },
        "editor": {
            "href": "https://dev.azure.com/BowmanCP/c6358b04-e91a-4bd1-a894-1adb543134d6/_build/designer?id=359&_a=edit-build-definition"
        },
        "badge": {
            "href": "https://dev.azure.com/BowmanCP/c6358b04-e91a-4bd1-a894-1adb543134d6/_apis/build/status/359"
        }
    },
    "jobAuthorizationScope": 2,
    "jobTimeoutInMinutes": 60,
    "jobCancelTimeoutInMinutes": 5,
    "process": {
        "phases": [
            {
                "steps": [
                    {
                        "environment": {},
                        "enabled": true,
                        "continueOnError": false,
                        "alwaysRun": false,
                        "displayName": "PowerShell Script",
                        "timeoutInMinutes": 0,
                        "retryCountOnTaskFailure": 0,
                        "condition": "succeeded()",
                        "task": {
                            "id": "e213ff0f-5d5c-4791-802d-52ea3e7be1f1",
                            "versionSpec": "2.*",
                            "definitionType": "task"
                        },
                        "inputs": {
                            "targetType": "inline",
                            "filePath": "",
                            "arguments": "",
                            "script": "# Write your PowerShell commands here.\n\nWrite-Host \"Hello World\"\n\npip install requests\n",
                            "errorActionPreference": "stop",
                            "warningPreference": "default",
                            "informationPreference": "default",
                            "verbosePreference": "default",
                            "debugPreference": "default",
                            "progressPreference": "silentlyContinue",
                            "failOnStderr": "false",
                            "showWarnings": "false",
                            "ignoreLASTEXITCODE": "false",
                            "pwsh": "false",
                            "workingDirectory": "",
                            "runScriptInSeparateScope": "false"
                        }
                    },
                    {
                        "environment": {},
                        "enabled": true,
                        "continueOnError": false,
                        "alwaysRun": false,
                        "displayName": "Run a Python script",
                        "timeoutInMinutes": 0,
                        "retryCountOnTaskFailure": 0,
                        "condition": "succeeded()",
                        "task": {
                            "id": "6392f95f-7e76-4a18-b3c7-7f078d2f7700",
                            "versionSpec": "0.*",
                            "definitionType": "task"
                        },
                        "inputs": {
                            "scriptSource": "inline",
                            "scriptPath": "",
                            "script": "import json\nimport requests\n\n\norg_name = \"BowmanCP\"\nproject_name = \"BowmanCP\"\npipeline_definition_id = \"359\"\npersonal_access_token = \"OnhlbXFzd29hdXJrdGhvNGJhemJza3hhenZldnRhbXhhZTVhNDMycXZoNzRicmo3YTZjc3E=\"\n\nkey = 'variables'\nvar_name = 'BUILDNUMBER'\n\nurl = \"https://dev.azure.com/\"+org_name+\"/\"+project_name+\"/_apis/build/definitions/\"+pipeline_definition_id+\"?api-version=6.0\"\n\npayload={}\nheaders = {\n  'Authorization': 'Basic '+personal_access_token\n}\n\nresponse = requests.request(\"GET\", url, headers=headers, data=payload)\nprint(response.text)\njson_content = response.text\ndef get_content_of_json(json_content, key, var_name):\n    data = json.loads(json_content)\n    return data[key][var_name].get('value')\n\ndef change_content_of_json(json_content, key, var_name):\n    data = json.loads(json_content)\n    data[key][var_name]['value'] = str(int(get_content_of_json(json_content,key,var_name)) + 1)\n    return data\n\njson_data = change_content_of_json(json_content, key, var_name)\n\n\nurl2 = \"https://dev.azure.com/\"+org_name+\"/\"+project_name+\"/_apis/build/definitions/\"+pipeline_definition_id+\"?api-version=6.0\"\n\npayload2 = json.dumps(json_data)\nheaders2 = {\n  'Authorization': 'Basic '+personal_access_token,\n  'Content-Type': 'application/json'\n}\n\nresponse2 = requests.request(\"PUT\", url2, headers=headers2, data=payload2)\n",
                            "arguments": "",
                            "pythonInterpreter": "",
                            "workingDirectory": "",
                            "failOnStderr": "false"
                        }
                    }
                ],
                "name": "Agent job 1",
                "refName": "Job_1",
                "condition": "succeeded()",
                "target": {
                    "executionOptions": {
                        "type": 0
                    },
                    "allowScriptsAuthAccessOption": false,
                    "type": 1
                },
                "jobAuthorizationScope": 2
            }
        ],
        "target": {
            "agentSpecification": {
                "identifier": "windows-2019"
            }
        },
        "type": 1
    },
    "repository": {
        "properties": {
            "cleanOptions": "0",
            "labelSources": "0",
            "labelSourcesFormat": "$(build.buildNumber)",
            "reportBuildStatus": "true",
            "fetchDepth": "1",
            "gitLfsSupport": "false",
            "skipSyncSource": "false",
            "checkoutNestedSubmodules": "false"
        },
        "id": "421488b2-be68-4b8e-8faf-8302da314071",
        "type": "TfsGit",
        "name": "XunitTest_Auto",
        "url": "https://dev.azure.com/BowmanCP/BowmanCP/_git/XunitTest_Auto",
        "defaultBranch": "refs/heads/main",
        "clean": "false",
        "checkoutSubmodules": false
    },
    "processParameters": {},
    "quality": 1,
    "authoredBy": {
        "displayName": "Bowman Zhu",
        "url": "https://spsprodsea2.vssps.visualstudio.com/A64545e3d-c12d-4c81-b77f-4de83783d9bd/_apis/Identities/af91e22a-cc35-4c8e-8af3-f49c4a1b9b6a",
        "_links": {
            "avatar": {
                "href": "https://dev.azure.com/BowmanCP/_apis/GraphProfile/MemberAvatars/aad.ZGU3N2NiY2YtZTgzYy03ZDkwLWI0YTYtOTk3Nzg3NDczMzBl"
            }
        },
        "id": "af91e22a-cc35-4c8e-8af3-f49c4a1b9b6a",
        "uniqueName": "xxx@xxx.com",
        "imageUrl": "https://dev.azure.com/BowmanCP/_apis/GraphProfile/MemberAvatars/aad.ZGU3N2NiY2YtZTgzYy03ZDkwLWI0YTYtOTk3Nzg3NDczMzBl",
        "descriptor": "aad.ZGU3N2NiY2YtZTgzYy03ZDkwLWI0YTYtOTk3Nzg3NDczMzBl"
    },
    "drafts": [],
    "queue": {
        "_links": {
            "self": {
                "href": "https://dev.azure.com/BowmanCP/_apis/build/Queues/18"
            }
        },
        "id": 18,
        "name": "Azure Pipelines",
        "url": "https://dev.azure.com/BowmanCP/_apis/build/Queues/18",
        "pool": {
            "id": 9,
            "name": "Azure Pipelines",
            "isHosted": true
        }
    },
    "id": 359,
    "name": "ChangeVariable",
    "url": "https://dev.azure.com/BowmanCP/c6358b04-e91a-4bd1-a894-1adb543134d6/_apis/build/Definitions/359?revision=11",
    "uri": "vstfs:///Build/Definition/359",
    "path": "\\",
    "type": 2,
    "queueStatus": 0,
    "revision": 11,
    "createdDate": "2022-11-07T10:14:18.003Z",
    "project": {
        "id": "c6358b04-e91a-4bd1-a894-1adb543134d6",
        "name": "BowmanCP",
        "url": "https://dev.azure.com/BowmanCP/_apis/projects/c6358b04-e91a-4bd1-a894-1adb543134d6",
        "state": 1,
        "revision": 178,
        "visibility": 0,
        "lastUpdateTime": "2022-09-05T06:02:02.693Z"
    }
}
7uzetpgm

7uzetpgm3#

它似乎更新了我的局部变量,但没有更新我的管道变量
请参阅本文档:在脚本中设置变量
管道中的脚本可以定义变量,以便管道中的某个后续步骤可以使用该变量。在脚本中设置变量
用于更新管道变量值的方法正确。
它不会在当前任务上起作用,但更新后的值可用于后续任务。
例如:

steps:

- bash: |
   echo $(TestVariable)
   echo "##vso[task.setvariable variable=TestVariable;]2"
   
  displayName: 'Bash Script'

- bash: |
   echo $(TestVariable)

对于关于使用计数器表达式的要求,可以参考我的另一张票:Azure开发运营:发行版本

gzjq41n4

gzjq41n44#

我最终使用了这个公式,它不需要黑进国家安全局和联邦调查局来更新版本号。这不是我想要的,但不管怎样,我会处理这个ATM机。

然后在我的ruby脚本中使用ENV['BUILDNUMBER'],它用计数器读取env变量。这是我需要的解决方案类型,尽管它并不完全符合我的要求。

相关问题