Search

Chapter 5. Transitioning to the Satellite 6 API

download PDF

One of the many differences between Red Hat Satellite 5 and Satellite 6 is the API. Satellite 5 uses an XMLRPC-based API. Satellite 6 uses a REST-based API. This fundamental difference requires that any existing scripts or tools that have been integrated with the Satellite 5 API must be reviewed and at least partially rewritten before use with the Satellite 6 REST API.

This section provides some comparisons of how to achieve the same use case within each Product. This is not designed to be a tutorial in any specific programming language. Neither are the scripts secured over HTTPS. They provide a starting point for anyone maintaining Satellite 5 API scripts to start the transition to the Satellite 6 API.

Important

The Satellite 6 transition tools do not transition the Satellite 5 API or scripts to Satellite 6. Use this section as a starting point to begin your own transition process.

Further Information

You can find further API documentation at the following locations on your own Satellite Servers:

5.1. Example API Scripts

The examples in this section cover the following:

  1. Systems and hosts in Red Hat Satellite

    1. Authenticate and request a list of systems (Satellite 5) or hosts (Satellite 6) available to the user who logged in.
  2. Users and Roles

    1. Authenticate and request a list of all users visible to the user who logged in.
    2. Delete the example user if it exists.
    3. Create a new example user and ensure that its role is set to Administrator.

This section provides a total of five different ways to achieve the same result; two examples for Satellite 5 and three examples for Satellite 6.

  • A Satellite 5 Python script
  • A Satellite 6 Python script
  • A Satellite 6 Ruby script
  • A Satellite 5 spacecmd example
  • A Satellite 6 hammer example
Note

The spacecmd command is not a supported feature in Satellite 5.6. It is supported in Satellite 5.7, and is shown here for the sake of completeness.

A total of 10 examples are provided. The first examples cover the simpler use cases of listing systems and hosts, followed by the more complex examples covering users and roles.

5.1.1. Listing Systems and Hosts

The examples in this section describe different ways to list systems and hosts available to the user who logged in.

Using Python to List Available Systems on Satellite 5

This example uses a Python script to connect to Satellite 5, authenticate, and retrieve a list of available systems.

#!/usr/bin/python
import xmlrpclib

# Define Satellite location and login details
SATELLITE_URL = "http://localhost/rpc/api"
SATELLITE_LOGIN = "admin"
SATELLITE_PASSWORD = "password"

client = xmlrpclib.Server(SATELLITE_URL, verbose=0)

# Authenticate and get session key
key = client.auth.login(SATELLITE_LOGIN, SATELLITE_PASSWORD)

# Get list of systems available to user
list = client.system.listSystems(key)
for system in list:
   print system.get('id')
   print system.get('name')

# Logout
client.auth.logout(key)

Using Python to List Available Hosts on Satellite 6

This example uses a Python script to connect to Satellite 6, authenticate, and retrieve a list of available hosts.

#!/usr/bin/python
import json
import requests

# Define Satellite location and login details
SAT_API = "https://localhost/api/v2/"
USERNAME = "admin"
PASSWORD = "changeme"
SSL_VERIFY = False

def get_json(location):
    """
    Performs a GET using the passed URL location
    """

    r = requests.get(location, auth=(USERNAME, PASSWORD), verify=SSL_VERIFY)

    return r.json()

def main():
    # List all hosts available to the user
    hosts = get_json(SAT_API + "hosts/")

    # Pretty Print the returned JSON of Hosts
    print json.dumps(hosts, sort_keys=True, indent=4)

if __name__ == "__main__":

main()

Using Ruby to List Available Hosts on Satellite 6

This example uses a Ruby script to connect to Satellite 6, authenticate, and retrieve a list of available hosts.

#!/usr/bin/ruby193-ruby
require 'json'
require 'rest-client'

url = 'https://localhost/api/v2/'
$username = 'admin'
$password = 'changeme'

def get_json(location)
    response = RestClient::Request.new(
        :method => :get,
        :url => location,
        :user => $username,
        :password => $password,
        :headers => { :accept => :json,
        :content_type => :json }
    ).execute
    results = JSON.parse(response.to_str)
end

hosts = get_json(url+"hosts/")
#puts JSON.pretty_generate(hosts)

puts "Hosts within Satellite are:"
hosts['results'].each do |name|
      puts name['name']
end

exit()

Using the Command Line to List Available Systems on Satellite 5

Use the following command to list available systems on Satellite 5:

# spacecmd -u username -p password system_list

An example session might appear as follows:

# spacecmd -u admin -p password system_list

INFO: Spacewalk Username: admin
INFO: Connected to https://localhost/rpc/api as admin
test_02.example.com

Using the Command Line to List Available Hosts on Satellite 6

Use the following command to list available hosts on Satellite 6:

# hammer host list

An example session might appear as follows:

# hammer host list

[Foreman] password for admin:
---|-----------------|-------------------|------------|--------------|------------------
ID | NAME            | OPERATING SYSTEM  | HOST GROUP | IP           | MAC
---|-----------------|-------------------|------------|--------------|------------------
1  | test.example.com | RHEL Server 6.5  |            | 10.34.34.235 | e4:1f:13:6b:ed:0c

5.1.2. Deleting and Creating Users

The examples in this section describe different ways to locate, create, and delete users.

Using Python to Manage Users on Satellite 5

This example uses a Python script to connect to and authenticate against a Satellite 5 Server. It then goes on to search for a specific user (example), to delete that user if it exists, and then recreate it with Administrator privileges.

#!/usr/bin/python
import xmlrpclib

# Define Satellite location and login details
SATELLITE_URL = "http://localhost/rpc/api"
SATELLITE_LOGIN = "admin"
SATELLITE_PASSWORD = "password"

client = xmlrpclib.Server(SATELLITE_URL, verbose=0)

# Authenticate and get session key
key = client.auth.login(SATELLITE_LOGIN, SATELLITE_PASSWORD)

# Get list of users
list = client.user.list_users(key)
print "Existing users in Satellite:"
for user in list:
   print user.get('login')

# Look for user example and if found, delete the user
for user in list:
   if user.get('login') == 'example':
       deleteuser = client.user.delete(key, 'example')
       if deleteuser == 1:
           print "User example deleted"

# Create a user called example
createuser = client.user.create(key, 'example', 'password', 'Example', 'User', "root@localhost")
if createuser == 1:
    print "User example created"
    # Admin Org Admin role to the example user
    adminrole = client.user.addRole(key, 'example', 'org_admin')
    if adminrole == 1:
        print "Made example an Org Admin"

# Logout
client.auth.logout(key)

Using Python to Manage Users on Satellite 6

This example performs the same task as the previous example. That is, it uses a Python script to connect to and authenticate against a Satellite 6 Server, search for a specific user, delete that user if it exists, and then recreate it with Administrator privileges.

#!/usr/bin/python
import json
import requests

# Define Satellite location and login details
SAT_API = "https://localhost/api/v2/"
POST_HEADERS = {'content-type': 'application/json'}
USERNAME = "admin"
PASSWORD = "changeme"
SSL_VERIFY = False

def get_json(location):
    """
    Performs a GET using the passed URL location
    """
    r = requests.get(location, auth=(USERNAME, PASSWORD), verify=SSL_VERIFY)

    return r.json()

def post_json(location, json_data):
    """
    Performs a POST and passes the data to the URL location
    """
    result = requests.post(
        location,
        data=json_data,
        auth=(USERNAME, PASSWORD),
        verify=SSL_VERIFY,
        headers=POST_HEADERS)

    return result.json()

def delete_json(location):
    """
    Performs a DELETE and passes the id to the URL location
    """
    result = requests.delete(
        location,
        auth=(USERNAME, PASSWORD),
        verify=SSL_VERIFY)

    return result.json()

def main():
    # List all users within the Satellite
    users = get_json(SAT_API + "users/")

    #print json.dumps(users, indent=4)
    print "Users known are:"
    for login in users['results']:
        print login['login']

    # Look for user example and if found, delete the user
    for delete in users['results']:
        if delete['login'] == 'example':
            id = delete ['id']
            id = str(id)

            delete = delete_json(SAT_API + "/users/" + id)
            #print json.dumps(delete, indent=4)
            print "User example deleted"

    # Create a user called example as admin role
    createuser = post_json(SAT_API + "/users/", json.dumps({ "mail": "root@localhost", "firstname": "Example", "lastname": "User", "login": "example", "password": "redhat", "admin": 'true', "auth_source_id": 1 }))
    #print json.dumps(createuser, indent=4)
    print "Admin user example created"

if __name__ == "__main__":
    main()

Using Ruby to Manage Users on Satellite 6

This example uses Ruby to perform the same task as the previous examples.

#!/usr/bin/ruby193-ruby
require 'json'
require 'rest-client'

url = 'https://localhost/api/v2/'
$username = 'admin'
$password = 'changeme'

def get_json(location)
    response = RestClient::Request.new(
        :method => :get,
        :url => location,
        :user => $username,
        :password => $password,
        :headers => { :accept => :json,
        :content_type => :json }
    ).execute
    results = JSON.parse(response.to_str)
end

def post_json(location, json_data)
    response = RestClient::Request.new(
        :method => :post,
        :url => location,
        :user => $username,
        :password => $password,
        :headers => { :accept => :json,
        :content_type => :json},
        :payload => json_data
    ).execute
    results = JSON.parse(response.to_str)
end

def delete_json(location)
    response = RestClient::Request.new(
        :method => :delete,
        :url => location,
        :user => $username,
        :password => $password,
        :headers => { :accept => :json,
        :content_type => :json }
    ).execute
    results = JSON.parse(response.to_str)
end

# List all users within the Satellite
users = get_json(url+"users/")

#puts JSON.pretty_generate(users)
puts "Users known are:"
users['results'].each do |name|
    puts name['login']
end

# Look for user example and if found, delete the user
users['results'].each do |name|
    if name['login'] == 'example'
        id = name['id']
        delete = delete_json(url+"users/"+id.to_s)
        #puts JSON.pretty_generate(delete)
        puts "User example deleted"
    end
end

# Create a user called example as admin role
data = JSON.generate({ :mail => "root@localhost", :firstname => "Example", :lastname => "User", :login => "example", :password => "password", :admin => 'true', :auth_source_id => 1})
createuser = post_json(url+"users/", data)

#puts JSON.pretty_generate(createuser)
puts "Admin user example created"

exit()

Using the Command Line to Manage Users on Satellite 5

This example uses the spacecmd command to perform the same task as the previous examples.

# spacecmd -u admin -p password user_list
# spacecmd -u admin -p password user_delete example
# spacecmd -u admin -p password user_create
# spacecmd -u admin -p password user_addrole example org_admin

An example session might appear as follows:

# spacecmd -u admin -p password user_list
INFO: Spacewalk Username: admin
INFO: Connected to https://localhost/rpc/api as admin
admin
example

# spacecmd -u admin -p password user_delete example
INFO: Spacewalk Username: admin
INFO: Connected to https://localhost/rpc/api as admin

Delete this user [y/N]: y

# spacecmd -u admin -p password user_list
INFO: Spacewalk Username: admin
INFO: Connected to https://localhost/rpc/api as admin
admin

# spacecmd -u admin -p password user_create
INFO: Spacewalk Username: admin
INFO: Connected to https://localhost/rpc/api as admin
Username: example
First Name: Example
Last Name: User
Email: root@localhost
PAM Authentication [y/N]: n
Password:
Repeat Password:

# spacecmd -u admin -p password user_list
INFO: Spacewalk Username: admin
INFO: Connected to https://localhost/rpc/api as admin
admin
example

# spacecmd -u admin -p password user_addrole example org_admin
INFO: Spacewalk Username: admin
INFO: Connected to https://localhost/rpc/api as admin

# spacecmd -u admin -p password user_details example
INFO: Spacewalk Username: admin
INFO: Connected to https://localhost/rpc/api as admin
Username:      example
First Name:    Example
Last Name:     User
Email Address: root@localhost
Organization:  MY ORG
Last Login:
Created:       8/19/14 8:42:52 AM EDT
Enabled:       True

Roles
-----
activation_key_admin
channel_admin
config_admin
monitoring_admin
org_admin
system_group_admin

Using the Command Line to Manage Users on Satellite 6

This example uses the hammer command to perform the same task as the previous examples.

# hammer shell
> user list
> user delete --id 4 --login example
> user create --admin true --firstname Example --lastname User --login example --mail root@localhost --password redhat --auth-source-id 1

An example session might appear as follows:

# hammer shell
[Foreman] password for admin:
Welcome to the hammer interactive shell
Type 'help' for usage information

hammer> user list
---|---------|--------------|---------------
ID | LOGIN   | NAME         | EMAIL
---|---------|--------------|---------------
4  | example | Example User | root@localhost
3  | admin   | Admin User   | root@localhost
---|---------|--------------|---------------

hammer> user delete --id 4 --login example
User deleted
hammer> user list
---|-------|------------|---------------
ID | LOGIN | NAME       | EMAIL
---|-------|------------|---------------
3  | admin | Admin User | root@localhost
---|-------|------------|---------------

hammer> user create --admin true --firstname Example --lastname User --login example --mail root@localhost --password redhat --auth-source-id 1
User created
hammer> user list
---|----------|--------------|---------------
ID | LOGIN    | NAME         | EMAIL
---|----------|--------------|---------------
3  | admin    | Admin User   | root@localhost
5  | example  | Example User | root@localhost
---|----------|--------------|---------------
hammer>

5.2. Satellite 6 API Tips

This section provides some general tips to help optimize your experience with the Satellite 6 API.

Browsing the Satellite 6 API

If you have already logged in to the Satellite 6 web UI, you can see the default results of GET requests at /api/v2/<API-NAME>. For example:

Using Satellite 6 API Requests on the Command Line

You can use the curl command to interact with the Satellite 6 API. For example:

Example 5.1. Example GET Requests

Example GET requests to list organizations, hosts, and users within Satellite 6.

# SATUSER=admin
# SATPASS='changeme'
# SATURL="https://localhost"

# curl -k -u $SATUSER:$SATPASS -X GET -H \
'Accept: application/json' $SATURL/api/v2/organizations | json_reformat
# curl -k -u $SATUSER:$SATPASS -X GET -H \
'Accept: application/json' $SATURL/api/v2/hosts | json_reformat
# curl -k -u $SATUSER:$SATPASS -X GET -H \
'Accept: application/json' $SATURL/api/v2/users | json_reformat
# curl -k -u $SATUSER:$SATPASS -X GET -H \
'Accept: application/json' $SATURL/api/v2/users/3 | json_reformat

Example 5.2. Example DELETE Request

An example DELETE request to remove an existing user with known ID "9" based on a previous list of users.

# curl -k -u $SATUSER:$SATPASS -X DELETE -H \
'Accept: application/json' $SATURL/api/v2/users/9 | json_reformat

Example 5.3. Example POST Request

An example POST request to create a new user called example, passing the true flag to enable administrator privileges for the user.

# curl -k -u $SATUSER:$SATPASS -X POST \
-d '{ "mail": "root@localhost", "firstname": "Example", \
"lastname": "User", "login": "example", "password": "redhat", \
"admin": 'true', "auth_source_id": 1 }' \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
$SATURL/api/v2/users | json_reformat

Example 5.4. Example PUT Request

An example PUT request to change the email address of the existing example user with known ID "10" to example@localhost.

# curl -k -u $SATUSER:$SATPASS -X PUT \
-d '{ "id": 10, "mail": "example@localhost" }' \
-H 'Accept: application/json' \
-H 'Content-Type: application/json' \
$SATURL/api/v2/users/10 | json_reformat
Red Hat logoGithubRedditYoutubeTwitter

Learn

Try, buy, & sell

Communities

About Red Hat Documentation

We help Red Hat users innovate and achieve their goals with our products and services with content they can trust.

Making open source more inclusive

Red Hat is committed to replacing problematic language in our code, documentation, and web properties. For more details, see the Red Hat Blog.

About Red Hat

We deliver hardened solutions that make it easier for enterprises to work across platforms and environments, from the core datacenter to the network edge.

© 2024 Red Hat, Inc.