Triggering a Jenkins job using API call and passing parameters

Jenkins is one of the important tool in DevOps and most of the time we would require to execute Jenkins job using remote REST API call. Jobs can either be parameterized or non parameterized. A Parameterized job will need certain input from user side for execution. Here we will discuss how to call both types of jobs using REST API.

We will discuss on following steps. Read more

  1. Setting Jenkins Job respond to REST API
  2. Finding out the API URL for the Job
  3. Handling Authentication
  4. Building REST API request
  5. How to trigger a non-parametrized Job.
  6. Triggering paremeterized job by sending values in URL
  7. Triggering parametrized Job by sending values in JSON file

Introduction to Jenkins API

[From Jenkins Documentation] “Jenkins is the market leading continuous integration system, originally created by Kohsuke Kawaguchi. This API makes Jenkins even easier to use by providing an easy to use conventional python interface.”

——————- advertisements ——————-  

———————————————————

Jenkins provides rich set of REST based APIs. 

Setting Jenkins Job to respond REST API

The REST API feature can be enabled per Job basis. To enable REST API trigger for a Job, Navigate to Your JobName ->Configure -> Build triggers TAB and Check on ‘Trigger build remotely’.

Find out the API URL for the Job

Once you enabled the check box to trigger build remotely , Jenkins will show you the URL to access the particular Job and gives an option to provide the API token for the build. Consider my Jenkins server URL is 10.10.10.100:8080 and my job name is ‘test-job’ , then the URL will be as follows

‘ http://10.10.10.100:8080/job/test-job/build?token=MyTestAPIToken’ -> For non parameterized build

‘ http://10.10.10.100:8080/job/test-job/buildWithParameters?token=MyTestAPIToken’ -> For parameterized build

——————- advertisements ——————-  

———————————————————

Handling Authentication

Jenkins using combination of user credential based authentication and API token authentication. We can build token for each build as shown above. In user credential authentication, you can either pass the usename+password or username+token . To access the token for your username, login with your user account , navigate to Manage Jenkins -> Manage Users ->Select User name -> Click Add New Token ->Give Token Name -> Click generate . This will display token for your user . Copy this token and save on safe place as this token can not be recovered in future.

Building REST API request

There are two steps involved in making a successful API request. The first step is to send authentication request and get the CRUMB variable. This crumb data required to be send as header on further API requests. Jenkins use this to prevent Cross Site Forgery. The second one include the actual job request where you will specify job name and parameters for the job. Following are the example for getting CRUMB data using CURL query

——————- advertisements ——————-  

———————————————————

Getting CRUMB data :

Format : crumb=$(curl -vvv -u “username:passsword” -s ‘http://jenkinsurl/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,”:”,//crumb)’)

Example using password :

crumb=$(curl -vvv -u “apiuser:[email protected]″ -s ‘http:// 10.10.10.100 :8080/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,”:”,//crumb)’)

Example using User Token :

crumb=$(curl -vvv -u “apiuser: 1104fbd9d00f4e9e0240365c20a358c2b7 ” -s ‘http:// 10.10.10.100 :8080/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,”:”,//crumb)’)

Triggering a Non-parameterized Job :

Triggering a non-parameterized job will be easy as there is no requirement of sending any additional data for the build. Below are the example for the API request. Assume we have got crumb data from the above step.

curl -H $crumb –user apiuser: 1104fbd9d00f4e9e0240365c20a358c2b7 -X POST http://10.10.10.100:8080/job/test-job/build?token=MyTestAPIToken

Where ‘test-job’ is name of my Job and ‘ MyTestAPIToken ‘ is the token keyword which i have set manually on Job configure page. Refer ‘Find out the API URL for the Job’ section above to understand for setting up token keyword.

——————- advertisements ——————-  

———————————————————

How to create Parameterized Job:

Consider a Jenkins Job where i am asking user inputs before executing Job, these type of jobs are called parameterized job. We can enable parameter request by checking ‘This Job Parameterized’ option under the general tab. Here i am enabling paramerized option for the job name ‘test-job’ and adding two string parameters ‘message1’ and ‘message2’.

Click on Job name -> Configure ->click on General Tab -> enable ‘This project is parameterized’ -> click add parameter and select ‘String Parameter’ from the drop down box. You can see multiple input parameter types which you can use as per your requirement.

On the upcoming window, enter the name as message1 and give the description. Click ‘add parameter’ and repeat the steps for ‘message2’ as well.

——————- advertisements ——————-  

———————————————————

Execute the Job by selecting your job name and clicking ‘Build with parameters’. This will prompt for user input before initiating the build. You can use the data provided by the user inside your build bash script or pipeline steps using ‘$message1’ format

Eg: echo Message 1 to the user $message1

echo Message 2 to the user $message2

 

Triggering Parametrized Job:

You can trigger parametrized job using API call and pass values. You can pass values in a URL encoded format or as part of a JSON file if you have many parameters. 

Passing parameters using URL encoded :

Step 1: Collect the CRUMB data 

——————- advertisements ——————-  

———————————————————

See the above section ‘Building REST API request’

Step 2: Send the parameters in URL

curl -v -H $crumb –user apiuser:apiuser -X POST ‘http://10.10.10.100:8080/job/testjob/buildWithParameters?token=MyTestAPIToken&message1=’hai’&message2=’hello’

Note : Message1 and message2 are the name of the parameter , please see above 

Passing parameters using URL encoded JSON format:

Step 1: Collect the crumb data 

See the above section ‘Building REST API request’

Step 2: Send the parameters in URL encoded Json format 

curl -v –user apiuser:apiuser -X POST http://10.10.10.100:8080/job/testjob/build –data token=MyTestAPIToken –data-urlencode json='{“parameter”:[{“name”:”message1″,”value”:”hai”},{“name”:”message2″,”value”:”hello”}]}’

 

Passing parameters using file:

Step 1: create a JSON file with all the parameters in the following format 

[[email protected] ~]# cat testapi.json
json={
“parameter”:[{“name”:”message1″,”value”:”hai”},{“name”:”message2″,”value”:”hello”}]
}
[[email protected] ~]#

Step 2: Collect the crumb data 

See the above section ‘Building REST API request’

Step 3: Send the api request by specifying file name . 

curl -v –user apiuser:apiuser -X POST http://10.10.10.100:8080/job/testjob/build –data “@testapi.json” -H “Accept: application/json”

 

Hope this helped you. Share your queries/feedback in the comments section below.

LINUX- Active Directory Integration

Most of the organisation uses Active directory domain services for user administration and management.Like windows machines, Linux servers also can authenticate and managed via active directory. In this tutorial, we are describing how to join a Linux server in to an active directory domain.

 Environment Prerequisites

Read more

  • Microsoft Windows Active Directory.
  • Linux host – RHEL
  • Below Packages needed to be installed on Linux host
  • Samba (version 3):
    • samba3x
    • samba3x-client
    • samba3x-winbind
    • samba3x-common
    • And  packages that might be needed to meet dependencies
  • Kerberos:
    • krb5-workstation
    • krb5-libs
    • And packages that might be needed to meet dependencies
  • PAM:
    • pam_krb5
  • NTP:

——————- advertisements ——————-  

———————————————————

   Configuration

This section describes the technical configuration of how to add Linux host as member of a Microsoft Windows Active Directory domain.Technical steps are below.

1. Update  the FQDN in /etc/hosts

It’s highly recommended to update  /etc/hosts with Acive directory FQDN. If something happens to DNS ,system can still resolve out to it.

2. Update the Host name – /etc/sysconfig/network

where “master” is the RHEL host name and “ADserver “is the ADDS (Active directory domain service) Server name.

3. Update the DNS – /etc/resolve.conf

Set the system’s search domain and point to the AD DNS server in /etc/resolv.conf

4. Synchronise the Time – /etc/ntp.conf

Its mandatory to have time synchronization between the domain server and its client. To achieve this, edit the ntp server details in the ntp.conf.

——————- advertisements ——————-  

———————————————————-

5. Update the Samba and krb configuration using authconfig-tui

Check if necessary packages are installed and backup the below configuration file 

/etc/krb5.conf

/etc/samba/smb.conf

Execute the command authconfig-tui. You will get the below text user interface. Fill in the field as below

Once You checked the necessary fields mentioned above, click on Next

——————- advertisements ——————-  

———————————————————-

Update the Kerberos setting as per your environment and click next.

Modify the Samba settings and click Ok.

Verify the configuration

Validate and update the additional information on the Kerberos and samba configuration files

  1. Verify /etc/krb5.conf

2.Update /etc/samba/smb.conf for ID management

Update idmap config range as below as well as backend connection as rid. This is to keep      same UID for the users across the domain. Please insert if these lines are not present

——————- advertisements ——————-  

———————————————————-

3. verify /etc/nsswitch.conf

In order to tell the system to use winbind for authentication, add winbind to passwd and group in /etc/nsswitch.conf as below if it is not already get updated

Join the server to the domain

To join the server in domain, under the specific OU , use the below command

#net ads join createcomputer=Datacenter-FI/Linux_Servers -U <admin id>

Replace the OU names accroding to your environment (Datacenter-Fi/Linux_servers is based on my test environment).You should be having an admin ID created in the AD already to join the computer.

Restart the service

Once joined to the domain , restart the  winbind service

#systemctl restart winbind

——————- advertisements ——————-  

———————————————————-

Restrict Access only to a specific AD group

To restrict access to the server for a specific AD group is possible via editing the file /etc/security/pam_winbind.conf .

 

Edit the line require_membership_of  and add the SIDs of the group which needs access to this server by comma separated.

Enable the Home directory on first login

Enable oddjobd to create home directory automatically in the initial login with default permissions of 700

# authconfig –enablemkhomedir –update

Verify Your Access

We have completed the AD integration in the server. now test your access with your AD id and password.

eg: login [email protected] and password – AD password.

Hope this helps you. Please have your queries and suggestions in the comments section below.

Top 50 CISCO ACI interview questions & answers

Cisco ACI is a part of Software Defined Network (SDN) product portfolio from Cisco . Cisco ACI is an emerging technology on DC build up and disruptive technology for traditional networking .This Question and Answers guide will help you to understand Cisco ACI from basics to advanced level and give confidence to tackling the interviews with positive result . You can download PDF of 50 Q&A from here by contributing small amount of money for our effort.

Read more

1.What is Cisco ACI.?
Cisco ACI, the industry-leading software-defined networking solution, facilitates application agility and data center automation with two important concepts from SDN solution, overlays and centralized control. ACI is a is a well defined architecture with centralised automation and policy-driven application profiles. ACI uses a centralised controller called the Application Policy Infrastructure Controller (APIC),It is the controller that creates application policies for the data center infrastructure.

2. What are the three components of ACI architecture .?
Application Network Profile (ANP)– a collection of end-point groups (EPG), their connections, and the policies that define those connections
Application Policy Infrastructure Controller (APIC)– a centralized software controller that manages downstream switches and act as management plane.
ACI fabric : This is connection of Spine and Leaf switches. In the ACI world Spine and Leaf are the Cisco Nexus 9000 Series Switches (N9k) , and they are act as Control and the Data plane of the ACI. It is running re written version of NX-OS in ACI mode.

3. Describe about ACI Fabric connection terminology.?
• You should use One or more spine switches to be connected to each Leaf, Models supported are Cisco Nexus 9336PQ, 9504, 9508, or 9516 switches
• You should use One or more leaf switches to be connected to End Points and APIC cluster , Models supported are Cisco Nexus 93128TX, 9332PQ, 9372PX, 9372PX-E, 9372TX, 9396PX, or 9396TX etc switches
• Spin switches can be connected to leaf switches but not each other.
• Leaf switches can be connected only to spine switches and endpoint devices including APIC devices , so this means APIC will be connected only to Leaf switches
• ACI Switches are not running spanning tree.
• Minimum 3 APIC controller should require in ACI fabric
• Max APIC can be used are 5
• Max Spine switches can be used are 6
• Max Leaf switches can be used are 200

4. What is the use of Application Policy Infrastructure Controller (APIC) on ACI Fabric.?
This is the network controller is responsible for provisioning policies to physical and virtual devices that belong to an ACI fabric. Minimum a cluster of three controllers is used. Following are the main APIC features.

  • Application and topology monitoring and troubleshooting
  • APIC shows Physical and logical topology (who is connected to whome)
  • Third-party integration (Layer 4 through Layer 7 [L4-L7] services & VMware vCenter/ vShield)
  • Image management (spine and leaf)
  • Cisco ACI inventory and configuration
  • Implementation on a distributed framework across a cluster of appliances
  • Health scores for critical managed objects (tenants, application profiles, switches, etc.)
  • Fault, event, and performance management
  • Cisco Application Virtual Switch (AVS), which can be used as a virtual leaf switch

5. How Cisco ACI differs from other SDN controllers.?
Open SDN architecture separates control plane and data plane . Control plane resides on the central controller and data plane resides on switches. If the switches lost connection to controller, it won’t function for new connections and applying traffic policies. In CIsco ACI architecture , the APIC is not control plane, rather switches still hold control plane and data plane and can function properly if the controller down.

6. What are the different object model implementation in ACI.?
Within the ACI object model, there are essentially three stages of implementation of the model, the Logical Model, the Resolved Model, and the Concrete Model.
Logical Model: The logical model is the interface for the system. Administrators are interacting with the logical model through the API, CLI, or GUI. This is a Policy layer which include endpoint configuration on the controller .Changes to the logical model are then pushed down to the concrete model, which becomes the hardware and software configuration.
Resolved Model : The Resolved Model is the abstract model expression that the APIC resolves from the logical model. This is essentially the elemental configuration components that would be delivered to the physical infrastructure when the policy must be executed (such as when an endpoint connects to a leaf)
Concrete Model : The Concrete Model is the actual in-state configuration delivered to each individual fabric member based on the resolved model and the Endpoints attached to the fabric.This is include actual configuration of device and resides on fabric (spines and leafes )

7.What is Policy layer and Concrete Layer in ACI model.?
Concrete layer is the ACI fabric and policy layer is controllers

8.What you mean by Tenant .?
Basically a Tenant (fvTenant) is logical container for application policies to isolate switching and routing function. A tenant represents a unit of isolation from a policy perspective, but it does not represent a private network. Tenants can represent a customer in a service provider setting, an organisation or domain in an enterprise setting, or just a convenient grouping of policies.
Four types of Tenant available

  1. User
  2. Common
  3. Management
  4. Infra

9 . Difference between management tenant and infrastructure tenant.?
Management Tenant : Used for infrastructure discovery and also used for all communication/integration with virtual machine controllers. It has separate Out Of Band (OOB) address space for APIC to Fabric communication, it is using to connect all fabric management interfaces
Infrastructure Tenant : It governs operation of fabric resources like allocating VXLAN overlays and allows fabric administrator to deploy selective shared services to tenants

10.What you mean by Context/VRF on ACI .?
The top level network construct within an ACI tenant is the VRF or Context . It is called as tenant network and available as ‘private network’ in the ACI GUI .Following are the important point about VRF’s
• A VRF defines Layer 3 address domain
• One or more bridge domain can associated with VRF
• All of the endpoints within the Layer 3 domain (VRF) must have unique IP addresses because it is possible to forward packets directly between these devices if the policy allows it.
• A tenant can contain multiple VRFs How ARP handled by ACI.?

Below are some of the additional questions available on PDF

  • How ARP and broadcast handled by ACI.?
  • Why and when you require contract in ACI Fabric.?
  • How to perform unicast routing on ACI.?
  • In Fabric, which switch will act as default gateway for pertucler subnet.?
  • How Cisco ACI differentiate Layer 2 traffic and Layer 3 traffic.?
  • How VLAN working in Cisco ACI.?
  • How can you configure trunk and access port on ACI.?
  • What is micro segmentation and how to configure.?
  • How to configure inter-VRF and Inter-tenant communication.?
  • How can you integrate Cisco ACI with VmWare.?
  • Explain about ACI fabric discovery process .?
  • Explain about traffic flow lookup on ACI fabric.?

Interested to know about the detailed answers of above questions along with other exclusive commonly asked 30 interview questions.? You can download PDF copy of 50 interview Q&A from here by contributing small perks to support our efforts. Please send email to ‘[email protected]‘ for PayPal payment option.


Hope you have enjoyed reading. Kindly share your feedback/suggestions in the comments section. For Q&A posts on other topics, please click here.

 

Ref:
https://www.sdxcentral.com/data-center/definitions/what-is-cisco-aci/

https://www.cisco.com/c/en_in/solutions/data-center-virtualization/application-centric-infrastructure/index.html

 

Introducing Beginner’s Forum TV

Introducing our YouTube channel – Beginner’s Forum TV. A new platform from the team as promised, to share more of our contents from the technology world. 

We have been posting contents here in the blog in different categories around the Data Center including Networking, Servers, Storage, Cloud and a bit of programming stuff. Our channel will have contents from all these areas but will not be limited to these. We will be adding more tech stuff – on electronics and gadgets, Application and Web development and anything technical of your interest.

Read more

Subscribe (by clicking the above button) to Beginner’s Forum TV so that you will not be missing any updates on our latest contents. 

 
Thank You for all your support and keep doing the same. Follow/Subscribe us, share our contents and keep sharing feedback (comments) as you always did. 

HAPPY nEW YEAR

We wish all our readers, a very happy New Year 2019..!!

We had a wonderful year 2018, a year we achieved many milestones and were able to do some amazing stuff on and off our page here.

Now we are into this New Year and we hope to cover even further this year. We assure you excellent and innovative content and we have ‘things’ planned for this New Year. 🙂

Once again we wish all our readers a Happy New Year, 2019..!

Keep reading..!

Vembu BDR Suite v4.0 is now GA

Vembu’s BDR Suite v4.0 is now GA.

Vembu announced the latest version – 4.0 – recently and is now Generally Available for customers. Vembu BDR 4.0 is only available now for fresh installations. An upgrade package will soon be available for existing customers to upgrade their environment to 4.0.

There are a lot of exciting new features available with 4.0 including backup of VM’s running on Hyper-V cluster etc… You can click here to read more about the new features in Vembu BDR 4.0.  Read more

You can download the installer here for your environment today.

Also, Vembu is giving away up to 40% discount on their products till the 24th of December. Hurry and enjoy the Thanksgiving-Christmas discount from Vembu and grab your your piece of software. Please refer to the Vembu blog here for more details.

IT Blog Awards by Cisco – Vote now..!

Hurry, vote now for the best IT Blogs in the IT Blogs awards hosted by Cisco..!

About the program:

This is the first ever IT Blogs awards from Cisco for recognizing the contribution by the blogger community, in various categories.

(about the program) from the Cisco website :

The first-ever IT Blog Awards, hosted by Cisco, is our way of recognizing the great community of independent tech bloggers for the passion, creativity, and expertise shared throughout the year. We appreciate your impact on the tech community.
Voting is now open through January 4, 2019.  Winners will receive a Cisco Live US pass.

You can vote for the blogs in different categories and the voting ends on 4th Jan, 2019. Make sure to consider the value, credibility and the consistency of the content while you select a blog as the best in that category.

It is your opportunity now to recognize the bloggers/blogs who are helping the community by providing excellent contents. Do not wait, Vote Now.

We are proud to announce that, we have been chosen as one of the finalists in the Best Group Effort Category. If you feel our contents were of quality, helping the community and at the same time meeting the program guidelines, you can select our blog in best group effort category.

Azure cloud provisioning using Ansible

                Automating the IT Infrastructure is today’s one of major focus of all organizations. This reduces the cost and human workloads. When you make a plan to automating your infrastructure, it should start with provisioning of the resources, this makes managing the resources very easy. Many businesses have adopted cloud computing in their operations in the past years because of its flexibility and high sociability features. When you integrate the cloud infrastructure with today’s open source DevOps tools available in the market, this makes your daily life easier to handling huge environments.

I would rather suggest to go with Ansible as the configuration management tool because of its simplicity and straight forward operation features. This came in market late, but gained solid footing and adopted by many DevOps professionals because of its unique features. Ansible offers huge number of modules for managing the cloud operations for all major cloud providers like Azure AWS and GCP.

The Ansible playbooks which I refer below will help you to provisioning cloud resources in Azure environment, which create a Window VM and configure the VM to connect with Ansible host for any post provision activities, The playbook will perform the following tasks.

Read more

  1. Create the resource groups and Network infrastructure
  2. Provisioning of windows VMs
  3. Adding the new host to dynamic inventory for any post provision activities
  4. Enabling the PowerShell execution policy to connect to WinRM
  5. Installing a Firefox package using ansible on the newly created VM
The playbook contains 3 roles which will create Network infrastructure, provision a windows VMs and install the Firefox package on it.
——————- advertisements ——————-
———————————————————-
Let’s go through the main playbook first which includes 3 roles First 2 will run against the localhost which creates the Network infrastructure and Virtual machine respectively. As you can see the third role which install the Firefox package is running against a host group azure_vms which will be created dynamically after provisioning the server

Now let’s go through the first role common which creates the resource group and network infrastructure.

 

- name: Create a resource group
   azure_rm_resourcegroup:      
     name: "{{ rg_name }}"      
     location: "{{ location }}"      
     state: present 

- name: Create a virtual network   
  azure_rm_virtualnetwork:      
    name: "{{ vitual_network }}"      
    resource_group: "{{ rg_name }}"      
    address_prefixes_cidr:         
      - "{{ CIDR }}" 
- name: Create network windows base_security groups   
  azure_rm_securitygroup:     
    resource_group: "{{ rg_name }}"     
    name: windows_base     
    purge_rules: yes     
    rules:        
     - name: 'AllowRDP'          
       protocol: Tcp          
       source_address_prefix: 0.0.0.0/0          
       destination_port_range: 3389          
       access: Allow          
       priority: 100          
       direction: Inbound        
     - name: 'AllowWinRM'          
       protocol: Tcp          
       source_address_prefix: 0.0.0.0/0          
       destination_port_range: 5986          
       priority: 102          
       direction: Inbound        
     - name: 'DenyAll'          
       protocol: Tcp          
       source_address_prefix: 0.0.0.0/0          
       destination_port_range: 0-65535          
       priority: 103          
       direction: Inbound

- name: Create a Subnet and adding the windows_base security group in to it
  azure_rm_subnet:
    name: "{{ subnet }}"
    virtual_network_name: "{{ vitual_network }}"
    resource_group: "{{ rg_name }}"
    address_prefix_cidr: "{{ subnet_CIDR }}"
    security_group_name: windows_base 

——————- advertisements ——————-
———————————————————-

Here it’s creating a Resource group, virtual network and a security group which allow incoming RDP and WinRM traffics. You can either add the security group to the NIC card or to the subnet where we create the Virtual machine. Azure will create a NIC card and allocate to the VM in default if you are not giving any custom NIC cards while provisioning. Here I am not creating any custom NIC cards for the server instead attaching the security group with the subnet.

Let’s go through the second role which creates the Virtual machine.


- name: Create a VM    
  azure_rm_virtualmachine:      
    os_type: Windows      
    resource_group: "{{ rg_name }}"      
    virtual_network_name: "{{ virtual_network_name }}"      
    name: "{{ vm_name }}"      
    admin_username: "{{ admin_user }}"      
    admin_password: "{{ admin_passwd }}"      
    vm_size: Standard_F2s_v2      
    image:         
      offer: WindowsServer         
      publisher: MicrosoftWindowsServer         
      sku: '2016-Datacenter'         
      version: latest    
  register: output  

- name: Add new instance to the host group    
  add_host:       
    hostname: "{{ vm_name }}"       
    ansible_host: "{{ azure_vm.properties.networkProfile.networkInterfaces[0].properties.ipConfigurations[0]. properties.publicIPAddress.properties.ipAddress }}"       
    ansible_user: "{{ admin_user }}"       
    ansible_password: "{{ admin_passwd }}"       
    ansible_connection: winrm       
    ansible_port: 5986       
    ansible_winrm_server_cert_validation: ignore       
    ansible_winrm_transport: ssl 
    groupname: azure_vms    
  with_items: output.instances   

- name: create Azure vm extension to enable HTTPS WinRM listener     
  azure_rm_virtualmachine_extension:        
    name: winrm-extension        
    resource_group: "{{ rg_name }}"        
    virtual_machine_name: "{{ vm_name }}"        
    publisher: Microsoft.Compute        
    virtual_machine_extension_type: CustomScriptExtension        
    type_handler_version: 1.9        
    settings: '{"commandToExecute": "powershell.exe -ExecutionPolicy ByPass -   EncodedCommand {{winrm_enable_script}}"}'        
    auto_upgrade_minor_version: true     
  with_items: output.instances   

- name: wait for the WinRM port to come online     
  wait_for:        
    port: 5986        
    host: '{{azure_vm.properties.networkProfile.networkInterfaces[0].properties.ipConfigurations[ 0].properties.publicIPAddress.properties.ipAddress}}'        
    timeout: 600     
  with_items: output.instances
——————- advertisements ——————-
———————————————————-
As you can see in the second task in the role, the newly created server will be added to a host group azure_vms using the ansible add_host module. The third and 4 th task will enable HTTPS WinRM listener for ansible communication.

The third and final role in the playbook will install a Firefox browser in the newly provisioned VM using the ansible win_chocolatey module.

 - name: Install Firefox 
   win_chocolatey:
     name: firefox
     state: present

Here is the main playbook which calls all the 3 roles

---
- hosts: localhost
  gather_facts: yes
  roles:
   - common
   - vm

- hosts: azure_vms
  gather_facts: no
  roles:
   - install_firefox

Hope this post helped you. Please share your feedback/suggestions in the comments below.

Update service-now ticket using a Python script

How cool it will be if you can upload the output of your script in to Service now incident notes or task notes automatically. This python script helps you to run set of command against the Cisco switches and routers and the output of command will upload to service now incident automatically. This will help you to increase the response time of NOC L1  team in troubleshooting task.

Service-now a IT Service management (ITSM) tool based on cloud platform provides end to end transformation of IT services. Service Now provides REST API to communicate with SNOW instance. We will use REST API in our program to interact with service now instance.

We are explaining step by step procedure to achieve this

Following are the components required: Read more

  1. Service now developer account
    2. Service now instance
    3. Python with Service now API installed

——————- advertisements ——————-

———————————————————-

Create service now developer account and instance

Please refer our post ‘Create service now developer account and instance’ and create new user for API calls.

Setup environment

We would  require ‘netmiko’ package to take ssh of devices. Please read part 1 and part 2  of our post for details about installing python and running your first program. Please read part 4 if you want to know how to take SSH of a switch.

Install python service-now API package

We also require ‘pysnow’ package which is using to interact with service now using REST API call. Please click here if you would like to know more about ‘pysnow’ package.

Install ‘psysnow’ using following command

‘pip install psynow’

please click here if you did not know how to install a package on python using pip

Script Definition:

The script will get service-now information and device credential initially. Then it will continuously run on server so user can update multiple incident by running the commands against multiple devices. All the required commands have to be saved on ‘command.txt’ file.

——————- advertisements ——————-

———————————————————-

It is using class ‘inc_update’ to gather information and update service-now.  Inside the class, the function ‘collectdata’ using to SSH to device and taking the out put of commands.  The function ‘inc_update’ using to update service now instance with the output.

Following are the script. It is easy to understand, and we have put inline comments for making it easy.

import pysnow
import getpass
from netmiko import ConnectHandler

print “=============================\n”
print “Program to update service now incident notes\n”
print “\n=============================\n”

##class to connect device
class cls_incident:
#initialising variables
def __init__(self,uname,password):
#initialising variables
self.uname = uname
self.password = password
self.secret=password
self.dev_type=’cisco_ios’
self.ip=”
self.output=”

——————- advertisements ——————-

———————————————————-

#creating dictionery for netmiko
self.dict_device = {
‘device_type’: self.dev_type,
‘ip’: self.ip,
‘username’: self.uname,
‘password’: self.password,
‘secret’: self.secret,
‘global_delay_factor’:1,

}

#function to login to device and collect output of command
def collectdata(self,ipaddress):
self.dict_device[‘ip’]=ipaddress
self.net_connect = ConnectHandler(**self.dict_device)
#opening command file
cmd_file=open(‘command.txt’)
self.output=”
#loop for reading command one by one
for line in cmd_file:
cmd=line.lstrip()
self.output+=”\nOutput of command “+cmd+” \n”
self.output+=self.net_connect.send_command(cmd)
cmd_file.close()

——————- advertisements ——————-

———————————————————-

print self.output
print “\nCommand Output collected”

#function to update service now
def inc_update(self,inc_number,s_uname,s_password,s_instance):
#connecting with service now
snow = pysnow.Client(instance=s_instance, user=s_uname, password=s_password)
incident = snow.resource(api_path=’/table/incident’)
#payload=self.output
update = {‘work_notes’:self.output, ‘state’: 5}
#updating incident record
updated_record = incident.update(query={‘number’:inc_number}, payload=update)
print “Incident note updated ”

def main():

#Collecting service now details
instance=raw_input(“Enter service now instant name in format of ‘company.service-now.com’ :”)

——————- advertisements ——————-

———————————————————-

instance=instance.rstrip(‘.service-now.com’)
s_uname=raw_input(“Enter service now user name:”)
s_password=getpass.getpass(“Password:”)

##Collecting device credential
dev_uname=raw_input(“\nEnter Device user name :”)
dev_passwd=getpass.getpass(“Password:”)

objDev=cls_incident(dev_uname,dev_passwd)

while True:
try:
inc_number=raw_input(“Enter incident number :”)
ip_address=raw_input(“Enter IP address of device:”)
print “Connecting device and collecting data ”
#creating class object
objDev.collectdata(ip_address)

print (“Updating service now”)
#updaing service nw
objDev.inc_update(inc_number,s_uname,s_password,instance)
print “\nThis program will keep on running, press ctrl C to exit”
print “Enter details for next incident \n”
except Exception,e:
print “Error on execution :”,e
if __name__== “__main__”:
main()

——————- advertisements ——————-

———————————————————-

How to run :

Download the ‘command.txt‘ and ‘incident-update.txt‘ in to same folder of your system. rename ‘incident-update.txt’ in to ‘incident-update.py’. Open the file ‘command.txt’ and add your required commands which need to be run on networking device.. Run the program from command prompt using ‘ python incident-update.py’ . Please provide your input and test . Please ensure you have the reach-ability to service-now instance and network devices from your machine.

Program screen shot

——————- advertisements ——————-

———————————————————-

Service-now screen shot

You could see service now incident notes updated with command output automatically

Hope this will ease your life a bit.. 🙂

Please comment below if you would require customized script based on your requirement which will support multiple device model like Cisco ASA, Juniper, Palo Alto, Checkpoint etc.

1 2 3 5