第4章 Red Hat Satellite API のスタートガイド
url = 'https://satellite6.example.com/api/v2/'
capsule_url = 'https://capsule.example.com:8443/api/v2/'
katello_url = 'https://satellite6.example.com/katello/api/v2/'
/etc/rhsm/rhsm.conf ファイルの [server] セクションの エントリーをもとに、API へのアクセスに必要な、正しいポートを判断できます。これらの値を使用してスクリプトを完全に自動化し、使用するポートを検証する必要性をなくします。
4.1. curl を使用した API の例 リンクのコピーリンクがクリップボードにコピーされました!
4.1.1. シンプルなクエリーの実行 リンクのコピーリンクがクリップボードにコピーされました!
-k (セキュアでない)オプションを使用して証明書チェックを省略することができます。
-u username:password を使用するか、パスワードを含めない場合はコマンドにより入力が求められます。Red Hat は、コマンドの一部としてパスワードを含めないことを推奨します。パスワードはシェル履歴の一部になり、セキュリティーリスクが生じる可能性があります。この例には、簡素化の目的でのみパスワードが含まれています。
-s (サイレント)オプションを使用する場合は、進捗メーターやエラーメッセージは表示されません。
リソースリストの取得
以下は、リソースの一覧を返す基本的なクエリーです。このような要求では、メタデータでラップされたデータリストを返しますが、他の要求タイプでは実際のオブジェクトが返されます。
$ curl -X GET -s -k -u sat_username:sat_password https://satellite6.example.com/api/v2/hosts | python -m json.tool
{
"total" => 2,
"subtotal" => 2,
"page" => 1,
"per_page" => 1000,
"search" => nil,
"sort" => {
"by" => nil,
"order" => nil
},
"results" => [
...
}
例4.1 ユーザーのリスト表示
$ curl -X GET -s -k -u sat_username:sat_password https://satellite6.example.com/api/users
{
"total": 1,
"subtotal": 1,
"page": 1,
"per_page": 20,
"search": null,
"sort": {
"by": null,
"order": null
},
"results": [{"firstname":"Admin","lastname":"User","mail":"root@example.com","admin":true,"auth_source_id":1,"auth_source_name":"Internal","timezone":null,"locale":null,"last_login_on":"2017-02-08 23:25:51 UTC","created_at":"2017-01-09 12:10:02 UTC","updated_at":"2017-02-08 23:25:51 UTC","id":3,"login":"admin","default_location":null,"locations":[],"default_organization":{"id":1,"name":"Default Organization","title":"Default Organization","description":null},"organizations":[]}]
}
一般的なホストクエリーの実行
以下のクエリーは、satellite6.example.com ホストの情報を返します。
$ curl -X GET -s -k -u sat_username:sat_password https://satellite6.example.com/api/v2/hosts/satellite6.example.com | python -m json.tool
{
"all_puppetclasses": [],
"architecture_id": 1,
"architecture_name": "x86_64",
"build": false,
"capabilities": [
"build"
],
"certname": "satellite6.example.com",
"comment": null,
"compute_profile_id": null,
...
}
特定のホストのファクト検索
以下のクエリーは、satellite6.example.com ホストの全ファクトを返します。
$ curl -X GET -s -k -u sat_username:sat_password https://satellite6.example.com/api/v2/hosts/satellite6.example.com/facts | python -m json.tool
{
...
"results": {
"satellite6.example.com": {
"augeasversion": "1.0.0",
"bios_release_date": "01/01/2007",
"bios_version": "0.5.1",
"blockdevice_sr0_size": "1073741312",
"facterversion": "1.7.6",
...
}
一致するパターンがあるか全ホストの検索
以下のクエリーは、example というパターンと一致するホストをすべて返します。
$ curl -X GET -s -k -u sat_username:sat_password https://satellite6.example.com/api/v2/hosts?search=example | python -m json.tool
{
...
"results": [
{
"name": "satellite6.example.com",
...
}
],
"search": "example",
...
}
特定の環境内の全ホスト検索
以下のクエリーは、production 環境内の全ホストを返します。
$ curl -X GET -s -k -u sat_username:sat_password https://satellite6.example.com/api/v2/hosts?search=environment=production | python -m json.tool
{
...
"results": [
{
"environment_name": "production",
"name": "satellite6.example.com",
...
}
],
"search": "environment=production",
...
}
特定のファクト値を持つ全ホストの検索
以下のクエリーでは、RHEV Hypervisor というモデル名を持つホストがすべて返されます。
$ curl -X GET -s -k -u sat_username:sat_password https://satellite6.example.com/api/v2/hosts?search=model=\"RHEV+Hypervisor\" | python -m json.tool
{
...
"results": [
{
"model_id": 1,
"model_name": "RHEV Hypervisor",
"name": "satellite6.example.com",
...
}
],
"search": "model=\"RHEV Hypervisor\"",
...
}
4.1.2. リソースの作成および変更 リンクのコピーリンクがクリップボードにコピーされました!
Accept:version=2 を使用するのと同じです。URL の仕様が優先されます。
$ curl -H "Accept:application/json,version=2" \
-H "Content-Type:application/json" -X POST \
-u username:password -k \
-d json-formatted-data https://satellite6.example.com
$ curl -H "Accept:application/json,version=2" \
-H "Content-Type:application/json" -X POST -u sat_username:sat_password \
-k -d "{\"architecture\":{\"name\":\"i686\"}}" \
https://satellite6.example.com/api/architectures
{"name":"i686","id":3,"created_at":"2015-10-29T13:21:09Z","updated_at":"2015-10-29T13:21:09Z","operatingsystems":[],"images":[]}
$ curl -X GET -u sat_username:sat_password -k https://satellite6.example.com/api/v2/architectures | python -m json.tool
{
"page": 1,
"per_page": 20,
"results": [
{
"created_at": "2015-04-02T05:29:46Z",
"id": 2,
"name": "i386",
"updated_at": "2015-04-02T05:29:46Z"
},
{
"created_at": "2015-04-02T05:29:46Z",
"id": 1,
"name": "x86_64",
"updated_at": "2015-04-02T05:29:46Z"
},
{
"created_at": "2015-11-04T19:40:15Z",
"id": 3,
"name": "i686",
"updated_at": "2015-11-04T19:40:15Z"
}
],
"search": null,
"sort": {
"by": null,
"order": null
},
"subtotal": 3,
"total": 3
}
$ hammer -u sat_username -p sat_password architecture list
---|-------
ID | NAME
---|-------
2 | i386
1 | x86_64
3 | i686
---|-------
例4.2 新しいユーザーの作成
$ curl -H "Accept:application/json,version=2" \
-H "Content-Type:application/json" -X POST \
-u sat_username:sat_password -k \
-d "{\"firstname\":\"Test\",\"lastname\":\"API-User\",\"mail\":\"test@example.com\",\"login\":\"test_api\",\"password\":\"123456\",\"auth_source_id\":1}" \
https://satellite6.example.com/api/users
4.1.2.1. Satellite Server へのコンテンツのアップロード リンクのコピーリンクがクリップボードにコピーされました!
- アップロード要求を作成します。
- コンテンツをアップロードします。
- コンテンツをインポートします。
- アップロード要求を削除します。
手順4.1 Satellite Server へのコンテンツのアップロード
- アップロード要求を作成します。デプロイメントに合わせてサンプルパラメーターを変更するようにしてください。
$ curl -H "Accept:application/json,version=2" \ -H "Content-Type:application/json" \ -X POST \ -u sat_username:sat_password -k -d "{}" \ https://satellite6.example.com/katello/api/repositories/3/content_uploadsこのコマンドは、以下のようなupload_idを返します。{"upload_id":"0be156b1-f373-4cad-89d0-924f8f4491d2","_href":"/pulp/api/v2/content/uploads/0be156b1-f373-4cad-89d0-924f8f4491d2/"} - コンテンツをアップロードします。データのアップロード時には、正しい MIME タイプを使用していることを確認します。application/json MIME タイプは、Satellite 6 に対する要求の大部分に使用されます。
upload_idと MIME タイプ、およびその他のパラメーターを組み合わせてコンテンツをアップロードします。$ curl -H "Accept:application/json,version=2" \ -H "Content-Type:multipart/form-data" \ -X PUT \ -u sat_username:sat_password \ -k --data-urlencode "content@/home/sat6user/rpmbuild/RPMS/noarch/python-scripttest-1.1.1-1.fc21.noarch.rpm" \ --data-urlencode offset=0 \ https://satellite6.example.com/katello/api/repositories/3/content_uploads/0be156b1-f373-4cad-89d0-924f8f4491d2 - Satellite Server にコンテンツをアップロードした後に、適切なリポジトリーにそのコンテンツをインポートする必要があります。この手順を完了するまで、Satellite Server は新しいコンテンツを認識しません。
$ curl -H "Accept:application/json,version=2" \ -H "Content-Type:application/json" \ -X PUT \ -u sat_username:sat_password \ -k -d "{\"upload_ids\":[\"0be156b1-f373-4cad-89d0-924f8f4491d2\"]}" \ https://satellite6.example.com/katello/api/repositories/3/import_uploads - コンテンツのアップロードおよびインポートが正常に完了したら、アップロード要求を削除することができます。これにより、アップロード中に使用された一時的なディスク領域を解放できます。
$ curl -H "Accept:application/json,version=2" \ -H "Content-Type:application/json" \ -X DELETE -d "{}" \ -u sat_username:sat_password \ -k https://satellite6.example.com/katello/api/repositories/3/content_uploads/0be156b1-f373-4cad-89d0-924f8f4491d2
例4.3 30 MB よりも大きいコンテンツのアップロード
- サンプルモジュールをダウンロードします。
$ wget https://forgeapi.puppetlabs.com/v3/files/theforeman-foreman-5.0.1.tar.gz?_ga=1.267255502.1792403825.1430297670 -O theforeman-foreman-5.0.1.tar.gz50,000 バイトのチャンクにモジュールを分割します。$ split --bytes 50000 --numeric-suffixes --suffix-length=1 theforeman-foreman-5.0.1.tar.gz foreman_module.結果ファイルを表示します。$ ls -la theforeman-foreman-5.0.1.tar.gz foreman_module.* -rw-r--r--. 1 root root 50000 Nov 4 04:42 foreman_module.0 -rw-r--r--. 1 root root 32928 Nov 4 04:42 foreman_module.1 -rw-r--r--. 1 root root 82928 Nov 4 04:41 theforeman-foreman-5.0.1.tar.gz - 新しいアップロード要求を作成します(これは Satellite Server の cat に相当します)。
$ curl -H "Accept:application/json,version=2" \ -H "Content-Type:application/json" \ -X POST \ -u sat_username:sat_password -k -d "{}" \ https://ibm-vm01.example.com/katello/api/repositories/2/content_uploads上記のコマンドはアップロード ID を返します。{"upload_id":"9585528f-07ad-4bb1-9c80-ccece249b2b7","_href":"/pulp/api/v2/content/uploads/9585528f-07ad-4bb1-9c80-ccece249b2b7/"} - ステップ 1 で作成したファイルのチャンクをアップロードします。以下の例で
offsetパラメーターを使用して、ファイルサイズと関連付けている点に注意してください。$ curl -H "Accept:application/json,version=2" \ -H "Content-Type:multipart/form-data" \ -X PUT \ -u sat_username:sat_password \ -k --data-urlencode "content@foreman_module.0" \ --data-urlencode offset=0 \ https://ibm-vm01.example.com/katello/api/repositories/2/content_uploads/9585528f-07ad-4bb1-9c80-ccece249b2b7$ curl -H "Accept:application/json,version=2" \ -H "Content-Type:multipart/form-data" \ -X PUT \ -u sat_username:sat_password \ -k --data-urlencode "content@foreman_module.1" \ --data-urlencode offset=50000 \ https://ibm-vm01.example.com/katello/api/repositories/2/content_uploads/9585528f-07ad-4bb1-9c80-ccece249b2b7 - 完全なアップロードをリポジトリーにインポートします。
$ curl -H "Accept:application/json,version=2" \ -H "Content-Type:application/json" \ -X PUT \ -u sat_username:sat_password \ -k -d "{\"upload_ids\":[\"9585528f-07ad-4bb1-9c80-ccece249b2b7\"]}" \ https://ibm-vm01.example.com/katello/api/repositories/2/import_uploads - アップロード要求を削除します。
$ curl -H "Accept:application/json,version=2" \ -H "Content-Type:application/json" \ -X DELETE -d "{}" \ -u sat_username:sat_password \ -k https://ibm-vm01.example.com/katello/api/repositories/2/content_uploads/9585528f-07ad-4bb1-9c80-ccece249b2b7 - Satellite サーバーにログインして、ファイルが正しく転送されたかどうかを確認します。
$ ls -la /var/lib/pulp/content/puppet_module/theforeman-foreman-5.0.1.tar.gz -rw-r--r--. 1 apache apache 82928 Nov 4 04:55 /var/lib/pulp/content/puppet_module/theforeman-foreman-5.0.1.tar.gzファイルを比較します。$ cmp /var/lib/pulp/content/puppet_module/theforeman-foreman-5.0.1.tar.gz theforeman-foreman-5.0.1.tar.gz$ echo $? 0
4.1.3. スマートクラスのオーバーライド リンクのコピーリンクがクリップボードにコピーされました!
GET /api/smart_class_parameters のようになります。curl を使用すると、コマンドは以下のようになります。
$ curl -X GET -s -k -u sat_username:sat_password \
https://satellite6.example.com/api/smart_class_parameters
$ curl -X GET -s -k -u sat_username:sat_password https://satellite6.example.com/api/puppetclasses/5/smart_class_parameters
puppetclass_name と key の 2 つで、特定のパラメーターを検索できます。たとえば、-- d, -- data オプションを使用して、URL のエンコードデータを渡します。
$ curl -X GET -s -k -u sat_username:sat_password https://satellite6.example.com/api/smart_class_parameters -d 'search=puppetclass_name = access_insights_client and key = authmethod'
GET /api/smart_class_parameters/63 です。curl を使用すると、コマンドは以下のようになります。
$ curl -X GET -s -k -u sat_username:sat_password \
https://satellite6.example.com/api/smart_class_parameters/63
$ curl -H "Accept:application/json,version=2" \
-H "Content-Type:application/json" -X PUT \
-s -k -u sat_username:sat_password \
-d '{"smart_class_parameter":{"override":true}}' \
https://satellite6.example.com/api/smart_class_parameters/63
$ curl -H "Accept:application/json,version=2" \
-H "Content-Type:application/json" -X PUT \
-s -k -u sat_username:sat_password \
-d '{"smart_class_parameter":{"override_value":{"match":"hostgroup=Test","value":"2.4.6"}}}' \
https://satellite6.example.com/api/smart_class_parameters/63
$ curl -X DELETE -s -u sat_username:sat_password \
https://satellite6.example.com/api/smart_class_parameters/63/override_values/3
4.1.3.1. 外部ファイルを使用したスマートクラスパラメーターの変更 リンクのコピーリンクがクリップボードにコピーされました!
手順4.2 外部ファイルを使用したスマートクラスパラメーターの変更
- motd という名前で Puppet クラスを検索します。今回の例では、motd という名前で検索します。
$ curl -H "Accept:application/json,version=2" \ -H "Content-Type:application/json" -X GET \ -u sat_user:sat_passwd -k \ "https://satellite6.example.com/api/smart_class_parameters?search=puppetclass_name=motd” \ | python -m json.tool { "page": 1, "per_page": 20, "results": [ { "avoid_duplicates": false, "created_at": "2017-02-06 12:37:48 UTC", "default_value": "", "description": "", "hidden_value": "*****", "hidden_value?": false, "id": 3, "merge_default": false, "merge_overrides": false, "override": false, "override_value_order": "fqdn\nhostgroup\nos\ndomain", "override_values_count": 0, "parameter": "content", "parameter_type": "string", "puppetclass_id": 3, "puppetclass_name": "motd", "required": false, "updated_at": "2017-02-07 13:08:42 UTC", "use_puppet_default": false, "validator_rule": null, "validator_type": "" }, { "avoid_duplicates": false, "created_at": "2017-02-06 12:37:48 UTC", "default_value": true, "description": "", "hidden_value": "*****", "hidden_value?": false, "id": 1, "merge_default": false, "merge_overrides": false, "override": false, "override_value_order": "fqdn\nhostgroup\nos\ndomain", "override_values_count": 0,"parameter": "dynamic_motd", "parameter_type": "boolean", "puppetclass_id": 3, "puppetclass_name": "motd", "required": false, "updated_at": "2017-02-06 15:21:06 UTC", "use_puppet_default": null, "validator_rule": null, "validator_type": null }, { "avoid_duplicates": false, "created_at": "2017-02-06 12:37:48 UTC", "default_value": "", "description": "", "hidden_value": "*****", "hidden_value?": false, "id": 2, "merge_default": false, "merge_overrides": false, "override": false, "override_value_order": "fqdn\nhostgroup\nos\ndomain", "override_values_count": 0, "parameter": "template", "parameter_type": "string", "puppetclass_id": 3, "puppetclass_name": "motd", "required": false, "updated_at": "2017-02-06 15:21:06 UTC", "use_puppet_default": null, "validator_rule": null, "validator_type": null } ], "search": "puppetclass_name=motd", "sort": { "by": null, "order": null }, "subtotal": 3, "total": 66 }スマートクラスのパラメーターにはそれぞれ、同じ Satellite インスタンスでグローバルとなる ID が割り当てられています。Satellite Server では、motd クラスのcontentパラメーターはid=3となっています。Puppet クラス名の前に表示される Puppet クラス ID と混同しないようにしてください。 - パラメーター ID
3を使用して、motd パラメーター固有の情報を取得して、出力をoutput_file.jsonなどのファイルにリダイレクトします。$ curl -H "Accept:application/json,version=2" \ -H "Content-Type:application/json" -X GET \ -u sat_user:sat_passwd -k \ "https://satellite6.example.com/api/smart_class_parameters/3 \ | python -m json.tool > output_file.json - 1 つ前の手順で作成し
たファイルを、新しいファイル(changeed_file.jsonなど)にコピーして編集します。エディターでファイルを開き、必要な値を変更します。以下の例では、motd モジュールのコンテンツパラメーターを変更しますが、これには、overrideオプションをfalseからtrueに変更する必要があります。{ "avoid_duplicates": false, "created_at": "2017-02-06 12:37:48 UTC", # This line must be removed. "default_value": "", # A new value should be supplied here. "description": "", "hidden_value": "*****", "hidden_value?": false, "id": 3, "merge_default": false, "merge_overrides": false, "override": false, # The override value must be set to true. "override_value_order": "fqdn\nhostgroup\nos\ndomain", "override_values": [], # This line must be removed. "override_values_count": 0, "parameter": "content", "parameter_type": "string", "puppetclass_id": 3, "puppetclass_name": "motd", "required": false, "updated_at": "2017-02-07 11:56:55 UTC", # This line must be removed. "use_puppet_default": false, "validator_rule": null, "validator_type": "" } - ファイルの編集後に、以下のようになっていることを確認して、変更を保存します。
{ "avoid_duplicates": false, "default_value": "No Unauthorized Access Allowed", "description": "", "hidden_value": "*****", "hidden_value?": false, "id": 3, "merge_default": false, "merge_overrides": false, "override": true, "override_value_order": "fqdn\nhostgroup\nos\ndomain", "override_values_count": 0, "parameter": "content", "parameter_type": "string", "puppetclass_id": 3, "puppetclass_name": "motd", "required": false, "use_puppet_default": false, "validator_rule": null, "validator_type": "" } - 以下のように PUT コマンドを使用して、Satellite サーバーに変更を適用します。
$ curl -H "Accept:application/json,version=2" \ -H "Content-Type:application/json" \ -X PUT -u $user:$passwd \ -d @changed_file.json \ -k "https://satellite6.example.com/api/smart_class_parameters/3
4.1.4. エラータのホストまたはホストコレクションへの適用 リンクのコピーリンクがクリップボードにコピーされました!
$ curl -H "Accept:application/json,version=2" \
-H "Content-Type:application/json" -X PUT \
-u sat_username:sat_password -k \
-d json-formatted-data https://satellite6.example.com
host_collection="my-collection" が含まれます。これは、以下の例でホストコレクションに使用されます。
例4.4 ホストへのエラータの適用
$ curl -H "Accept:application/json,version=2" \
-H "Content-Type:application/json" -X PUT \
-u sat_username:sat_password -k \
-d "{\"organization_id\":1,\"included\":{\"search\":\"my-host\"},\"content_type\":\"errata\",\"content\":[\"RHBA-2016:1981\"]}" https://satellite6.example.com/api/v2/hosts/bulk/install_content
例4.5 ホストコレクションへのエラータの適用
host_collection="my-collection" を渡すために必要なエスケープレベルに注目してください。
$ curl -H "Accept:application/json,version=2" \
-H "Content-Type:application/json" -X PUT \
-u sat_username:sat_password -k \
-d "{\"organization_id\":1,\"included\":{\"search\":\"host_collection=\\\"my-collection\\\"\"},\"content_type\":\"errata\",\"content\":[\"RHBA-2016:1981\"]}" https://satellite6.example.com/api/v2/hosts/bulk/install_content
4.2. Ruby を使用した API の例 リンクのコピーリンクがクリップボードにコピーされました!
4.2.1. Ruby を使用したオブジェクトの作成 リンクのコピーリンクがクリップボードにコピーされました!
#!/usr/bin/ruby
require 'rest-client'
require 'json'
url = 'https://satellite6.example.com/api/v2/'
katello_url = "#{url}/katello/api/v2/"
$username = 'admin'
$password = 'changeme'
org_name = "MyOrg"
environments = [ "Development", "Testing", "Production" ]
# Performs a GET using the passed URL location
def get_json(location)
response = RestClient::Request.new(
:method => :get,
:url => location,
:user => $username,
:password => $password,
:headers => { :accept => :json,
:content_type => :json }
).execute
JSON.parse(response.to_str)
end
# Performs a POST and passes the data to the URL location
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
JSON.parse(response.to_str)
end
# Creates a hash with ids mapping to names for an array of recods
def id_name_map(records)
records.inject({}) do |map, record|
map.update(record['id'] => record['name'])
end
end
# Get list of existing organizations
orgs = get_json("#{katello_url}/organizations")
org_list = id_name_map(orgs['results'])
if !org_list.has_value?(org_name)
# If our organization is not found, create it
puts "Creating organization: \t#{org_name}"
org_id = post_json("#{katello_url}/organizations", JSON.generate({"name"=> org_name}))["id"]
else
# Our organization exists, so let's grab it
org_id = org_list.key(org_name)
puts "Organization \"#{org_name}\" exists"
end
# Get list of organization's lifecycle environments
envs = get_json("#{katello_url}/organizations/#{org_id}/environments")
env_list = id_name_map(envs['results'])
prior_env_id = env_list.key("Library")
# Exit the script if at least one life cycle environment already exists
environments.each do |e|
if env_list.has_value?(e)
puts "ERROR: One of the Environments is not unique to organization"
exit
end
end
# Create life cycle environments
environments.each do |environment|
puts "Creating environment: \t#{environment}"
prior_env_id = post_json("#{katello_url}/organizations/#{org_id}/environments", JSON.generate({"name" => environment, "organization_id" => org_id, "prior_id" => prior_env_id}))["id"]
end
4.2.2. Apipie バインディングの使用 リンクのコピーリンクがクリップボードにコピーされました!
#!/usr/bin/ruby
require 'apipie-bindings'
org_name = "MyOrg"
environments = [ "Development", "Testing", "Production" ]
# Create an instance of apipie bindings
@api = ApipieBindings::API.new({
:uri => 'https://satellite6.example.com/',
:username => 'admin',
:password => 'changeme',
:api_version => 2
})
# Performs an API call with default options
def call_api(resource_name, action_name, params = {})
http_headers = {}
apipie_options = { :skip_validation => true }
@api.resource(resource_name).call(action_name, params, http_headers, apipie_options)
end
# Creates a hash with IDs mapping to names for an array of records
def id_name_map(records)
records.inject({}) do |map, record|
map.update(record['id'] => record['name'])
end
end
# Get list of existing organizations
orgs = call_api(:organizations, :index)
org_list = id_name_map(orgs['results'])
if !org_list.has_value?(org_name)
# If our organization is not found, create it
puts "Creating organization: \t#{org_name}"
org_id = call_api(:organizations, :create, {'organization' => { :name => org_name }})['id']
else
# Our organization exists, so let's grab it
org_id = org_list.key(org_name)
puts "Organization \"#{org_name}\" exists"
end
# Get list of organization's life cycle environments
envs = call_api(:lifecycle_environments, :index, {'organization_id' => org_id})
env_list = id_name_map(envs['results'])
prior_env_id = env_list.key("Library")
# Exit the script if at least one life cycle environment already exists
environments.each do |e|
if env_list.has_value?(e)
puts "ERROR: One of the Environments is not unique to organization"
exit
end
end
# Create life cycle environments
environments.each do |environment|
puts "Creating environment: \t#{environment}"
prior_env_id = call_api(:lifecycle_environments, :create, {"name" => environment, "organization_id" => org_id, "prior_id" => prior_env_id })['id']
end
4.3. Python を使用した API の例 リンクのコピーリンクがクリップボードにコピーされました!
4.3.1. Python を使用したオブジェクトの作成 リンクのコピーリンクがクリップボードにコピーされました!
#!/usr/bin/python
import json
import sys
try:
import requests
except ImportError:
print "Please install the python-requests module."
sys.exit(-1)
# URL to your Satellite 6 server
URL = "https://satellite6.example.com"
# URL for the API to your deployed Satellite 6 server
SAT_API = "%s/katello/api/v2/" % URL
# Katello-specific API
KATELLO_API = "%s/katello/api/" % URL
POST_HEADERS = {'content-type': 'application/json'}
# Default credentials to login to Satellite 6
USERNAME = "admin"
PASSWORD = "changeme"
# Ignore SSL for now
SSL_VERIFY = False
# Name of the organization to be either created or used
ORG_NAME = "MyOrg"
# Name for life cycle environments to be either created or used
ENVIRONMENTS = ["Development", "Testing", "Production"]
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 main():
"""
Main routine that creates or re-uses an organization and
life cycle environments. If life cycle environments already
exist, exit out.
"""
# Check if our organization already exists
org = get_json(SAT_API + "organizations/" + ORG_NAME)
# If our organization is not found, create it
if org.get('error', None):
org_id = post_json(
SAT_API + "organizations/",
json.dumps({"name": ORG_NAME}))["id"]
print "Creating organization: \t" + ORG_NAME
else:
# Our organization exists, so let's grab it
org_id = org['id']
print "Organization '%s' exists." % ORG_NAME
# Now, let's fetch all available life cycle environments for this org...
envs = get_json(
SAT_API + "organizations/" + str(org_id) + "/environments/")
# ... and add them to a dictionary, with respective 'Prior' environment
prior_env_id = 0
env_list = {}
for env in envs['results']:
env_list[env['id']] = env['name']
prior_env_id = env['id'] if env['name'] == "Library" else prior_env_id
# Exit the script if at least one life cycle environment already exists
if all(environment in env_list.values() for environment in ENVIRONMENTS):
print "ERROR: One of the Environments is not unique to organization"
sys.exit(-1)
# Create life cycle environments
for environment in ENVIRONMENTS:
new_env_id = post_json(
SAT_API + "organizations/" + str(org_id) + "/environments/",
json.dumps(
{
"name": environment,
"organization_id": org_id,
"prior": prior_env_id}
))["id"]
print "Creating environment: \t" + environment
prior_env_id = new_env_id
if __name__ == "__main__":
main()
4.3.2. Python を使用したクエリーの実行 リンクのコピーリンクがクリップボードにコピーされました!
sat6api.py という名前の実行可能ファイルを作成し、以下の内容を追加します。
#!/usr/bin/python
import json
import sys
try:
import requests
except ImportError:
print "Please install the python-requests module."
sys.exit(-1)
SAT_API = 'https://satellite6.example.com/api/v2/'
USERNAME = "admin"
PASSWORD = "password"
SSL_VERIFY = False # Ignore SSL for now
def get_json(url):
# Performs a GET using the passed URL location
r = requests.get(url, auth=(USERNAME, PASSWORD), verify=SSL_VERIFY)
return r.json()
def get_results(url):
jsn = get_json(url)
if jsn.get('error'):
print "Error: " + jsn['error']['message']
else:
if jsn.get('results'):
return jsn['results']
elif 'results' not in jsn:
return jsn
else:
print "No results found"
return None
def display_all_results(url):
results = get_results(url)
if results:
print json.dumps(results, indent=4, sort_keys=True)
def display_info_for_hosts(url):
hosts = get_results(url)
if hosts:
for host in hosts:
print "ID: %-10d Name: %-30s IP: %-20s OS: %-30s" % (host['id'], host['name'], host['ip'], host['operatingsystem_name'])
def main():
host = 'satellite6.example.com'
print "Displaying all info for host %s ..." % host
display_all_results(SAT_API + 'hosts/' + host)
print "Displaying all facts for host %s ..." % host
display_all_results(SAT_API + 'hosts/%s/facts' % host)
host_pattern = 'example'
print "Displaying basic info for hosts matching pattern '%s'..." % host_pattern
display_info_for_hosts(SAT_API + 'hosts?search=' + host_pattern)
environment = 'production'
print "Displaying basic info for hosts in environment %s..." % environment
display_info_for_hosts(SAT_API + 'hosts?search=environment=' + environment)
model = 'RHEV Hypervisor'
print "Displaying basic info for hosts with model name %s..." % model
display_info_for_hosts(SAT_API + 'hosts?search=model="' + model + '"')
if __name__ == "__main__":
main()
4.4. 詳細検索の使用 リンクのコピーリンクがクリップボードにコピーされました!
os_description で、以下のように API クエリーで使用できます。
$ curl -s -k -u sat_username:sat_password https://satellite6.example.com/api/v2/hosts?search=os_description=\"RHEL+Server+6.6\" | python -m json.tool
{
...
"results": [
{
"name": "satellite6.example.com",
"operatingsystem_id": 1,
"operatingsystem_name": "RHEL Server 6.6",
...
}
],
"search": "os_description=\"RHEL Server 6.6\"",
}
4.5. ページネーション制御のある検索の使用 リンクのコピーリンクがクリップボードにコピーされました!
per_page および page ページネーションパラメーターを使用して、API 検索クエリーによって返される検索結果を制限できます。per_page パラメーターは、ページごとの量を指定し、page パラメーターは per_page パラメーターの計算に合わせて、どのページを返すかを指定します。
page パラメーターを指定すると per_page のデフォルト値は 20 が適用されます。
例4.6 コンテンツビューの表示
$ curl -X GET --user sat_username:sat_password \
"https://satellite6.example.com/katello/api/content_views?per_page=10&page=3"
例4.7 アクティベーションキーの表示
$ curl -X GET --user sat_username:sat_password \
"https://satellite6.example.com/katello/api/activation_keys?organization_id=1&per_page=30&page=2"
例4.8 複数ページを返す設定
$ for i in `seq 1 3`; do curl -X GET --user sat_username:sat_password \
"https://satellite6.example.com/katello/api/content_views?per_page=5&page=$i"; done
4.6. ライフサイクル環境との作業 リンクのコピーリンクがクリップボードにコピーされました!
_id パラメーターを使用してください。
/katello/api/environments および /katello/api/organizations/:organization_id/environments が含まれます。
1 について一覧表示できます。
$ curl -H "Accept:application/json,version=2" \
-H "Content-Type:application/json" -X GET \
-u sat_user:sat_password -k \
https://satellite6.example.com/katello/api/organizations/1/environments | python -m json.tool
output omitted
"description": null,
"id": 1,
"label": "Library",
"library": true,
"name": "Library",
"organization": {
"id": 1,
"label": "Default_Organization",
"name": "Default Organization"
},
"permissions": {
"destroy_lifecycle_environments": false,
"edit_lifecycle_environments": true,
"promote_or_remove_content_views_to_environments": true,
"view_lifecycle_environments": true
},
"prior": null,
"successor": null,
output truncated
1 のデフォルトのライブラリー環境が、ライフサイクル環境を作成するための開始点として使用されます。
手順4.3 ライフサイクル環境のリンク作成
- 開始点として使用する既存のライフサイクル環境を選択します。その ID を使用して環境を一覧表示します。今回の例では、ID が
1の環境を使用します。$ curl -X GET -s -k -u sat_user:sat_password \ https://satellite6.example.com/katello/api/environments/1 | python -m json.tool output omitted "id": 1, "label": "Library", output omitted "prior": null, "successor": null, output truncated priorオプションを1に設定して、新しいライフサイクル環境を作成します。{"organization_id":1,"label":"api-dev","name":"API Development","prior":1}の内容で JSON ファイルを作成します(例:life-cycle.json)。- 以下のようなコマンドを入力します。
$ curl -H "Accept:application/json,version=2" \ -H "Content-Type:application/json" -X POST \ -u sat_user:sat_password -k \ -d @life-cycle.json \ https://satellite6.example.com/katello/api/environments \ | python -m json.tool output omitted "description": null, "id": 2, "label": "api-dev", "library": false, "name": "API Development", "organization": { "id": 1, "label": "Default_Organization", "name": "Default Organization" }, "permissions": { "destroy_lifecycle_environments": true, "edit_lifecycle_environments": true, "promote_or_remove_content_views_to_environments": true, "view_lifecycle_environments": true }, "prior": { "id": 1, "name": "Library" }, output truncated
以下のコマンドの出力では、ライフサイクル環境の ID が2で、その 1 つ前のライフサイクル環境は1であると分かります。これは、ライフサイクル環境1および2がリンクされていることを示しています。この環境の後継を作成する際には、ライフサイクル環境 ID2が使用されます。priorオプションを2に設定して、別のライフサイクル環境を作成します。- 以前作成した
life-cycle.jsonを編集して、ラベル、名前、および以前の値を更新します:{"organization_id":1,"label":"api-qa","name":"API QA","prior":2} - 以下のようなコマンドを入力します。
$ curl -H "Accept:application/json,version=2" \ -H "Content-Type:application/json" -X POST \ -u sat_user:sat_password -k \ -d @life-cycle.json \ https://satellite6.example.com/katello/api/environments \ | python -m json.tool output omitted "description": null, "id": 3, "label": "api-qa", "library": false, "name": "API QA", "organization": { "id": 1, "label": "Default_Organization", "name": "Default Organization" }, "permissions": { "destroy_lifecycle_environments": true, "edit_lifecycle_environments": true, "promote_or_remove_content_views_to_environments": true, "view_lifecycle_environments": true }, "prior": { "id": 2, "name": "API Development" }, "successor": null, output truncated
以下のコマンドの出力では、ライフサイクル環境の ID が3で、その 1 つ前のライフサイクル環境は2であると分かります。これは、ライフサイクル環境2と3がリンクされていることを示しています。
ライフサイクル環境の更新
$ curl -H "Accept:application/json,version=2" \
-H "Content-Type:application/json" -X POST \
-u sat_user:sat_password -k \
-d '{"description":"Quality Acceptance Testing"}' \
https://satellite6.example.com/katello/api/environments/3 \
| python -m json.tool
output omitted
"description": "Quality Acceptance Testing",
"id": 3,
"label": "api-qa",
"library": false,
"name": "API QA",
"organization": {
"id": 1,
"label": "Default_Organization",
"name": "Default Organization"
},
"permissions": {
"destroy_lifecycle_environments": true,
"edit_lifecycle_environments": true,
"promote_or_remove_content_views_to_environments": true,
"view_lifecycle_environments": true
},
"prior": {
"id": 2,
"name": "API Development"
},
output truncated
ライフサイクル環境の削除
curl -X DELETE -s -k -u sat_user:sat_password https://satellite6.example.com/katello/api/environments/:id