You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法将变量传递至Python脚本,JIRA子任务创建代码求助

Fixing Variable Passing in Your JIRA Sub-Task Script

Hey there! I can spot exactly what's causing your variable passing issue—let's break it down and get your script working properly step by step.

The Core Issues

  • You’re trying to use the line variable directly inside a single-quoted string: Python doesn’t parse variables inside regular single/double quotes, so it’s sending the literal string "line" to JIRA instead of the actual value from your file.
  • Your data definition and requests.post call are outside the loop, so even if the variable worked, you’d only create a sub-task for the last line in your file (and get an error on the first run since line wouldn’t be defined yet).
  • Manually opening/closing the file can lead to resource leaks if something goes wrong mid-execution.

This version uses a context manager for safe file handling, builds the payload as a Python dictionary (then converts it to JSON properly), and ensures every line from your file is used to create a sub-task:

import requests
import json

# Use `with` to auto-close the file when done (safer than manual close)
with open('/var/lib/rundeck/output.txt') as inf:
    for line in inf:
        # Strip newline/extra whitespace to get a clean JIRA parent key
        parent_key = line.strip()
        print(parent_key)  # Verify we're grabbing the correct key
        
        # Build payload as a dictionary (avoids messy string escaping)
        payload = {
            "fields": {
                "project": {"key": "TECH"},
                "parent": {"key": parent_key},
                "summary": "Create AD List ",
                "description": "",
                "issuetype": {"name": "Sub-task"},
                "customfield_10107": {"id": "10400"}
            }
        }
        
        headers = {'Content-Type': 'application/json'}
        response = requests.post(
            'https://jira.company.com/rest/api/latest/issue/',
            headers=headers,
            data=json.dumps(payload),
            auth=('user', 'pass')
        )
        
        # Optional: Add error checking to debug failures
        if response.status_code == 201:
            print(f"Successfully created sub-task for parent {parent_key}!")
        else:
            print(f"Failed to create sub-task for {parent_key}: {response.text}")

Alternative: String Formatting (If You Prefer)

If you want to stick with a string-based payload, use an f-string (Python 3.6+) or .format() to inject the variable correctly:

import requests

with open('/var/lib/rundeck/output.txt') as inf:
    for line in inf:
        parent_key = line.strip()
        print(parent_key)
        
        headers = {'Content-Type': 'application/json'}
        # Use f-string to insert the parent_key into the JSON string
        data = f'''{{"fields":{{"project":{{"key":"TECH"}},"parent":{{"key":"{parent_key}"}},"summary":"Create AD List ","description":"","issuetype":{{"name":"Sub-task"}},"customfield_10107":{{"id":"10400"}}}}}}'''
        
        response = requests.post(
            'https://jira.company.com/rest/api/latest/issue/',
            headers=headers,
            data=data,
            auth=('user', 'pass')
        )

Quick Tips

  • Always strip whitespace/newlines from lines read from files—JIRA keys won’t work if they have extra characters.
  • Using a dictionary for the payload makes it easier to modify fields later and avoids bugs from string escaping.
  • Adding status code checks helps you quickly debug if JIRA’s API returns an error.

内容的提问来源于stack exchange,提问作者Milister

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:38:54