Karthik
Karthik

Reputation: 349

Jenkins job unable to pass integer parameters into python script during build

I have a python script that I tested on an EC2 instance, which works perfectly fine on the server but when I try to pass the same parameters from Jenkins job as shown below. I get the error message:

Security Group Created sg-ca09bcae in vpc vpc-d79691b9. Traceback (most recent call last): File "./create_sg.py", line 32, in 'FromPort': int(FROM_PORT_1.strip("")), marked build as failure Finished: FAILURE> ValueError: invalid literal for int() with base 10: 'within' Build step 'Execute shell'

Jenkins Job Parameters

I'm pretty sure the error is because of the string parameter that I'm passing through Jenkins parameters but there isn't an option to send both From and To ports as integers in jenkins parameters.

How can I set the parameters to an integer within Jenkins build job?

Python code to create SG:

#!/usr/bin/env python

import sys
import boto3
from botocore.exceptions import ClientError
region = "us-west-1"

VPC_ID=sys.argv[1]
SECURITY_GROUP_NAME=sys.argv[2]
DESCRIPTION=sys.argv[3]
IP_PROTOCOL_1=sys.argv[4]
FROM_PORT_1=sys.argv[5]
TO_PORT_1=sys.argv[6]
CIDR_IP_1=sys.argv[7]


ec2 = boto3.client('ec2')

response = ec2.describe_vpcs()

vpc_id = VPC_ID

try:
    response = ec2.create_security_group(GroupName=SECURITY_GROUP_NAME,Description=DESCRIPTION,VpcId=VPC_ID)
    security_group_id = response['GroupId']
    print('Security Group Created %s in vpc %s.' % (security_group_id, vpc_id))

    data = ec2.authorize_security_group_ingress(
        GroupId=security_group_id,
        IpPermissions=[
            {'IpProtocol': IP_PROTOCOL_1,
             'FromPort': int(FROM_PORT_1),
             'ToPort': int(TO_PORT_1),
             'IpRanges': [{'CidrIp': CIDR_IP_1}]}
        ]
    )
    print('Ingress Successfully Set %s' % data)
except ClientError as e:
    print(e)

@nosklo, Suggested I try the following:

VPC_ID=sys.argv[1] 
SECURITY_GROUP_NAME=sys.argv[2]
DESCRIPTION=' '.join(sys.argv[3:-4])
IP_PROTOCOL_1=sys.argv[-4]
FROM_PORT_1=sys.argv[-3]
TO_PORT_1=sys.argv[-2] 
CIDR_IP_1=sys.argv[-1]

With which the ports are listed as 0 vs the values that I passed in the parameters.

Upvotes: 0

Views: 3456

Answers (2)

Peter Westlake
Peter Westlake

Reputation: 5036

I haven't any way to test this, but the error message shows the invalid int value as the word "within". That suggests that the Description parameter is being substituted directly onto a command line without any quoting, so that sys.argv[5] would indeed be the string "within". You might try including quotes around the description: `"Security group within dev environment".

Upvotes: 1

Dash Winterson
Dash Winterson

Reputation: 1295

I think what you're looking for is os.getenv:

import os

VPC_ID = os.getenv('VPC_ID')

print(VPC_ID)

should work.

Upvotes: 0

Related Questions