第4章 Red Hat Satellite API のスタートガイド


この章では、Red Hat Satellite API を使用して各種タスクを実行する方法をさまざまな例を挙げて説明します。以下の例では、ポート 443 で HTTPS を使用する Satellite Server に重点を置いています。Satellite Capsule から API にアクセスすることもできますが、ポート 8443 を使用する必要があります。そうしないと、API 呼び出しが失敗します。
スクリプト自体で、異なるポートの要件に対応することができます。たとえば、Ruby では Satellite および Capsule の URL を以下のように指定することができます。
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/'
ホストが Satellite Server または Capsule Server にサブスクライブしている場合は、/etc/rhsm/rhsm.conf ファイルの [server] セクションの エントリーをもとに、API へのアクセスに必要な、正しいポートを判断できます。これらの値を使用してスクリプトを完全に自動化し、使用するポートを検証する必要性をなくします。

4.1. curl を使用した API の例

本セクションでは、curl を使用して Satellite API を使用してさまざまなタスクを実行する方法を説明します。

4.1.1. シンプルなクエリーの実行

以下の例では、curl を使用して Satellite デプロイメントに関する情報を検索する方法を説明します。これらの例には、実際のコマンドとサンプル出力、およびユーザー名とパスワードの例の値が含まれます。デプロイメントごとに、異なる結果が得られることが想定されます。これらの例では、python -m json.tool コマンドを使用して出力をフォーマットしています。
注記
Red Hat Satellite は HTTPS と、デフォルトではホストの識別用に証明書を使用する必要があります。「SSL 認証の使用」 の記載どおりに Satellite Server の証明書を追加していない場合には、-k (セキュアでない)オプションを使用して証明書チェックを省略することができます。
ユーザー認証の場合は、form -u username:password を使用するか、パスワードを含めない場合はコマンドにより入力が求められます。Red Hat は、コマンドの一部としてパスワードを含めないことを推奨します。パスワードはシェル履歴の一部になり、セキュリティーリスクが生じる可能性があります。この例には、簡素化の目的でのみパスワードが含まれています。
curl-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. リソースの作成および変更

Satellite API を使用して、Satellite Server のリソースを操作できます。これらの API 呼び出しでは、クエリーを実行する単純なユーザー名、パスワード、および URI 以外にさまざまなパラメーターを渡す必要があります。たとえば、Satellite Server にコンテンツをアップロードするか、Satellite リソースを変更するには、要求の作成時にヘッダーに追加情報を追加する必要があります。
以下の例のように、API のバージョンは、ヘッダーで、または URL の一部として指定できます。たとえば、https://satellite6.example.com/api/v2/architectures は要求ヘッダーで Accept:version=2 を使用するのと同じです。URL の仕様が優先されます。
以下は、POST 要求の基本構文です。
$ 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
  }
Satellite Server で hammer を使用して、結果を検証することもできます。
$ 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 へのコンテンツのアップロード

このセクションでは、Satellite 6 API で curl を使用して、Satellite Server に大容量のファイルをアップロードし、インポートする方法を説明します。このプロセスでは、4 つの手順が含まれます。
  1. アップロード要求を作成します。
  2. コンテンツをアップロードします。
  3. コンテンツをインポートします。
  4. アップロード要求を削除します。
アップロード可能な最大ファイルサイズは約 30 MB です。より大きなコンテンツをアップロードするには、例4.3「30 MB よりも大きいコンテンツのアップロード」 を参照してください。

手順4.1 Satellite Server へのコンテンツのアップロード

  1. アップロード要求を作成します。デプロイメントに合わせてサンプルパラメーターを変更するようにしてください。
    $ 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/"}
  2. コンテンツをアップロードします。データのアップロード時には、正しい 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
  3. 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
  4. コンテンツのアップロードおよびインポートが正常に完了したら、アップロード要求を削除することができます。これにより、アップロード中に使用された一時的なディスク領域を解放できます。
    $ 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 よりも大きいコンテンツのアップロード

以下の例では、大容量のファイルをチャンクに分割して、アップロード要求の作成、個別ファイルのアップロード、Satellite へのインポートを行ってから、アップロード要求を削除する方法を説明します。この例は、サンプルのコンテンツ、ホスト名、ユーザー名、ファイル名を使用している点に注意してください。
  1. サンプルモジュールをダウンロードします。
    $ 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.gz
    
    50,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
  2. 新しいアップロード要求を作成します(これは 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/"}
  3. ステップ 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
  4. 完全なアップロードをリポジトリーにインポートします。
    $ 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
  5. アップロード要求を削除します。
    $ 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
  6. 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. スマートクラスのオーバーライド

API を使用してスマートパラメーターを検索し、値を指定してクラスのスマートパラメーターを上書きすることができます。変更可能な属性の完全リストは、https://satellite6.example.com/apidoc/v2/smart_class_parameters/update.html にある組み込み API リファレンスを参照してください。
たとえば、スマートクラスパラメーターすべてを一覧表示するには、API ルートは GET /api/smart_class_parameters のようになります。curl を使用すると、コマンドは以下のようになります。
$ curl -X GET -s -k -u sat_username:sat_password \
https://satellite6.example.com/api/smart_class_parameters
5 など、Puppet クラス ID が分かる場合には、以下のように範囲を絞り込むことができます。
$ curl -X GET -s -k -u sat_username:sat_password https://satellite6.example.com/api/puppetclasses/5/smart_class_parameters
どちらの呼び出しも検索パラメーターに対応します。検索可能なフィールドの全一覧は、Web UI の 検索入力ボックス に表示されます。Configure Smart variables に移動し、検索クエリーボックスをクリックしてフィールドのリストを表示します。
特に検索パラメーターで便利なのは、puppetclass_namekey の 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'
標準のスコープ指定の検索構文はサポートされています。
パラメーターの ID が見つかったら、現在のオーバーライド値を含む完全な詳細の一覧表示に進むことができます。たとえば、ID が 63 の場合には、API ルートは 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
これで、PUT 呼び出しでパラメーターの値をオーバーライドすることができます。
$ 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
パラメーターを手動で作成または削除する方法がないことに注意してください。ユーザーは属性のみを変更できます。パラメーターは、プロキシーからクラスをインポートすることでのみ作成および削除されます。
オーバーライドが有効な場合には、カスタムの Override Matcher を追加できます。
$ 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
API 呼び出しのすべてのパラメーターの詳細については、https://satellite6.example.com/apidoc/v2/override_values.html を参照してください。
オーバーライド値を削除するには、以下のようなコマンドを使用します。
$ 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. 外部ファイルを使用したスマートクラスパラメーターの変更

外部ファイルを使用すると、JSON データでの作業が簡素化されます。構文が強調されるエディターを使用するので、間違いを回避し、特定しやすくなります。

手順4.2 外部ファイルを使用したスマートクラスパラメーターの変更

以下の例では、MOTD Puppet マニフェストを使用します。
  1. 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 と混同しないようにしてください。
  2. パラメーター 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
  3. 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": ""
    }
  4. ファイルの編集後に、以下のようになっていることを確認して、変更を保存します。
    {
    "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": ""
    }
  5. 以下のように 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. エラータのホストまたはホストコレクションへの適用

PUT コマンドで curl を使用して、エラータをホスト、ホストグループ、またはホストコレクションに適用することができます。以下は、PUT 要求の基本的な構文です。
$ 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
同梱の API ドキュメント(https://satellite6.example.com/apidoc/v2.html)を参照して、エラータ適用に使用する URL を検索します。Satellite Web UI で、検索クエリーの形式を確認できます。Hosts Host Collections に移動し、ホストコレクションを選択します。コレクションアクション エラータのインストール に移動して、検索クエリーボックスの内容を確認します。たとえば、my-collection と呼ばれるホストコレクションの場合は、検索ボックスに host_collection="my-collection" が含まれます。これは、以下の例でホストコレクションに使用されます。

例4.4 ホストへのエラータの適用

以下の例では、一括アクションの API URL /katello/api/hosts/bulk/install_content を使用して、単純な検索に必要な形式を示しています。
$ 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 ホストコレクションへのエラータの適用

以下の例では、Satellite Web UI に表示されているように、検索文字列 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 の例

以下の例では、Ruby を使用してさまざまなタスクを実行して Satellite API と通信する方法について説明します。
重要
以下は、スクリプトおよびコマンドの例です。以下のスクリプトを慎重にレビューしてから使用するようにしてください。変数、ユーザー名、パスワード、その他の情報は、お使いのデプロイメントに適した値に置き換えてください。

4.2.1. Ruby を使用したオブジェクトの作成

以下のスクリプトは Red Hat Satellite 6 API と接続して新規組織を作成し、続いて新規組織に 3 つの環境を作成します。組織がすでに存在する場合には、このスクリプトはその組織を使用します。組織内に環境が 1 つでも存在する場合は、スクリプトによりエラーが送出されて、スクリプトは終了します。
#!/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 バインディングの使用

Apipie バインディングは、apipie で記述された API の Ruby バインディングであり、Satellite から API 定義を取得してキャッシュし、オンデマンドで API 呼び出しを生成します。apipie バインディングを使用すると、Ruby API クエリーを簡素化できます。APIpie は通常、happy がない rhyme まで、"appy-pie" です。
以下の例では、新しい組織を作成してから、新しい組織に 3 つの環境を作成します。組織がすでに存在する場合には、このスクリプトはその組織を使用します。組織内に環境が 1 つでも存在する場合は、スクリプトによりエラーが送出されて、スクリプトは終了します。
#!/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 の例

以下の例では、Python を使用してさまざまなタスクを実行して Satellite API と通信する方法について説明します。
重要
以下は、スクリプトおよびコマンドの例です。以下のスクリプトを慎重にレビューしてから使用するようにしてください。変数、ユーザー名、パスワード、その他の情報は、お使いのデプロイメントに適した値に置き換えてください。
以下のスクリプトは、REST API との対話に SSL 検証を使用しません。ここで紹介しているスクリプトはデモのみを目的としています。

4.3.1. Python を使用したオブジェクトの作成

以下のスクリプトは Red Hat Satellite 6 API と接続して新規組織を作成し、続いて新規組織に 3 つの環境を作成します。組織がすでに存在する場合には、このスクリプトはその組織を使用します。組織内に環境が 1 つでも存在する場合は、スクリプトによりエラーが送出されて、スクリプトは終了します。
#!/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 を使用したクエリーの実行

Python スクリプトを作成および実行して、「curl を使用した API の例」 に記載されているものと同じ結果を得ることができます。以下のスクリプト例では、このアプローチを説明します。まず、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()
その後、コマンドラインから ./sat6api.py を実行して結果を表示できます。

4.4. 詳細検索の使用

Web UI を使用して、クエリーの作成に使用できるその他の検索用語を判断できます。Satellite 6 は、このタスクを簡単にするために、スコープ指定の検索とタブ補完をサポートします。
たとえば、オペレーティングシステム別にホストを検索するには、Hosts All Hosts に移動し、Search テキストボックスをクリックして検索用語のリストを表示します。オペレーティングシステムの検索用語の 1 つが 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 パラメーターの計算に合わせて、どのページを返すかを指定します。
ページネーションパラメーターを指定しない場合に、返す項目数のデフォルト値を 1000 に設定しますが、page パラメーターを指定すると per_page のデフォルト値は 20 が適用されます。

例4.6 コンテンツビューの表示

以下の例では、返された結果の 3 ページ目の 10 件分をリストするコンテンツビューが表示されます。
$ curl -X GET --user sat_username:sat_password \
"https://satellite6.example.com/katello/api/content_views?per_page=10&page=3"

例4.7 アクティベーションキーの表示

以下の例では、ID が 1 の組織のアクティベーションキー 30 個を 1 ページにリストする検索の 2 ページ目を表示します。
$ 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 複数ページを返す設定

以下の例では、ページごとに 5 件ずつ表示するコンテンツビュー 3 ページ分の 1 ページを返します。
$ 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. ライフサイクル環境との作業

サーバー 『管理ガイド』 の ライフサイクル 環境 セクション で説明されているように、アプリケーションライフサイクルは ライフサイクル 環境 に分割され、アプリケーションライフサイクルの各ステージを表します。ライフサイクル環境はリンクし 環境パス を形成します。API を使用してリンクされたライフサイクル環境を作成するには、prio _id パラメーターを使用してください。
ライフサイクル環境に関する API リファレンスは https://satellite6.example.com/apidoc/v2/lifecycle_environments.html にあります。API ルートには /katello/api/environments および /katello/api/organizations/:organization_id/environments が含まれます。
以下のように、Satellite 上の現在のライフサイクル環境をすべてデフォルトの組織 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
新規インストールした Satellite の出力では、以下のようなセクションが表示されるはずです。
      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
以下の手順では、ID が 1 のデフォルトのライブラリー環境が、ライフサイクル環境を作成するための開始点として使用されます。

手順4.3 ライフサイクル環境のリンク作成

  1. 開始点として使用する既存のライフサイクル環境を選択します。その 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
  2. prior オプションを 1 に設定して、新しいライフサイクル環境を作成します。
    1. {"organization_id":1,"label":"api-dev","name":"API Development","prior":1}の内容で JSON ファイルを作成します(例: life-cycle.json )。
    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": 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 がリンクされていることを示しています。この環境の後継を作成する際には、ライフサイクル環境 ID 2 が使用されます。
  3. prior オプションを 2 に設定して、別のライフサイクル環境を作成します。
    1. 以前作成した life-cycle.json を編集して、ラベル名前、および以前の値を更新します: {"organization_id":1,"label":"api-qa","name":"API QA"," prior ":2}
    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 であると分かります。これは、ライフサイクル環境 23 がリンクされていることを示しています。

ライフサイクル環境の更新

ライフサイクル環境は PUT コマンドを使用して更新できます。以下に例を示します。
$ 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
Red Hat logoGithubRedditYoutubeTwitter

詳細情報

試用、購入および販売

コミュニティー

Red Hat ドキュメントについて

Red Hat をお使いのお客様が、信頼できるコンテンツが含まれている製品やサービスを活用することで、イノベーションを行い、目標を達成できるようにします。

多様性を受け入れるオープンソースの強化

Red Hat では、コード、ドキュメント、Web プロパティーにおける配慮に欠ける用語の置き換えに取り組んでいます。このような変更は、段階的に実施される予定です。詳細情報: Red Hat ブログ.

会社概要

Red Hat は、企業がコアとなるデータセンターからネットワークエッジに至るまで、各種プラットフォームや環境全体で作業を簡素化できるように、強化されたソリューションを提供しています。

© 2024 Red Hat, Inc.