CyberKeeda In Social Media
Showing posts with label Automation. Show all posts
Showing posts with label Automation. Show all posts

Python Script to create new JIRA tickets using JIRA API

 


Python Script with below JIRA operations

  • Fetch JIRA ticket details using JIRA API.
  • Create JIRA ticket using JIRA API


Information to collect before using script.
  • Get your organization JIRA URL handy with you.
    • Can be retrieved from any JIRA ticket URL, respective URL has FQDN that's the JIRA URL dedicated for your organization.
  • Know your JIRA project/space name.
    • Login to any of your JIRA tickets.
    • From top navigation panel, select projects and check the name associated with the project, project name will be single word without any space.
  • Know JIRA field/mandatory fields within your ticket, before you create a ticket via API.
    • Will know how to fetch details about it from our python script, get_jita_details method can be used to get details for field

Script has one class and two methods, will know how and when to use one by one.
  • JiraHandler ( Class )
  • get_jira_details ( Method ) - Can be used to fetch JIRA ticket details.
  • create_jira_cr_ticket( Method ) - Can be used to create new JIRA ticket. 
Note : 
  • For simplicity, i have used basic authentication method to authenticate to JIRA servers, although for some sort of security instead of using plain text password, have encoded it using base64 authentication.
  • You need to ready with the Payload data json file, before you go ahead and create a new JIRA ticket, this file can be of any name but please content is in JSON format.
        payload_data.json
 

Script.

import requests
import json
import base64
from requests.auth import HTTPBasicAuth

# Inorder to encrypt/decrypt your credentials using base64 module as below.
# To encode --> base64.b64encode(bytes("random", "utf-8"))
# To decode --> base64.b64decode("cmFuZG9t").decode("utf-8")

class JiraHandler:
      
    def __init__(self, username):
        print('Loading Instnace variables...')
        self.username = username
        self.securestring = base64.b64decode("replaceItwithYourCredential").decode("utf-8")
        self.url = "https://jira.yourownjiradomain.com/rest/api/2/issue/"

    def get_jira_details(self,jira_ticket):

        try :
            
            auth = HTTPBasicAuth(self.username, self.securestring)
            get_details_url = self.url + jira_ticket

            headers = {
               "Accept": "application/json"
            }
            
            print("retrieveing", jira_ticket, "details...")
            response = requests.request(
               "GET",
               get_details_url,
               headers=headers,
               auth=auth
            )
            print(json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": ")))
            
        except Exception as e:
            return e



    def create_jira_cr_ticket(self, filename):
        get_details_url = self.url

        auth = HTTPBasicAuth(self.username, self.securestring)

        headers = {
           "Accept": "application/json",
           "Content-Type": "application/json"
        }
        try:
            with open(filename, "r") as re_read_file:
                payload = re_read_file.read()
                print("Creating new JIRA...")
                response = requests.request(
                   "POST",
                   get_details_url,
                   data=payload,
                   headers=headers,
                   auth=auth
                )
                print(json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": ")))
        except Exception as filenotfound:
            print("Can't load file..", filenotfound)



         


How to use it, 
  • Load Instance variable by calling class and provide your JIRA username as an input.
# Initiate Class and load instance variable.
d = JiraHandler("your_JIRA_Username")
  • Call method get_jira_details and add JIRA ticket as method input, for example if we want to get details about a specific JIRA ticket CKPROJ-6162, we must call the method as described below.
# Call below method to get JIRA ticket details.
d.get_jira_details("CKPROJ-6162")
  • Before calling method create_jira_cr_ticket, dump json content within a json file, for instance i have created a file named payload_data.json and it looks somehow like below.
    • Thinking how to find it, use method get_jira_details, it will give you an idea for the field used within your project's jira ticket.
{
        "fields": {
           "project":
           {
              "key": "CKPROJ"
           },
           "summary": "My Dummy Ticket created by REST API",
           "description": "Dummy CR for REST API Test",
           "confluence": "Dummy Confluence Page Link",
           "verification_steps": "Verification Plan",
           "issuetype": {
              "name": "Change Request"
               }
           }
        }
Once you are ready with the payload data, save it within a JSON file and call method providing payload_data.json file as an input to it, as an output script will return the JIRA ticket details.
# Call below method to create new JIRA ticket
d.create_jira_cr_ticket("C:\\Users\\cyberkeeda\\payload_data.json")

Hope this script can have help in any sort, for any help comment please.


Read more ...

YAML Cheat Sheet

 


YAML or YML has become a must know data serialization language for System Administrators, it is widely used in many of the configuration management, containerization platforms , Orchestration applications, Infra as a Code, and many more, and because of it's human readable formats, it's widely accepted and used.

YAML usage in some widely used sysadmin tools.
  • Ansible
  • Docker
  • Kubernetes
  • AWS CloudFormation.
  • TerraForm
Here in this blog post, i have kept some of the YAML cheat sheets, which can help you to craft your own or to read some yaml files.

Key Value

A variety of data is structured in the form of key value pairs.

Key - Items written on left side of data ( Fruit, Drink, Vegetable )
Value Items written on left side of data ( Orange, Juice, Spinach)
Important: Space after :


YAML Key Value Pair
Fruit: Orange Drink: Juice Vegetable: Spinach


List or Array

A representation of List Smartphone type and Brand type in YAML format.


YAML List/Array
Smartphones:
- IOS - Android Brands: - Apple - Nokia - Micromax
- Vivo


Dictionary

A representation of Employee named 26 year old male named as Jignesh working as Web developer data in dictionary type in YAML format.


YAML Dictionary/Map
Employee: Name: Jignesh Sex: Male Age: 26 Title: Web Developer


Dictionary inside List

A representation of multiple list of Fruits (Mango, Guava, Banana) and their individual specification mapped in dictionary value ( Calories, Fat, Carbs )


YAML Dictionary inside List
Fruits: - Mango: Calories: 95 Fat: 0.3 Carbs: 25 - Guava: Calories: 105 Fat: 0.4 Carbs: 27 - Banana: Calories: 45 Fat: 0.1 Carbs: 11 Vegetables: - Onion: Calories: 25 Fat: 0.1 Carbs: 6 - Potato: Calories: 22 Fat: 0.2 Carbs: 4.8 - Ginger: Calories: 8 Fat: 0.1 Carbs: 1.9


List inside Dictionary

A representation of Employee named 26 year old male named as Jignesh working as Web developer data in dictionary type.

Employee Shail has been assigned two Projects ( Login and Logout Form ), a representation of List data.

YAML List inside Dictionary
Employee: Name: Shail Sex: Male Age: 28 Title: Web Developer
  Projects:
- Login Form - Logout Form

For sure there are many more to update in the YAML cheat list, but will begin with these..

Read more ...

How to export and import Jenkins job.

If you have multiple jenkins instances, there might be a requirement to export an existing jenkins job, that could be further imported into the newer jenkins instance.

We will learn how to do the export/import of jenkins job using jenkins cli.

How to Export existing Jenkins job.

  • Jenkins Home Page 
  • Manage Jenkins
  • Jenkins CLI.
  • Download  jenkins-cli.jar


  • Click on Jenkins CLI.




Once file "jenkins-cli.jar" file has been downloaded, we are ready to export our Jenkins job, lets do it.
Open your terminal and run the below commands.

Authenticate and List down your jobs to identify the one, which one you want to export, replace "your-jenkins-server-url:your_server_port" from your source jenkins server's url and port.

cyberkeeda@jenkins-master:~$ java -jar jenkins-cli.jar -s "http://your-jenkins-server-url:your_server_port" -auth UserName:Password  list-jobs

djpass-ansible
djpass-docker-app
docker ps

Now, from above enlisted jobs i want to export the one named as "djpass-docker-app".
Run the below command and replace the highlighted one by yours.

cyberkeeda@jenkins-master:~$  java -jar jenkins-cli.jar -s "http://your-jenkins-server-url:your_server_port" -auth UserName:Password get-job djpass-docker-app > djpass-docker-app.xml

We have successfully exported our jenkins job named as "djpass-docker-app" as an xml file named as "djpass-docker-app.xml"

How to import Jenkins job to different Jenkins server.

  • Go to your new jenkins server dashboard, where you want to import.
  • Follow the same above steps to download the jenkins-cli.jar file.
  • Ensure you are ready with "jenkins-cli.jar" and your exported jenkins job XML file with you.
Now run the below command to import your jenkins job xml file to new jenkins server.
Note : Replace the highlighted one by yours.

Preview:
cyberkeeda@jenkins-slave:~$  java -jar jenkins-cli.jar -s "http://your-Newjenkins-server-url:your_server_port" -auth UserName:Password create-job new-djpass-docker-app < djpass-docker-app.xml

Hoah !!! Thats it, check your dashboard to verify the same.

Read more ...

AWK equivalent in Windows CMD




Missing AWK on Windows ?  for /f  may help you.
Lets see how can we implement the same.


Example.

C:\Users\Cyberkeeda>netsh interface show interface

Admin State    State          Type             Interface Name
-------------------------------------------------------------------------
Enabled        Connected      Dedicated        Wi-Fi
Enabled        Connected      Dedicated        VMware Network Adapter VMnet1
Enabled        Connected      Dedicated        VMware Network Adapter VMnet8
Enabled        Disconnected   Dedicated        Ethernet

Lets assume we have saved the same within a file in linux names as file.txt

Within Linux, to gather the State of interfaces, we use the below command.

cat file.txt| awk '{print $2}'

State
Connected
Connected
Connected
Disconnected

In Windows, it can be accomplished with FOR /F

C:\Users\cyberkeeda>for /f "tokens=2" %a in ('netsh interface show interface') do @echo %a

State
Connected
Connected
Connected
Disconnected

Now, if wish to add two values .

cat file.txt| awk '{print $1 " " $2}'

Admin State
-------------------------------------------------------------------------
Enabled Connected
Enabled Connected
Enabled Connected
Enabled Disconnected

Same can be accomplished within Windows as

C:\Users\cyberkeeda>for /f "tokens=1,2" %a in ('netsh interface show interface') do @echo %a %b
Admin State
-------------------------------------------------------------------------
Enabled Connected
Enabled Connected
Enabled Connected
Enabled Disconnected

In case, if you want to additional string along with the variable.

C:\Users\cyberkeeda>for /f "tokens=1,2" %a in ('netsh interface show interface') do @echo Boot Stats= %a Ethernet stat= %b


Now in case, if you want to use further filter within it, below one liner can help you.

C:\Users\cyberkeeda>netsh interface show interface | for /f "tokens=2" %a in ('findstr Wi-Fi') do @echo %a
Connected




Read more ...

How to add Hosts and Host groups into Ansible Server



Ansible Initial Host Configuration.

Ansible knows the hosts and hostgroups from a host file by default it is located as /etc/ansible/hosts.

Read more ...

How to Install Ansible on CentOS 7



Need Automation on Linux : Ansible will become your best friend for sure.

Ansible is the simplest way to automate apps and IT infrastructure. Application Deployment + Configuration Management + Continuous Delivery.

So let's not discuss more jump into installation to have hands on it.


Redhat/Centos ships ANSIBLE on its default repository, so you don’t ned to woory about packages or it’s dependencies.

Just a single command will install ansible and your Automation cockpit is ready to fly.

cybeerkeeda@Linux-Maniac:~ yum install ansible

If you too found the same issue while installing ansible from one liner yum command.
cybeerkeeda@Linux-Maniac:~ yum install ansible 
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * base: mirror.nbrc.ac.in
 * extras: mirror.nbrc.ac.in
 * updates: mirror.nbrc.ac.in
No package ansible available.
Error: Nothing to do

Make sure first of all you are connected to internet, then simply install the epel repo first.

cybeerkeeda@Linux-Maniac:~ yum install epel-release
Then run the same earlier command  yum install ansible.
cybeerkeeda@Linux-Maniac:~ yum install ansible
Done ! All fine 

Now lets confirm it’s installation status by checking the installed ansible version.
cybeerkeeda@Linux-Maniac:~ ansible --version

 ansible 2.3.1.0
  config file = /etc/ansible/ansible.cfg
  configured module search path = Default w/o overrides
  python version = 2.7.5 (default, Nov  6 2016, 00:28:07) [GCC 4.8.5 20150623 (Red Hat 4.8.5-11)]

Do find the video for reference purpose too.



Read more ...

Download all Puppet Packages , puppet packages



Puppet Package Repository links.

Download any packages relevant with puppet directly through puppet repository.

http://yum.puppetlabs.com/el/

Add direct repo for REDHAT/ CentOS 7 , if you are connected to internet.

http://dl.fedoraproject.org/pub/epel/beta/7/x86_64/epel-release-7-0.1.noarch.rpm





Read more ...
Designed By Jackuna