[Solved] ConfigItem Update

Moderator: crythias

Post Reply
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

[Solved] ConfigItem Update

Post by VCSousa »

Hi everyone,

Hope to find you well on this days.

I want to update a configitem deplyoment state. This configitem are related with a process. There is some way to update deployment state?

By command line with a script? WebService? Generic Agent? Addon?

Can some one give me some lights about it?
Last edited by VCSousa on 12 Feb 2021, 17:23, edited 1 time in total.
alexus
Znuny wizard
Posts: 380
Joined: 20 Sep 2010, 16:54
Znuny Version: OTRS 6 CE
Real Name: Alexey Yusov
Company: Radiant System Group s.r.o
Location: Prague
Contact:

Re: ConfigItem Update

Post by alexus »

Hi,

There is a build-in web-service
818f727d75.png
You do not have the required permissions to view the files attached to this post.
Alexey Yusov

Production: OTRS CE ITSM 6.0.28 on CentOS 7 + Apache 2.4 + MariaDB 10.4.13 + Radiant Customer Portal

Radiant System OTRS Intergrator
RS4OTRS marketplace
Stay tuned on our Facebook
((OTRS)) Community Edition - what next?
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

Hi Alexus,

I know, but i don't understand how can I use the web service. At really, i dont understand nothing about WebServices and API's.

Can you give me a litle guide how can I do it?
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

I already got me to this:

Image

How can I go further this (What should I add on URL) and how can I trigger it from a process.
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

Hi everyone,

Hopes of a good weekend for all of you.

I made some advances on this. And I already could get some answers from otrs via Curl with Rest WebService. I can acomplish a good answer with ConfigItemGet with response of all data about the configitem. Now, I wanted to updated it and there i'm strugling.

My Curl script:
curl -X PATCH -H "Content-Type: application/json" --data '
{"ConfigItem": {
"ConfigItemID":"16",
"InciState":"operational",
"DeplState":"001. Produção",
"CurDeplState":"002. Futuro",
"Class":"Portátil",
"Name":"PTL011"
}}' http://10.35.3.19/otrs/nph-genericinter ... s10extreme -w "\n"


I alreadry tryed with POST instead of PATCH and the result are the same. And follow the feedbacks:

Image

Image

Can someone help me?
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

The log on system log are:

[Mon Jan 25 12:01:50.602808 2021] [:error] [pid 31053] Can't use string ("") as a HASH ref while "strict refs" in use at /opt/otrs//Kernel/GenericInterface/Operation/ConfigItem/Common.pm line 745.\n
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

Bump
root
Administrator
Posts: 3963
Joined: 18 Dec 2007, 12:23
Znuny Version: Znuny and Znuny LTS
Real Name: Roy Kaldung
Company: Znuny
Contact:

Re: ConfigItem Update

Post by root »

Hi,

I suggest there is more in thee error_log. Especially Deployment State und Incident State looks suspicious to me.

- Roy
Znuny and Znuny LTS running on CentOS / RHEL / Debian / SLES / MySQL / PostgreSQL / Oracle / OpenLDAP / Active Directory / SSO

Use a test system - always.

Do you need professional services? Check out https://www.znuny.com/

Do you want to contribute or want to know where it goes ?
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

Hi Roy,

Thanks in advance. The only error, related to this, on /etc/httpd/logs/error_log are that lines.

The IncState and DeplState are right, i don't know if the problem comes on Deployment State with the dot and space, but inside quotes, it wasnt to happen.
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

One example, if i change the script on Deployment state to "002. Produção", it gives me erro because that DeplState doesn't exist, and its true. So it recognize the existence of that DplState (001. Produção).
root
Administrator
Posts: 3963
Joined: 18 Dec 2007, 12:23
Znuny Version: Znuny and Znuny LTS
Real Name: Roy Kaldung
Company: Znuny
Contact:

Re: ConfigItem Update

Post by root »

Hi,

Your data structure looks wrong for me. See the example in the code: https://github.com/znuny/ITSMConfigurat ... te.pm#L120

Your payload should look like this:

Code: Select all

{
  "UserLogin": "xx",
  "Password": "yy",
  "ReplaceExistingData": 0,
  "ConfigItemID": 16,
  "ConfigItem": {
      "InciState":"operational",
      "DeplState":"001. Produção",
      "CurDeplState":"002. Futuro",
      "Class":"Portátil",
      "Name":"PTL011"
    }
}
- Roy
Znuny and Znuny LTS running on CentOS / RHEL / Debian / SLES / MySQL / PostgreSQL / Oracle / OpenLDAP / Active Directory / SSO

Use a test system - always.

Do you need professional services? Check out https://www.znuny.com/

Do you want to contribute or want to know where it goes ?
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

Hi Roy,

So, i think I got some info about this errors.

The error no error.log about "" HASH, after some tests with your configuration, i realize that the error is about other fields of Config Item that are empty but not used on the case to update. That config item is about a laptop and some fields like buy date, waranty, are blank.

So i picked another class of ConfigItem where I have not fields except DeplState, InciState and Name, where doesnt exist blank fields, and here, the error on error.log is another:

[Tue Jan 26 08:21:59.855351 2021] [:error] [pid 17299] Can't use an undefined value as a HASH reference at /opt/otrs//Kernel/GenericInterface/Operation/ConfigItem/ConfigItemUpdate.pm line 335.\n
root
Administrator
Posts: 3963
Joined: 18 Dec 2007, 12:23
Znuny Version: Znuny and Znuny LTS
Real Name: Roy Kaldung
Company: Znuny
Contact:

Re: ConfigItem Update

Post by root »

Hi,

Did you added ReplaceExistingData => 0 as a parameter?

- Roy
Znuny and Znuny LTS running on CentOS / RHEL / Debian / SLES / MySQL / PostgreSQL / Oracle / OpenLDAP / Active Directory / SSO

Use a test system - always.

Do you need professional services? Check out https://www.znuny.com/

Do you want to contribute or want to know where it goes ?
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

Hi Roy,

Yes, I already tried with 0 and 1 on that.

Image
root
Administrator
Posts: 3963
Joined: 18 Dec 2007, 12:23
Znuny Version: Znuny and Znuny LTS
Real Name: Roy Kaldung
Company: Znuny
Contact:

Re: ConfigItem Update

Post by root »

Hi Ruben,

I'll check this on a test system. But not today, I'm too busy preparing the release 6.0.31.

- Roy
Znuny and Znuny LTS running on CentOS / RHEL / Debian / SLES / MySQL / PostgreSQL / Oracle / OpenLDAP / Active Directory / SSO

Use a test system - always.

Do you need professional services? Check out https://www.znuny.com/

Do you want to contribute or want to know where it goes ?
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

Many thanks Roy, i'll wait ;)

Don't worry about the time ;)
skullz
Znuny superhero
Posts: 623
Joined: 24 Feb 2012, 03:58
Znuny Version: LTS and Features
Real Name: Mo Azfar
Location: Kuala Lumpur, MY
Contact:

Re: ConfigItem Update

Post by skullz »

I wrote some test script back in the days in perl script..

Code: Select all

#!/usr/bin/perl -w
# --
### OTRS 5S/OTRS 6
###
### **OTRS Generic Interface Webservice REST must be created first!!!!!!
###
### 1. Get some info from otrs via webservice rest ticket connector
###
use strict;
use warnings;

## nofilter(TidyAll::Plugin::OTRS::Perl::Dumper)

## use ../ as lib location
use File::Basename;
use FindBin qw($RealBin);
use lib dirname($RealBin);

use JSON;
use REST::Client;

## ---
## Variables to be defined

## This is the HOST for the web service the format is:
## <HTTP_TYPE>:://<OTRS_FQDN>/nph-genericinterface.pl
my $Host = 'http://app.myserver.local:83/otrs/nph-genericinterface.pl';

my $RestClient = REST::Client->new(
    {
        host => $Host,
    }
);

my $User="admin";
my $Pass="123"; 
my $ConfigItemID = "20";

####################################START REST CI UPDATE#####################################
# Method: PATCH
# Endpoint: /ConfigItem/$CIID
# OTRS Route Mapping: /ConfigItem/:ConfigItemID

my $ControllerAndRequest2 = "/Webservice/GenericTicketConnectorREST/ConfigItem/$ConfigItemID";

## ticket parameter need to be pass for create a ticket
my $Params2 = {
    UserLogin => $User,       # to be filled with valid agent login
    Password  => $Pass,    # to be filled with valid agent password
    ConfigItem    => 
    {
        Class	=> "Computer",
		Name	=> 'C3',
		DeplState => 'Planned',
		InciState => 'Operational',
        ##PLEASE REFER REST CI SEARCH RESULT FOR AVAILABLE PARAM FOR EACH CLASS
		# it depends on the Configuration Item class and definition
		CIXMLData	=> 
        {
            #SerialNumber     => "12345",
            Vendor            => "HP XXXXXX",   #update this field
			NIC => [
                            {
                              'NIC' => 'wdXXXX',  #update this field
                              'IPoverDHCP' => 'Yes'   #update this field
                            }
                        ],
        }
    },
};

my @RequestParam2;

# # ----
# # For POST method
my $JSONParams2 = encode_json $Params2;
#print Dumper($JSONParams);

# # The @RequestParam array on position 0 holds controller and request
# # on position 1 it holds the JSON data string that gets posted
@RequestParam2 = (
   $ControllerAndRequest2,
   $JSONParams2
 );

$RestClient->PATCH(@RequestParam2);

## If the host isn't reachable, wrong configured or couldn't serve the requested page:
my $ResponseCode2 = $RestClient->responseCode();
if ( $ResponseCode2 ne '200' ) {
    print "Request failed, response code was: $ResponseCode2\n";
    exit;
}

# If the request was answered correctly, we receive a JSON string here.
my $ResponseContent2 = $RestClient->responseContent();

my $Data2 = decode_json $ResponseContent2;

## Just to print out the returned Data structure:
print "Update Response was:\n";
print Dumper($Data2);

#########################################END REST CI GET##################################
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

Hi Skullz,

Thanks for trying help.

I'm trying your script and giving this error:

[root@PT01NS19 ~]# ./rest2
Can't locate REST/Client.pm in @INC (@INC contains: / /root/perl5/lib/perl5/5.16.3/x86_64-linux-thread-multi /root/perl5/lib/perl5/5.16.3 /root/perl5/lib/perl5/x86_64-linux-thread-multi /root/perl5/lib/perl5 /usr/local/lib64/perl5 /usr/local/share/perl5 /usr/lib64/perl5/vendor_perl /usr/share/perl5/vendor_perl /usr/lib64/perl5 /usr/share/perl5 .) at ./rest2 line 20.
BEGIN failed--compilation aborted at ./rest2 line 20.
skullz
Znuny superhero
Posts: 623
Joined: 24 Feb 2012, 03:58
Znuny Version: LTS and Features
Real Name: Mo Azfar
Location: Kuala Lumpur, MY
Contact:

Re: ConfigItem Update

Post by skullz »

this is perl script (.pl)

an additional cpan module is require

- JSON;
- REST::Client;
- Data::Dumper

REF: https://doc.otrs.com/doc/manual/admin/6 ... .12.10.7.4
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

Skullz,

I'm getting now an error 500.

[root@PT01NS19 ~]# ./rest2
Request failed, response code was: 500

Image

Image
reneeb
Znuny guru
Posts: 5018
Joined: 13 Mar 2011, 09:54
Znuny Version: 6.0.x
Real Name: Renée Bäcker
Company: Perl-Services.de
Contact:

Re: ConfigItem Update

Post by reneeb »

The Apache error log on the OTRS server should give you more details about the error.
Perl / Znuny development: http://perl-services.de
Free Znuny add ons from the community: http://opar.perl-services.de
Commercial add ons: http://feature-addons.de
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

Code: Select all

ERROR: GenericInterfaceProvider-78 Perl: 5.16.3 OS: linux Time: Tue Jan 26 13:10:31 2021

 Message: DebugLog error:  Summary: Could not read input data  Data   : No data provided.

 RemoteAddress: 10.35.3.19
 RequestURI: /otrs/nph-genericinterface.pl/Webservice/CMDBConnector/ConfigItemUpdate/16

 Traceback (20538):
   Module: Kernel::GenericInterface::Debugger::DebugLog Line: 224
   Module: Kernel::GenericInterface::Debugger::Error Line: 318
   Module: Kernel::GenericInterface::Transport::HTTP::REST::_Error Line: 1000
   Module: Kernel::GenericInterface::Transport::HTTP::REST::ProviderProcessRequest Line: 254
   Module: Kernel::GenericInterface::Transport::ProviderProcessRequest Line: 102
   Module: Kernel::GenericInterface::Provider::Run Line: 169
   Module: ModPerl::ROOT::ModPerl::Registry::opt_otrs_bin_cgi_2dbin_nph_2dgenericinterface_2epl::handler Line: 38
   Module: (eval) (v1.99) Line: 207
   Module: ModPerl::RegistryCooker::run (v1.99) Line: 207
   Module: ModPerl::RegistryCooker::default_handler (v1.99) Line: 173
   Module: ModPerl::Registry::handler (v1.99) Line: 32

ERROR: GenericInterfaceProvider-78 Perl: 5.16.3 OS: linux Time: Tue Jan 26 13:10:31 2021

 Message: DebugLog error:  Summary: Could not read input data  Data   : Could not read input data.

 RemoteAddress: 10.35.3.19
 RequestURI: /otrs/nph-genericinterface.pl/Webservice/CMDBConnector/ConfigItemUpdate/16

 Traceback (20538):
   Module: Kernel::GenericInterface::Debugger::DebugLog Line: 224
   Module: Kernel::GenericInterface::Debugger::Error Line: 318
   Module: Kernel::GenericInterface::ErrorHandling::HandleError Line: 108
   Module: Kernel::GenericInterface::Provider::_HandleError Line: 479
   Module: Kernel::GenericInterface::Provider::Run Line: 175
   Module: ModPerl::ROOT::ModPerl::Registry::opt_otrs_bin_cgi_2dbin_nph_2dgenericinterface_2epl::handler Line: 38
   Module: (eval) (v1.99) Line: 207
   Module: ModPerl::RegistryCooker::run (v1.99) Line: 207
   Module: ModPerl::RegistryCooker::default_handler (v1.99) Line: 173
   Module: ModPerl::Registry::handler (v1.99) Line: 32

ERROR: GenericInterfaceProvider-78 Perl: 5.16.3 OS: linux Time: Tue Jan 26 13:10:31 2021

 Message: DebugLog error:  Summary: Returning provider data to remote system (HTTP Code: 500)  Data   : Could not read input data.

 RemoteAddress: 10.35.3.19
 RequestURI: /otrs/nph-genericinterface.pl/Webservice/CMDBConnector/ConfigItemUpdate/16

 Traceback (20538):
   Module: Kernel::GenericInterface::Debugger::DebugLog Line: 224
   Module: Kernel::GenericInterface::Transport::HTTP::REST::_Output Line: 922
   Module: Kernel::GenericInterface::Transport::HTTP::REST::ProviderGenerateResponse Line: 356
   Module: Kernel::GenericInterface::Transport::ProviderGenerateResponse Line: 152
   Module: Kernel::GenericInterface::Provider::_GenerateErrorResponse Line: 422
   Module: Kernel::GenericInterface::Provider::_HandleError Line: 490
   Module: Kernel::GenericInterface::Provider::Run Line: 175
   Module: ModPerl::ROOT::ModPerl::Registry::opt_otrs_bin_cgi_2dbin_nph_2dgenericinterface_2epl::handler Line: 38
   Module: (eval) (v1.99) Line: 207
   Module: ModPerl::RegistryCooker::run (v1.99) Line: 207
   Module: ModPerl::RegistryCooker::default_handler (v1.99) Line: 173
   Module: ModPerl::Registry::handler (v1.99) Line: 32
Last edited by VCSousa on 27 Jan 2021, 15:01, edited 1 time in total.
root
Administrator
Posts: 3963
Joined: 18 Dec 2007, 12:23
Znuny Version: Znuny and Znuny LTS
Real Name: Roy Kaldung
Company: Znuny
Contact:

Re: ConfigItem Update

Post by root »

Hi,

Please export you webservice if possible and upload it here.

- Roy
Znuny and Znuny LTS running on CentOS / RHEL / Debian / SLES / MySQL / PostgreSQL / Oracle / OpenLDAP / Active Directory / SSO

Use a test system - always.

Do you need professional services? Check out https://www.znuny.com/

Do you want to contribute or want to know where it goes ?
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

Code: Select all

---
Debugger:
  DebugThreshold: debug
  TestMode: '0'
Description: ''
FrameworkVersion: 6.0.17
Provider:
  Operation:
    ConfigItemCreate:
      Description: ''
      MappingInbound: {}
      MappingOutbound: {}
      Type: ConfigItem::ConfigItemCreate
    ConfigItemDelete:
      Description: ''
      MappingInbound: {}
      MappingOutbound: {}
      Type: ConfigItem::ConfigItemDelete
    ConfigItemGet:
      Description: ''
      IncludeTicketData: '0'
      MappingInbound:
        Type: XSLT
      MappingOutbound:
        Type: XSLT
      Type: ConfigItem::ConfigItemGet
    ConfigItemSearch:
      Description: ''
      MappingInbound: {}
      MappingOutbound: {}
      Type: ConfigItem::ConfigItemSearch
    ConfigItemUpdate:
      Description: ''
      IncludeTicketData: '0'
      MappingInbound:
        Config:
          KeyMapDefault:
            MapTo: ''
            MapType: Keep
          ValueMapDefault:
            MapTo: ''
            MapType: Keep
        Type: Simple
      MappingOutbound:
        Type: Simple
      Type: ConfigItem::ConfigItemUpdate
    teste:
      Description: ''
      IncludeTicketData: '1'
      MappingInbound:
        Type: Simple
      MappingOutbound:
        Type: Simple
      Type: Ticket::TicketCreate
    testeteste:
      Description: ''
      IncludeTicketData: '0'
      MappingInbound:
        Type: Simple
      MappingOutbound:
        Type: Simple
      Type: ConfigItem::ConfigItemGet
  Transport:
    Config:
      AdditionalHeaders: ~
      KeepAlive: ''
      MaxLength: '9999999999'
      RouteOperationMapping:
        ConfigItemCreate:
          RequestMethod:
          - CONNECT
          - DELETE
          - GET
          - HEAD
          - OPTIONS
          - PATCH
          - POST
          - PUT
          - TRACE
          Route: /ConfigItemCreate/:ConfigItemID
        ConfigItemDelete:
          RequestMethod:
          - CONNECT
          - DELETE
          - GET
          - HEAD
          - OPTIONS
          - PATCH
          - POST
          - PUT
          - TRACE
          Route: /ConfigItemDelete/:ConfigItemID
        ConfigItemGet:
          RequestMethod:
          - CONNECT
          - DELETE
          - GET
          - HEAD
          - OPTIONS
          - PATCH
          - POST
          - PUT
          - TRACE
          Route: /ConfigItemGet/:ConfigItemID
        ConfigItemSearch:
          RequestMethod:
          - CONNECT
          - DELETE
          - GET
          - HEAD
          - OPTIONS
          - PATCH
          - POST
          - PUT
          - TRACE
          Route: /ConfigItemSearch/:ConfigItemID
        ConfigItemUpdate:
          RequestMethod:
          - CONNECT
          - DELETE
          - GET
          - HEAD
          - OPTIONS
          - PATCH
          - POST
          - PUT
          - TRACE
          Route: /ConfigItemUpdate/:ConfigItemID
        teste:
          RequestMethod:
          - CONNECT
          - DELETE
          - GET
          - HEAD
          - OPTIONS
          - PATCH
          - POST
          - PUT
          - TRACE
          Route: /ConfigItemUpdate/:ConfigItemID
        testeteste:
          RequestMethod:
          - CONNECT
          - DELETE
          - GET
          - HEAD
          - OPTIONS
          - PATCH
          - POST
          - PUT
          - TRACE
          Route: /ConfigItemUpdate/:ConfigItemID
    Type: HTTP::REST
RemoteSystem: ''
Requester:
  Invoker: {}
  Transport:
    Config:
      Authentication:
        AuthType: BasicAuth
        BasicAuthPassword: Pedas10extreme
        BasicAuthUser: ruben.sousa
      DefaultCommand: GET
      Host: http://10.35.3.19/otrs/nph-genericinterface.pl/Webservice/CMDBConnector
      Timeout: '120'
    Type: HTTP::REST
Last edited by VCSousa on 27 Jan 2021, 15:01, edited 1 time in total.
reneeb
Znuny guru
Posts: 5018
Joined: 13 Mar 2011, 09:54
Znuny Version: 6.0.x
Real Name: Renée Bäcker
Company: Perl-Services.de
Contact:

Re: ConfigItem Update

Post by reneeb »

You are using UTF-8 characters in your code. Please add

Code: Select all

use utf8;
after

Code: Select all

use warnings;
Perl / Znuny development: http://perl-services.de
Free Znuny add ons from the community: http://opar.perl-services.de
Commercial add ons: http://feature-addons.de
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

The error keeps the same.
skullz
Znuny superhero
Posts: 623
Joined: 24 Feb 2012, 03:58
Znuny Version: LTS and Features
Real Name: Mo Azfar
Location: Kuala Lumpur, MY
Contact:

Re: ConfigItem Update

Post by skullz »

1. ConfigItem Update WS configuration
ws2.PNG
ws1.PNG

2. Updated script

Code: Select all

#!/usr/bin/perl -w
# --
### OTRS 5S/OTRS 6
###
### **OTRS Generic Interface Webservice REST must be created first!!!!!!
###
### 1. Get some info from otrs via webservice rest ticket connector
###
use strict;
use warnings;

## nofilter(TidyAll::Plugin::OTRS::Perl::Dumper)

## use ../ as lib location
use File::Basename;
use FindBin qw($RealBin);
use lib dirname($RealBin);

use JSON;
use REST::Client;
use Data::Dumper;
## ---
## Variables to be defined

my $Host = 'http://192.168.17.128:8080/development/nph-genericinterface.pl';

my $RestClient = REST::Client->new(
    {
        host => $Host,
    }
);

$RestClient->addHeader('Content-Type', 'application/json');
$RestClient->addHeader('charset', 'UTF-8');
$RestClient->addHeader('Accept', 'application/json');

my $User="admin";
my $Pass="123"; 
my $ConfigItemID = "8";

####################################START REST CI UPDATE#####################################
# Method: PATCH
# Endpoint: /ConfigItemUpdate/$CIID
# OTRS Route Mapping: /ConfigItemUpdate/:ConfigItemID


my $ControllerAndRequest2 = "/Webservice/GenericTicketConnectorREST/ConfigItemUpdate/$ConfigItemID";

## ticket parameter need to be pass for create a ticket
my $Params2 = {
    UserLogin => $User,       # to be filled with valid agent login
    Password  => $Pass,    # to be filled with valid agent password
    ReplaceExistingData => 0,
	ConfigItem    => 
    {
        Class	=> "Computer",
		Name	=> 'PC 4',
		DeplState => 'Planned',
		InciState => 'Operational',
		
        ##PLEASE REFER REST CI SEARCH RESULT FOR AVAILABLE PARAM FOR EACH CLASS
		# it depends on the Configuration Item class and definition
		#CIXMLData	=> 
        #{
        #    #SerialNumber     => "12345",
        #    Vendor            => "HP XXXXXX",   #update this field
		#	NIC => [
        #                    {
        #                      'NIC' => 'wdXXXX',  #update this field
        #                      'IPoverDHCP' => 'Yes'   #update this field
        #                    }
        #                ],
        #}
    },
};

my @RequestParam2;

# # ----
# # For POST method
my $JSONParams2 = encode_json $Params2;
#print Dumper($JSONParams);

# # The @RequestParam array on position 0 holds controller and request
# # on position 1 it holds the JSON data string that gets posted
@RequestParam2 = (
   $ControllerAndRequest2,
   $JSONParams2
 );

$RestClient->PATCH(@RequestParam2);

## If the host isn't reachable, wrong configured or couldn't serve the requested page:
my $ResponseCode2 = $RestClient->responseCode();
if ( $ResponseCode2 ne '200' ) {
    print "Request failed, response code was: $ResponseCode2\n";
    exit;
}

# If the request was answered correctly, we receive a JSON string here.
my $ResponseContent2 = $RestClient->responseContent();

my $Data2 = decode_json $ResponseContent2;

## Just to print out the returned Data structure:
print "Update Response was:\n";
print Dumper($Data2);

#########################################END REST CI GET##################################

Lol i forgot to change and add some header..
Tested it and worked on my machine , at least
ws3.PNG
You do not have the required permissions to view the files attached to this post.
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

Skullz,

A many thanks for the work. I think that i'm very close to the solution.

Now i'm getting an error about enconded text:

Code: Select all

[root@PT01NS19 ~]# ./rest2
Update Response was:
$VAR1 = {
          'Error' => {
                       'ErrorCode' => 'ConfigItemUpdate.InvalidParameter',
                       'ErrorMessage' => 'ConfigItemUpdate: ConfigItem->Class parameter is invalid!'
                     }
        };
[root@PT01NS19 ~]#
This are giving that error cause this:

Code: Select all

Incoming data after mapping (2021-01-27 08:15:24, debug)
$VAR1 = {
  'ConfigItem' => {
    'CIXMLData' => {
      'Name' => 'PTL011BBB'
    },
    'Class' => 'Portátil',
    'DeplState' => '001. Produção',
    'InciState' => 'Operational',
    'Name' => 'PTL011'
  },
  'ConfigItemID' => '16',
  'Password' => '###########',
  'ReplaceExistingData' => 0,
  'UserLogin' => 'ruben.sousa'
};
It should be Class: Portátil and DeplState: 001. Produção
skullz
Znuny superhero
Posts: 623
Joined: 24 Feb 2012, 03:58
Znuny Version: LTS and Features
Real Name: Mo Azfar
Location: Kuala Lumpur, MY
Contact:

Re: ConfigItem Update

Post by skullz »

as per error, the config item class not exists.
More like wording encode issue..
maybe try to' use utf8;' at the script as recommended by
reneeb wrote: 26 Jan 2021, 16:42use utf8;
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

I already tried.

The error is now:

Code: Select all

[root@PT01NS19 ~]# ./rest2
malformed JSON string, neither tag, array, object, number, string or atom, at character offset 0 (before "<!DOCTYPE HTML PUBLI...") at ./rest2 line 106.
The line 106 are the "my $Data2 = decode_json $ResponseContent2;"

Code: Select all

my @RequestParam2;

# # ----
# # For POST method
my $JSONParams2 = encode_json $Params2;
#print Dumper($JSONParams);

# # The @RequestParam array on position 0 holds controller and request
# # on position 1 it holds the JSON data string that gets posted
@RequestParam2 = (
   $ControllerAndRequest2,
   $JSONParams2
 );

$RestClient->PATCH(@RequestParam2);

## If the host isn't reachable, wrong configured or couldn't serve the requested page:
my $ResponseCode2 = $RestClient->responseCode();
if ( $ResponseCode2 ne '200' ) {
    print "Request failed, response code was: $ResponseCode2\n";
    exit;
}

# If the request was answered correctly, we receive a JSON string here.
my $ResponseContent2 = $RestClient->responseContent();

my $Data2 = decode_json $ResponseContent2;

## Just to print out the returned Data structure:
print "Update Response was:\n";
print Dumper($Data2);

#########################################END REST CI GET##################################
reneeb
Znuny guru
Posts: 5018
Joined: 13 Mar 2011, 09:54
Znuny Version: 6.0.x
Real Name: Renée Bäcker
Company: Perl-Services.de
Contact:

Re: ConfigItem Update

Post by reneeb »

What does the error log and the debugger say? OTRS seems to send some HTML...
Perl / Znuny development: http://perl-services.de
Free Znuny add ons from the community: http://opar.perl-services.de
Commercial add ons: http://feature-addons.de
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

The error no HTTPD are:

Code: Select all

[Wed Jan 27 11:07:56.243637 2021] [:error] [pid 31873] Can't use string ("") as a HASH ref while "strict refs" in use at /opt/otrs//Kernel/GenericInterface/Operation/ConfigItem/Common.pm line 745.\n
About the debug is:

Image
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

I already passed this errors.

The problem was on Config Item used, that had an error on DB about my experiments :O

It is possible make this script run with GenericAgent?
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

I saw this. Is it possible, run it as a command. What trigger it, for now, is not important (I have to redesign some processes to it). What I wanted to is, as arguments, pass the ID, Name and DeplState.

https://forums.otterhub.org/viewtopic.php?t=32538
skullz
Znuny superhero
Posts: 623
Joined: 24 Feb 2012, 03:58
Znuny Version: LTS and Features
Real Name: Mo Azfar
Location: Kuala Lumpur, MY
Contact:

Re: ConfigItem Update

Post by skullz »

Back to your 1st post, you are using it with Process Management which is ticketing.

What i can suggest,

1. Somehow, you have to save the Config item id in the ticket dynamic field. Check oparl for the cmdb dynamic field addon.

2. Execute Generic agent upon some ticket action.
- With option to 'Execute Ticket Commands' -> 'CMD' : /usr/bin/perl/config_item.pl
- Generic agent will auto pass ARG[0[ and ARG[1]. **ARG[0] will be the ticket number. ARG[1] the ticket id.

3. Regarding config_item.pl,
- So use ARG[1] value (ticket id) to get the ticket dynamic field value that hold the config item id (using the webservices).
- Maybe also grab another value from another dynamic field.
- Then, use this config item id (alongside with another value) to perform the config item update (you got this already).

4. Personally, i rather use 'Execute Custom Module' option so i dont have to deals with the webservices.

5. Either way, perl and programming knowledge is needed.

Good luck.
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

Hi Skullz,

Thanks in advance by all the help provided.

Abou the firt point, i already use that Addon, and thats not the problem how I get the info to use.

I have no idea how to build a module, and my knowledge with perl is not my key.

About running the script, with args, can you, or someone, give me some lights about how can I pass the Dynamic Fields as Args to the your pearl script?
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

I already figured it out how to use Args on Perl and pass it to the script.

Can I pass directly, by a TAG maybe, the DynamicField in the Generic Agent?
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

I got this error when trying to execute the script from Generic Agent CMD. I have already CPAN REST::Client installed

Code: Select all

Can't locate REST/Client.pm in @INC (@INC contains: /opt/otrs /usr/local/lib64/perl5 /usr/local/share/perl5 /usr/lib64/perl5/vendor_perl /usr/share/perl5/vendor_perl /usr/lib64/perl5 /usr/share/perl5 .) at /opt/otrs/bin/ConfigItemUpdateDeplState.pl line 21.
BEGIN failed--compilation aborted at /opt/otrs/bin/ConfigItemUpdateDeplState.pl line 21.
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

Updating this, I developed a Shell script to be runned by GA.

The shell script take the TicketID passeb by GA and execute a Curl request as TicketGet and process the data to save on a Var the ConfigItemID (That are on a DynamicField).

With the ConfigItemID, the shell script execute another Curl request as ConfigItemGet and process the data to save in Vars the Name, Class, DeplState, whatever.

With this in vars, i'm able on the Shell script to call the Skullz perl script with args, that i already could put working.

The problem now is, per example, the Class is "Portátil" and are passed by the shell script correctly as utf8. But when the var on Perl script are used, isn't in utf8 and give error cause the encode. (On perl script, if i use the string instead of VAR) it runs normally. Follow the codes:

Perl Script

Code: Select all

#!/usr/bin/perl -w
# --
### OTRS 5S/OTRS 6
###
### **OTRS Generic Interface Webservice REST must be created first!!!!!!
###
### 1. Get some info from otrs via webservice rest ticket connector
###
use strict;
use warnings;
use utf8;

## nofilter(TidyAll::Plugin::OTRS::Perl::Dumper)

## use ../ as lib location
use File::Basename;
use FindBin qw($RealBin);
use lib dirname($RealBin);

use JSON;
use REST::Client;
use Data::Dumper;

## ---
## Variables to be defined

##my $numArgs = $#ARGV + 1;
#print "thanks, you gave me $numArgs command-line arguments.\n";

## foreach my $argnum (0 .. $#ARGV) {

##	print "$ARGV[$argnum]\n";
##	my $DeplState = $ARGV[$argnum];
##	print "$DeplState\n";
##}

#my $CIDeplState = $ARGV[0];
#my $CIName = $ARGV[1];
#my $CINumber = [$ARGV[2];

my $Host = 'http://10.35.3.19/otrs/nph-genericinterface.pl';

my $RestClient = REST::Client->new(
    {
        host => $Host,
    }
);

$RestClient->addHeader('Content-Type', 'application/json');
$RestClient->addHeader('charset', 'UTF-8');
$RestClient->addHeader('Accept', 'application/json');

my $User="ruben.sousa";
my $Pass="###########"; 
my $ConfigItemID=$ARGV[0];
#my $ConfigItemName=$ARGV[2];
my $ConfigItemClass=$ARGV[1];

####################################START REST CI UPDATE#####################################
# Method: PATCH
# Endpoint: /ConfigItemUpdate/$CIID
# OTRS Route Mapping: /ConfigItemUpdate/:ConfigItemID


my $ControllerAndRequest2 = "/Webservice/CMDBConnector/ConfigItemUpdate/$ConfigItemID";


## ticket parameter need to be pass for create a ticket
my $Params2 = {
    UserLogin => $User,       # to be filled with valid agent login
    Password  => $Pass,    # to be filled with valid agent password
    ReplaceExistingData => 0,
	ConfigItem    => 
    {
        	Class		=> 'Portátil',
		Name		=> 'PTL011BB',
		DeplState 	=> '001. Produção',
		InciState 	=> 'Operational',
		
        ##PLEASE REFER REST CI SEARCH RESULT FOR AVAILABLE PARAM FOR EACH CLASS
		# it depends on the Configuration Item class and definition
	#	CIXMLData	=> 
        #	{
	#		Name		=> 'PTL011'
        #    		SerialNumber	=> '12345',
        #    		Vendor          => "HP XXXXXX",   #update this field
	#		NIC 		=> [
        #               	{
        #               		'NIC' => 'wdXXXX',  #update this field
        #              			'IPoverDHCP' => 'Yes'   #update this field
        #                    	}
        #                	],
        #	}
    },
};

my @RequestParam2;

# # ----
# # For POST method
my $JSONParams2 = encode_json $Params2;
#print Dumper($JSONParams);

# # The @RequestParam array on position 0 holds controller and request
# # on position 1 it holds the JSON data string that gets posted
@RequestParam2 = (
   $ControllerAndRequest2,
   $JSONParams2
 );

$RestClient->PATCH(@RequestParam2);

## If the host isn't reachable, wrong configured or couldn't serve the requested page:
my $ResponseCode2 = $RestClient->responseCode();
if ( $ResponseCode2 ne '200' ) {
    print "Request failed, response code was: $ResponseCode2\n";
    exit;
}

# If the request was answered correctly, we receive a JSON string here.
my $ResponseContent2 = $RestClient->responseContent();

my $Data2 = decode_json $ResponseContent2;

## Just to print out the returned Data structure:
print "Update Response was:\n";
print Dumper($Data2);

#########################################END REST CI GET##################################

Shell Script

Code: Select all

#!/bin/bash

######  Variáveis extraídas do Generic Agent

ticketNumber=$1
#ticketID=$2
ticketID=3639

######  Construção do URL para extraír o ConfigItemID do Ticket

urlTicket1="http://10.35.3.19/otrs/nph-genericinterface.pl/Webservice/CMDBConnector/TicketGet/"
urlTicket2="?UserLogin=ruben.sousa&Password=&DynamicFields=1"
urlTicketFull=$urlTicket1$ticketID$urlTicket2

######  Extração do ConfigItemID do Ticket

curl=$(curl -s -X PATCH "$urlTicketFull")
curlLine=$(echo $curl | awk '{gsub(/\}/,"\n")}1' | grep ConfigItemTeste)
configItemID=$(echo $curlLine | awk '{print substr($1,11); }' | cut -d'"' -f2)

######  Construção do URL para extraír o ConfigItem

url1="http://10.35.3.19/otrs/nph-genericinterface.pl/Webservice/CMDBConnector/ConfigItemGet/"
url2="?UserLogin=ruben.sousa&Password="
urlFull=$url1$configItemID$url2

######  Extração do Name do ConfigItem

curl=$(curl -s -X PATCH "$urlFull")
curlLineCI=$(echo $curl | awk '{gsub(/\,/,"\n")}1' | grep Name)
configItemName=$(echo $curlLineCI | awk '{print substr($1,8); }' | cut -d'"' -f2)

######  Extração da Class do ConfigItem

curlLineCI=$(echo $curl | awk '{gsub(/\,/,"\n")}1' | grep Class)
configItemClass=$(echo $curlLineCI | awk '{print substr($1,8); }' | cut -d'"' -f2)

######  Confirmação de Execução do GA

echo $ticketNumber > /opt/otrs/variaveis
echo $ticketID >> /opt/otrs/variaveis
echo $configItemID >> /opt/otrs/variaveis
echo $configItemName >> /opt/otrs/variaveis
echo $configItemClass >> /opt/otrs/variaveis

/opt/otrs/ConfigItemUpdateDeplState.pl $configItemID $configItemClass
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

I solve it by adding this on perl script right after "use utf8;":

use Encode;
@ARGV = map { decode( 'utf8', $_ ) } @ARGV;
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

When I run the shell script with ticketID manually from the command line. All executes well.

If i run from generic agent, the shell script runs well and collect all the information, but the Perl script, gives me the follow error:

Image
VCSousa
Znuny newbie
Posts: 62
Joined: 05 Feb 2020, 17:45
Znuny Version: OTRS6
Real Name: Ruben Sousa
Company: Zolve - Logistic and Transport, S.A.

Re: ConfigItem Update

Post by VCSousa »

With some searching, i realized that, the Module REST::Client, was installed, with root and not acessible to OTRS user. With this, I have installed it again, with otrs user on CentOS.

With this. Everything is working now.

With time, i will do a catch to all the codes and publish it here as a Solution to Update CI's with Generic Agent.

It probably isn't the best code (I'm not a coder) but works.
Post Reply