使用 Satellite REST API


Red Hat Satellite 6.16

使用 Satellite REST API 开发自定义应用程序或集成

Red Hat Satellite Documentation Team

摘要

Red Hat Satellite Representational State Transfer (REST) API 指南解释了 REST API 背后的概念,并提供各种请求的示例用法。这为管理员和开发人员提供了编写自定义脚本并将 Red Hat Satellite 与第三方应用程序集成的基础。

对红帽文档提供反馈

我们感谢您对我们文档的反馈。让我们了解如何改进它。

使用 Red Hat Jira 中的 Create Issue 表单提供您的反馈。JIRA 问题是在 Red Hat Satellite Jira 项目中创建的,您可以在其中跟踪其进度。

先决条件

流程

  1. 单击以下链接: 创建问题。如果 Jira 显示登录错误,则登录并在您重定向到表单后继续。
  2. 完成 SummaryDescription 字段。在 Description 字段中,包含文档 URL、章节号以及问题的详细描述。不要修改表单中的任何其他字段。
  3. Create

第 1 章 Satellite API 简介

Red Hat Satellite 提供了一个 Representational State Transfer (REST) API。API 为软件开发人员和系统管理员提供在标准 Web 界面之外控制其 Red Hat Satellite 环境。REST API 对于旨在将 Red Hat Satellite 功能与通过 HTTP 访问 API 的自定义脚本或外部应用程序集成在一起的开发人员和管理员很有用。

1.1. Satellite API 概述

使用 REST API 的优点包括:

  • 广泛的客户端支持 - 任何支持 HTTP 协议的编程语言、框架或系统都可以使用 API。
  • 自我说明 - 客户端应用程序需要最少了解 Red Hat Satellite 基础架构,因为用户在运行时发现许多详细信息。
  • 基于资源的模型 - 基于资源的 REST 模型提供了管理虚拟化平台的自然方法。

您可以使用 REST API 来执行以下任务:

  • 与企业 IT 系统集成。
  • 与第三方应用程序集成.
  • 执行自动维护或错误检查任务。
  • 使用脚本自动执行重复性任务。

1.2. 与 Hammer CLI 相比的 Satellite API

对于许多任务,您可以使用 Hammer 和 Satellite API。您可以使用 Hammer 作为 Satellite API 的人员友好接口。例如,要在脚本中应用 API 调用前测试对 API 调用的响应,请使用 use-debug 选项来检查 Hammer 问题的 API 调用: hammer --debug 组织列表。相反,使用 API 命令的脚本直接与 Satellite API 通信。

如需更多信息 ,请参阅使用 Hammer CLI 工具

第 2 章 访问内置 API 参考

您可以访问 Satellite 服务器上的完整 API 参考。

流程

  • 在您的浏览器中,访问以下 URL:

    https://satellite.example.com/apidoc/
    Copy to Clipboard Toggle word wrap

    satellite.example.com 替换为您的 Satellite 服务器的 FQDN。

第 3 章 API 语法

您可以查看 API 请求和 JSON 响应的基本语法。

重要

虽然 Satellite 6 API 版本 1 和 2 可用,但红帽只支持版本 2。

3.1. API 请求组成

内置 API 引用显示 API 路由或路径,前面带有 HTTP 方法:

HTTP_METHOD API_ROUTE
Copy to Clipboard Toggle word wrap

要使用 API,请使用 curl 命令语法和参考文档中的 API 路由来构造命令:

$ curl --request HTTP_METHOD \         
1

--insecure \                           
2

--user My_User_Name:My_Password \      
3

--data @input_file.json \              
4

--header "Accept:application/json" \       
5

--header "Content-Type:application/json" \ 
6

--output output_file                    
7

API_ROUTE \                             
8

| python3 -m json.tool                  
9
Copy to Clipboard Toggle word wrap
1
要将 curl 用于 API 调用,请使用 the- request 选项指定 HTTP 方法。例如,-- request POST
2
添加 -insecure 选项以跳过 SSL 对等证书验证检查。红帽建议您配置 SSL 身份验证并使用安全调用。如需更多信息,请参阅 第 4.1 节 “SSL 身份验证概述”
3
通过 -user 选项提供 Satellite 用户凭据。
4
对于 POSTPUT 请求,请使用-- data 选项传递 JSON 格式的数据。如需更多信息,请参阅 第 5.1.1 节 “将 JSON 数据传递给 API 请求”
5 6
当使用 the-data 选项传递 JSON 数据时,您必须使用-- header 选项指定以下标头: 如需更多信息,请参阅 第 5.1.1 节 “将 JSON 数据传递给 API 请求”
7
从 Satellite 服务器下载内容时,请使用-- output 选项指定输出文件
8
使用以下格式的 API 路由: https://satellite.example.com/katello/api/activation_keys。在 Satellite 6 中,API 的版本 2 是默认值。因此,在 API 调用的 URL 中使用 v2 不需要。
9
将输出重定向到 Python json.tool 模块,以便更轻松地读取输出。

3.1.1. 使用 GET HTTP 方法

使用 GET HTTP 方法从 API 中获取有关现有条目或资源的数据。

Example

这个示例请求 Satellite 主机的数量:

请求示例:

$ curl --request GET --user My_User_Name:My_Password \
https://satellite.example.com/api/hosts | python3 -m json.tool
Copy to Clipboard Toggle word wrap

响应示例:

{
  "total": 2,
  "subtotal": 2,
  "page": 1,
  "per_page": 20,
  "search": null,
  "sort": {
    "by": null,
    "order": null
  },
  "results":
output truncated
Copy to Clipboard Toggle word wrap

API 的响应表示总计有两个结果,这是结果的第一个页面,每个页面的最大结果设置为 20。如需更多信息,请参阅 第 3.2 节 “JSON 响应格式”

3.1.2. 使用 POST HTTP 方法

使用 POST HTTP 动词将数据提交到 API,以创建条目或资源。您必须使用 JSON 格式提交数据。如需更多信息,请参阅 第 5.1.1 节 “将 JSON 数据传递给 API 请求”

创建激活码的示例

  1. 创建包含以下内容的测试文件,如 activation-key.json

    {"organization_id":1, "name":"TestKey", "description":"Just for testing"}
    Copy to Clipboard Toggle word wrap
  2. 通过在 activation-key.json 文件中应用数据来创建激活码:

    请求示例:

    $ curl --header "Accept:application/json" \
    --header "Content-Type:application/json" --request POST \
    --user My_User_Name:My_Password \
    --data @activation-key.json \
    https://satellite.example.com/katello/api/activation_keys \
    | python3 -m json.tool
    Copy to Clipboard Toggle word wrap

    响应示例:

    {
        "id": 2,
        "name": "TestKey",
        "description": "Just for testing",
        "unlimited_hosts": true,
        "auto_attach": true,
        "content_view_id": null,
        "environment_id": null,
        "usage_count": 0,
        "user_id": 3,
        "max_hosts": null,
        "release_version": null,
        "service_level": null,
        "content_overrides": [
    
        ],
        "organization": {
            "name": "Default Organization",
            "label": "Default_Organization",
            "id": 1
        },
        "created_at": "2017-02-16 12:37:47 UTC",
        "updated_at": "2017-02-16 12:37:48 UTC",
        "content_view": null,
        "environment": null,
        "products": null,
        "host_collections": [
    
        ],
        "permissions": {
            "view_activation_keys": true,
            "edit_activation_keys": true,
            "destroy_activation_keys": true
        }
    }
    Copy to Clipboard Toggle word wrap
  3. 验证新激活密钥是否存在。在 Satellite Web UI 中,进入到 Content > Lifecycle > Activation Keys 来查看您的激活码。

3.1.3. 使用 PUT HTTP 方法

使用 PUT HTTP 方法更改现有值或附加到现有资源。您必须使用 JSON 格式提交数据。更多信息请参阅 第 5.1.1 节 “将 JSON 数据传递给 API 请求”

示例

本例更新在上例中创建的 TestKey 激活码。

  1. 编辑之前创建的 activation-key.json 文件,如下所示:

    {"organization_id":1, "name":"TestKey", "description":"Just for testing","max_hosts":"10" }
    Copy to Clipboard Toggle word wrap
  2. 在 JSON 文件中应用更改:

    请求示例:

    $ curl  --request PUT \
    --header "Accept:application/json" \
    --header "Content-Type:application/json" \
    --user My_User_Name:My_Password \
    --data @activation-key.json \
    https://satellite.example.com/katello/api/activation_keys/2 \
    | python3 -m json.tool
    Copy to Clipboard Toggle word wrap

    响应示例:

    {
        "id": 2,
        "name": "TestKey",
        "description": "Just for testing",
        "unlimited_hosts": false,
        "auto_attach": true,
        "content_view_id": null,
        "environment_id": null,
        "usage_count": 0,
        "user_id": 3,
        "max_hosts": 10,
        "release_version": null,
        "service_level": null,
        "content_overrides": [
    
        ],
        "organization": {
            "name": "Default Organization",
            "label": "Default_Organization",
            "id": 1
        },
        "created_at": "2017-02-16 12:37:47 UTC",
        "updated_at": "2017-02-16 12:46:17 UTC",
        "content_view": null,
        "environment": null,
        "products": null,
        "host_collections": [
    
        ],
        "permissions": {
            "view_activation_keys": true,
            "edit_activation_keys": true,
            "destroy_activation_keys": true
        }
    }
    Copy to Clipboard Toggle word wrap
  3. 在 Satellite Web UI 中,导航到 Content > Lifecycle > Activation Keys 来验证更改。

3.1.4. 使用 DELETE HTTP 方法

要删除资源,请使用 DELETE 方法以及包含您要删除的资源 ID 的 API 路由。

Example

这个示例删除 ID 为 2 的 TestKey 激活码:

请求示例:

$ curl  \
--header "Accept:application/json" \
--header "Content-Type:application/json" \
--request DELETE \
--user My_User_Name:My_Password \
https://satellite.example.com/katello/api/activation_keys/2 \
| python3 -m json.tool
Copy to Clipboard Toggle word wrap

响应示例:

output omitted
    "started_at": "2017-02-16 12:58:17 UTC",
    "ended_at": "2017-02-16 12:58:18 UTC",
    "state": "stopped",
    "result": "success",
    "progress": 1.0,
    "input": {
        "activation_key": {
            "id": 2,
            "name": "TestKey"
output truncated
Copy to Clipboard Toggle word wrap

3.2. JSON 响应格式

以 JSON 格式调用 API 返回结果。API 调用返回单一选项响应或响应集合的结果。

单个对象的 JSON 响应格式

您可以使用单对象 JSON 响应来处理单个对象。对单个对象的 API 请求需要对象的唯一标识符 :id

这是 Satellite 域的单对象请求格式的示例,ID 为 23:

请求示例:

$ curl --request GET --user My_User_Name:My_Password \
https://satellite.example.com/api/domains/23 | python3 -m json.tool
Copy to Clipboard Toggle word wrap

响应示例:

{
    "id": 23,
    "name": "qa.lab.example.com",
    "fullname": "QA",
    "dns_id": 10,
    "created_at": "2024-08-13T09:02:31Z",
    "updated_at": "2024-08-13T09:02:31Z"
}
Copy to Clipboard Toggle word wrap

集合的 JSON 响应格式

集合是对象列表,如主机和域。集合 JSON 响应的格式由 metadata 字段和 results 部分组成。

这是 Satellite 域列表集合请求的格式示例:

请求示例:

$ curl --request GET --user My_User_Name:My_Password \
https://satellite.example.com/api/domains | python3 -m json.tool
Copy to Clipboard Toggle word wrap

响应示例:

{
    "total": 3,
    "subtotal": 3,
    "page": 1,
    "per_page": 20,
    "search": null,
    "sort": {
        "by": null,
        "order": null
    },
    "results": [
        {
            "id": 23,
            "name": "qa.lab.example.com",
            "fullname": "QA",
            "dns_id": 10,
            "created_at": "2024-08-13T09:02:31Z",
            "updated_at": "2024-08-13T09:02:31Z"
        },
        {
            "id": 25,
            "name": "dev.lab.example.com",
            "fullname": "DEVEL",
            "dns_id": 8,
            "created_at": "2024-08-13T08:32:48Z",
            "updated_at": "2024-08-14T07:04:03Z"
        },
        {
            "id": 32,
            "name": "hr.lab.example.com",
            "fullname": "HR",
            "dns_id": 8,
            "created_at": "2024-08-16T08:32:48Z",
            "updated_at": "2024-08-16T07:04:03Z"
        }
    ]
}
Copy to Clipboard Toggle word wrap

JSON 响应元数据

API 响应使用以下元数据字段:

  • total - 没有搜索参数的对象总数。
  • Subtotal - 使用给定搜索参数返回的对象数量。如果没有搜索,则 subtotal 等于 total。
  • page - 页面号。
  • per_page - 每个页面返回的最大对象数。
  • Limit - 在集合响应中返回指定数量的对象。
  • offset - 返回集合前跳过的对象数量。
  • search - 基于 scoped_scoped 语法的搜索字符串。
  • 排序

    • 通过 API 对集合进行排序的字段指定。
    • 顺序 -排序顺序,可以是升序的 ASC 或 DESC (降序)。
  • results - 对象集合。

3.3. 与 API 参考相关的 API 错误消息

API 使用 RAILs 格式来指示错误:

Nested_Resource.Attribute_Name
Copy to Clipboard Toggle word wrap

这会转换为 API 引用中使用的以下格式:

Resource[Nested_Resource_attributes][Attribute_Name_id]
Copy to Clipboard Toggle word wrap

第 4 章 API 调用身份验证

与 Satellite API 交互需要与 Satellite 服务器 CA 证书进行 SSL 身份验证,并使用有效的 Satellite 用户凭据进行身份验证。您可以使用以下身份验证方法。

4.1. SSL 身份验证概述

Red Hat Satellite 使用 HTTPS,在与 Satellite 服务器通信时提供一定程度的加密和身份验证。Satellite 6.16 不支持非 SSL 通信。

默认情况下,Satellite 服务器使用自签名证书。此证书同时充当服务器证书,以验证加密密钥和证书颁发机构(CA)以信任 Satellite 服务器的身份。

您可以将 Satellite 服务器配置为使用自定义 SSL 证书。如需更多信息,请参阅在连接的网络环境中安装 Satellite 服务器 中的 使用自定义 SSL 证书配置 Satellite 服务器。有关断开连接的 Satellite 服务器的更多信息,请参阅 在断开连接的网络环境中安装 Satellite 服务器 中的 使用自定义 SSL 证书配置 Satellite 服务器

4.1.1. 配置 SSL 身份验证

为向 Satellite 服务器的 API 请求配置 SSL 身份验证。

流程

  1. 使用以下选项之一从 Satellite 服务器获取证书:

    • 如果您计划从远程服务器调用 API,请下载 CA 证书:

      # curl -o /etc/pki/ca-trust/source/anchors/satellite.example.com-katello-server-ca.crt \
      http://satellite.example.com/pub/katello-server-ca.crt
      Copy to Clipboard Toggle word wrap
    • 如果您计划直接在 Satellite 服务器上调用 API,请将证书复制到 /etc/pki/ca-trust/source/anchors 目录中:

      # cp /var/www/html/pub/katello-server-ca.crt \
      /etc/pki/ca-trust/source/anchors/satellite.example.com-katello-server-ca.crt
      Copy to Clipboard Toggle word wrap
  2. 将证书添加到可信 CA 列表中:

    $ update-ca-trust extract
    Copy to Clipboard Toggle word wrap

验证

  • 输入没有 a- cacert 选项的 API 请求来验证您的客户端是否信任 Satellite SSL 证书:

    $ curl --request GET \
    --user My_User_Name:My_Password \
    https://satellite.example.com/api/v2/hosts
    Copy to Clipboard Toggle word wrap

4.2. HTTP 身份验证概述

对 Satellite API 的所有请求都需要有效的 Satellite 用户名和密码。API 使用基本 HTTP 身份验证对这些凭证进行编码,并添加到 Authorization 标头中。有关基本身份验证的更多信息,请参阅 RFC 2617 HTTP 身份验证: Basic 和 Digest Access 身份验证。如果请求没有包括适当的 Authorization 标头,API 会返回 401 Authorization Required 错误。

重要

基本身份验证涉及潜在的敏感信息,例如,它将密码以纯文本形式发送。REST API 需要 HTTPS 进行纯文本请求的传输级别加密。

有些 base64 库将编码的凭据分成多行,并使用换行符终止每行。这会使标头无效,并导致请求出现故障。Authorization 标头需要编码的凭证位于标头中的一行中。

4.3. 令牌身份验证概述

Red Hat Satellite 支持可用于验证 API 请求的个人访问令牌,而不使用您的密码。您可以为个人访问令牌设置过期日期。如果您决定它应在过期日期前过期,可以撤销它。

4.3.1. 创建一个个人访问令牌

使用这个流程创建个人访问令牌。

流程

  1. 在 Satellite Web UI 中,进入到 Administer > Users
  2. 选择您要为其创建个人访问令牌的用户。
  3. Personal Access Tokens 选项卡中,点 Add Personal Access Token
  4. 输入个人访问令牌的名称
  5. 可选:选择 Expires 日期来设置过期日期。如果您没有设置过期日期,您的个人访问令牌将永远不会过期,除非被撤销。
  6. 点 Submit。到此,在 Personal Access Tokens 选项卡会包括您可用的个人访问令牌。

    重要

    确保存储您的个人访问令牌,因为您将无法在离开页面或创建新的个人访问令牌后再次访问它。您可以点 Copy to clipboard 复制个人访问令牌。

验证

  1. 向 Satellite 服务器发出 API 请求,并使用您的个人访问令牌进行身份验证:

    # curl https://satellite.example.com/api/status --user My_Username:My_Personal_Access_Token
    Copy to Clipboard Toggle word wrap
  2. 您应该收到状态为 200 的响应,例如:

    {"satellite_version":"6.16.0","result":"ok","status":200,"version":"3.5.1.10","api_version":2}
    Copy to Clipboard Toggle word wrap

    如果您再次返回 Personal Access Tokens 选项卡,您可以在个人访问令牌旁看到最后使用时间。

4.3.2. 撤销个人访问令牌

使用这个流程在过期日期前撤销个人访问令牌。

流程

  1. 在 Satellite Web UI 中,进入到 Administer > Users
  2. 选择您要撤销个人访问令牌的用户。
  3. Personal Access Tokens 选项卡中,找到您要撤销的个人访问令牌。
  4. 在您要撤销的个人访问令牌旁边的 Actions 列中点 Revoke

验证

  1. 向 Satellite 服务器发出 API 请求,并尝试使用撤销的个人访问令牌进行身份验证:

    # curl https://satellite.example.com/api/status --user My_Username:My_Personal_Access_Token
    Copy to Clipboard Toggle word wrap
  2. 您会收到以下出错信息:

    {
      "error": {"message":"Unable to authenticate user My_Username"}
    }
    Copy to Clipboard Toggle word wrap

4.4. OAuth 身份验证概述

作为基本身份验证的替代选择,您可以使用有限的 OAuth 1.0a 身份验证。这有时被称为 1 legged OAuth

要在 Satellite Web UI 中查看 OAuth 设置,请导航到 Administer > Settings > AuthenticationOAuth consumer 密钥 是所有 OAuth 客户端要使用的令牌。

Satellite 将 OAuth 设置存储在 /etc/foreman/settings.yaml 文件中。使用 satellite-installer 脚本配置这些设置。

4.4.1. 配置 OAuth

使用 satellite-installer 更改 Satellite 服务器上的 OAuth 设置。输入以下命令列出所有与 OAuth 相关的安装程序选项:

# satellite-installer --full-help | grep oauth
Copy to Clipboard Toggle word wrap

启用 OAuth 用户映射

默认情况下,Satellite 授权所有 OAuth API 请求作为内置匿名 API 管理员帐户。因此,API 响应包括所有 Satellite 数据。但是,您还可以指定发出请求的 Satellite 用户,并限制对该用户的数据的访问。

要启用 OAuth 用户映射,请输入以下命令:

# satellite-installer --foreman-oauth-map-users true
Copy to Clipboard Toggle word wrap
重要

Satellite 在 OAuth 请求中不为标头签名。具有有效消费者密钥的任何人都可以模拟任何 Satellite 用户。

4.4.2. OAuth 请求格式

每个 OAuth API 请求都需要带有现有 Satellite 用户的登录和 Authorization 标头的 FOREMAN-USER 标头,格式为:

--header 'FOREMAN-USER: My_User_Name' \
--header 'Authorization: OAuth oauth_version="1.0",oauth_consumer_key="secretkey",oauth_signature_method="hmac-sha1",oauth_timestamp=timestamp,oauth_signature=signature'
Copy to Clipboard Toggle word wrap
重要

使用 OAuth 客户端库来构建所有 OAuth 参数。有关使用 requests_oauthlib Python 模块的示例,请参阅红帽知识库中的 通过 Red Hat Satellite 6 中的 python 脚本使用 OAuth 验证方法来执行 API 调用

Example

本例使用 OAuth 进行身份验证列出了架构。请求在 FOREMAN-USER 标头中使用 My_User_Name 用户名。将 --foreman-oauth-map-users 设置为 true 时,响应只包含用户可访问的架构。签名反映了每个参数、HTTP 方法和 URI 更改。

请求示例:

$ curl 'https://satellite.example.com/api/architectures' \
--header 'Content-Type: application/json' \
--header 'Accept:application/json' \
--header 'FOREMAN-USER: My_User_Name' \
--header 'Authorization: OAuth oauth_version="1.0",oauth_consumer_key="secretkey",oauth_signature_method="hmac-sha1",oauth_timestamp=1321473112,oauth_signature=Il8hR8/ogj/XVuOqMPB9qNjSy6E='
Copy to Clipboard Toggle word wrap

第 5 章 使用各种语言的 API 请求

您可以查看从 curl、Ruby 或 Python 向 Red Hat Satellite 发送 API 请求示例。

5.1. 在 curl 中调用 API

您可以将 curl 与 Satellite API 搭配使用来执行各种任务。

Red Hat Satellite 需要使用 HTTPS,默认是主机识别的证书。如果您还没有添加 Satellite 服务器证书,如 第 4.1 节 “SSL 身份验证概述” 所述,您可以使用-- insecure 选项绕过证书检查。

对于用户身份验证,您可以使用-- user 选项以 form- user username:password 提供 Satellite 用户凭据,或者如果您不包含密码,命令会提示您输入它。要降低安全风险,请不要将密码包含在命令中,因为它会成为 shell 历史记录的一部分。本节中的示例仅包含简单性的密码。

请注意,如果您使用- silent 选项,则 curl 不会显示进度计量或任何错误消息。

本章中的示例使用 Python json.tool 模块格式化输出。

5.1.1. 将 JSON 数据传递给 API 请求

您可以使用 API 请求将数据传递给 Satellite 服务器。数据必须采用 JSON 格式。当使用 the-data 选项指定 JSON 数据时,您必须使用-- header 选项设置以下 HTTP 标头:

--header "Accept:application/json" \
--header "Content-Type:application/json"
Copy to Clipboard Toggle word wrap

使用以下选项之一将数据与- data 选项一起包含

JSON 格式的字符串

将带引号的 JSON 格式的数据用大括号 {} 括起。在传递 JSON 类型参数的值时,您必须用反斜杠 \ 转义引号 "。例如,在大括号中,您必须将 "示例 JSON 变量" 格式化为 \"Example JSON Variable\"

--data {"id":44, "smart_class_parameter":{"override":"true", "parameter_type":"json", "default_value":"{\"GRUB_CMDLINE_LINUX\": {\"audit\":\"1\",\"crashkernel\":\"true\"}}"}}
Copy to Clipboard Toggle word wrap

JSON 格式的文件

未加引号的 JSON 格式数据包含在文件中,并由 @ 符号和文件名指定。例如:

--data @file.json
Copy to Clipboard Toggle word wrap

将外部文件用于 JSON 格式数据有以下优点:

  • 您可以使用您首选的文本编辑器。
  • 您可以使用语法检查程序来查找并避免错误。
  • 您可以使用工具检查 JSON 数据的有效性或重新格式化它。

使用 json_verify 工具检查 JSON 文件的有效性:

$ json_verify < file.json
Copy to Clipboard Toggle word wrap

5.1.2. 检索资源列表

本节概述了如何将 curl 与 Satellite 6 API 搭配使用,以从 Satellite 请求信息。这些示例包括请求和响应。每个部署都有不同的结果。

列出用户

本例是返回 Satellite 资源列表(本例中为 Satellite 用户)的基本请求。此类请求返回嵌套在元数据中的数据列表,而其他请求类型则仅返回实际对象。

请求示例:

$ curl --request GET --user My_User_Name:My_Password \
https://satellite.example.com/api/users | python3 -m json.tool
Copy to Clipboard Toggle word wrap

响应示例:

{
    "page": 1,
    "per_page": 20,
    "results": [
        {
            "admin": false,
            "auth_source_id": 1,
            "auth_source_name": "Internal",
            "created_at": "2018-09-21 08:59:22 UTC",
            "default_location": null,
            "default_organization": null,
            "description": "",
            "effective_admin": false,
            "firstname": "",
            "id": 5,
            "last_login_on": "2018-09-21 09:03:25 UTC",
            "lastname": "",
            "locale": null,
            "locations": [],
            "login": "test",
            "mail": "example@domain.com",
            "organizations": [
                {
                    "id": 1,
                    "name": "Default Organization"
                }
            ],
            "ssh_keys": [],
            "timezone": null,
            "updated_at": "2018-09-21 09:04:45 UTC"
        },
        {
            "admin": true,
            "auth_source_id": 1,
            "auth_source_name": "Internal",
            "created_at": "2018-09-20 07:09:41 UTC",
            "default_location": null,
            "default_organization": {
                "description": null,
                "id": 1,
                "name": "Default Organization",
                "title": "Default Organization"
            },
            "description": "",
            "effective_admin": true,
            "firstname": "Admin",
            "id": 4,
            "last_login_on": "2018-12-07 07:31:09 UTC",
            "lastname": "User",
            "locale": null,
            "locations": [
                {
                    "id": 2,
                    "name": "Default Location"
                }
            ],
            "login": "admin",
            "mail": "root@example.com",
            "organizations": [
                {
                    "id": 1,
                    "name": "Default Organization"
                }
            ],
            "ssh_keys": [],
            "timezone": null,
            "updated_at": "2018-11-14 08:19:46 UTC"
        }
    ],
    "search": null,
    "sort": {
        "by": null,
        "order": null
    },
    "subtotal": 2,
    "total": 2
}
Copy to Clipboard Toggle word wrap

5.1.3. 创建和修改资源

您可以使用 curl 操作 Satellite 服务器上的资源。对 Satellite 的 API 调用需要 json 格式的数据。如需更多信息,请参阅 第 5.1.1 节 “将 JSON 数据传递给 API 请求”

创建用户

本例通过在 data- data 选项中提供所需的信息来创建用户。

请求示例:

$ curl --header "Accept:application/json" \
--header "Content-Type:application/json" --request POST \
--user My_User_Name:My_Password \
--data "{\"firstname\":\"Test Name\",\"mail\":\"test@example.com\",\"login\":\"test_user\",\"password\":\"password123\",\"auth_source_id\":1}" \
https://satellite.example.com/api/users | python3 -m json.tool
Copy to Clipboard Toggle word wrap

修改用户

这个示例修改 创建用户 中创建的 test_user 的名称和登录。

请求示例:

$ curl --header "Accept:application/json" \
--header "Content-Type:application/json" --request PUT \
--user My_User_Name:My_Password \
--data "{\"firstname\":\"New Test Name\",\"mail\":\"test@example.com\",\"login\":\"new_test_user\",\"password\":\"password123\",\"auth_source_id\":1}" \
https://satellite.example.com/api/users/8 | python3 -m json.tool
Copy to Clipboard Toggle word wrap

5.2. 在 Ruby 中调用 API

您可以将 Ruby 与 Satellite API 搭配使用来执行各种任务。

重要

这些是示例脚本和命令。在使用之前,请确定您仔细查看这些脚本,并替换任何变量、用户名、密码和其他信息,以适应您自己的部署。

5.2.1. 使用 Ruby 创建对象

此脚本连接到 Red Hat Satellite 6 API 并创建一个机构,然后在组织中创建三个生命周期环境。如果机构已存在,该脚本将使用该组织。如果机构中已存在任何生命周期环境,该脚本将引发错误并退出。

#!/usr/bin/ruby

require 'rest-client'
require 'json'

url = 'https://satellite.example.com/api/v2/'
katello_url = "#{url}/katello/api/v2/"

$username = 'admin'
$password = 'changeme'

org_name = "MyOrg"
environments = [ "Development", "Testing", "Production" ]

# Performs a GET by 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 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 = 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
Copy to Clipboard Toggle word wrap

5.2.2. 在 Ruby 中使用 apipie 绑定

apipie 绑定是针对 apipie 记录的 API 调用的 Ruby 绑定。它们从 Satellite 获取并缓存 API 定义,然后根据需要生成 API 调用。

#!/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://satellite.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
Copy to Clipboard Toggle word wrap

5.3. 在 Python 中调用 API

您可以将 Python 与 Satellite API 搭配使用来执行各种任务。

重要

这些是示例脚本和命令。在使用之前,请确定您仔细查看这些脚本,并替换任何变量、用户名、密码和其他信息,以适应您自己的部署。

本节中的示例脚本不使用 SSL 验证与 REST API 交互。

5.3.1. 使用 Python 创建对象

此脚本连接到 Red Hat Satellite 6 API,并创建组织,然后在组织中创建三个环境。如果机构已存在,该脚本将使用该组织。如果组织中已存在任何环境,该脚本将引发错误并退出。

Python 3 示例

#!/usr/bin/python3

import json
import sys

try:
    import requests
except ImportError:
    print("Please install the python-requests module.")
    sys.exit(-1)

# URL to your Satellite Server
URL = "https://satellite.example.com"
FOREMAN_API = f"{URL}/api/"
KATELLO_API = f"{URL}/katello/api/"
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 by 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(f"{FOREMAN_API}/organizations/{ORG_NAME}")

    # If our organization is not found, create it
    if org.get('error', None):
        org_id = post_json(
            f"{FOREMAN_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(f"Organization '{ORG_NAME}' exists.")

    # Now, let's fetch all available life cycle environments for this org...
    envs = get_json(
        f"{KATELLO_API}/organizations/{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(
            f"{KATELLO_API}/organizations/{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()
Copy to Clipboard Toggle word wrap

5.3.2. 使用 Python 从 API 请求信息

这是使用 Python 进行各种 API 请求的示例脚本。

Python 3 示例

#!/usr/bin/env python3

import json
import sys

try:
    import requests
except ImportError:
    print("Please install the python-requests module.")
    sys.exit(-1)

HOSTNAME = "satellite.example.com"
# URL for the API to your Satellite Server
FOREMAN_API = f"https://{HOSTNAME}/api/"
KATELLO_API = f"https://{HOSTNAME}/katello/api/v2/"

POST_HEADERS = {'content-type': 'application/json'}
# Default credentials to login to Satellite 6
USERNAME = "admin"
PASSWORD = "password"
# Ignore SSL for now
SSL_VERIFY = False
#SSL_VERIFY = "./path/to/CA-certificate.crt" # Put the path to your CA certificate here to allow SSL_VERIFY


def get_json(url):
    # Performs a GET by 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:
        print(f"{'ID':10}{'Name':40}{'IP':30}{'Operating System':30}")
        for host in hosts:
            print(f"{str(host['id']):10}{host['name']:40}{str(host['ip']):30}{str(host['operatingsystem_name']):30}")

def display_info_for_subs(url):
    subs = get_results(url)
    if subs:
        print(f"{'ID':10}{'Name':90}{'Start Date':30}")
        for sub in subs:
            print(f"{str(sub['id']):10}{sub['name']:90}{str(sub['start_date']):30}")

def main():
    host = HOSTNAME
    print(f"Displaying all info for host {host} ...")
    display_all_results(FOREMAN_API + 'hosts/' + host)

    print(f"Displaying all facts for host {host} ...")
    display_all_results(FOREMAN_API + f'hosts/{host}/facts')

    host_pattern = 'example'
    print(f"Displaying basic info for hosts matching pattern '{host_pattern}'...")
    display_info_for_hosts(FOREMAN_API + 'hosts?per_page=1&search=name~' + host_pattern)

    print(f"Displaying basic info for subscriptions")
    display_info_for_subs(KATELLO_API + 'subscriptions')

    environment = 'production'
    print(f"Displaying basic info for hosts in environment {environment}...")
    display_info_for_hosts(FOREMAN_API + 'hosts?search=environment=' + environment)


if __name__ == "__main__":
    main()
Copy to Clipboard Toggle word wrap

第 6 章 API cheat sheet

您可以查看如何使用 Red Hat Satellite API 执行各种任务的示例。您可以通过 HTTPS 在端口 443 上使用 API。

例如,在 Ruby 中,您可以指定 Satellite 服务器 URL,如下所示:

url = 'https://satellite.example.com/api/v2/'
katello_url = 'https://satellite.example.com/katello/api/v2/'
Copy to Clipboard Toggle word wrap

您可以使用这些值来完全自动化脚本,无需验证要使用的端口。

以下示例使用 curl 发送 API 请求。如需更多信息,请参阅 第 5.1 节 “在 curl 中调用 API”

6.1. 使用主机

列出主机

本例返回 Satellite 主机列表。

请求示例:

$ curl --request GET --user My_User_Name:My_Password \
https://satellite.example.com/api/v2/hosts | python3 -m json.tool
Copy to Clipboard Toggle word wrap

响应示例:

{
      ...
       "total" => 2,
    "subtotal" => 2,
        "page" => 1,
    "per_page" => 1000,
      "search" => nil,
        "sort" => {
           "by" => nil,
        "order" => nil
    },
     "results" => [
      ...
}
Copy to Clipboard Toggle word wrap

为主机请求信息

此请求返回主机 satellite.example.com 的信息。

请求示例:

$  curl --request GET --user My_User_Name:My_Password \
https://satellite.example.com/api/v2/hosts/satellite.example.com \
| python3 -m json.tool
Copy to Clipboard Toggle word wrap

响应示例:

{
    "all_puppetclasses": [],
    "architecture_id": 1,
    "architecture_name": "x86_64",
    "build": false,
    "capabilities": [
        "build"
    ],
    "certname": "satellite.example.com",
    "comment": null,
    "compute_profile_id": null,
    ...
}
Copy to Clipboard Toggle word wrap

列出主机事实

此请求返回主机 satellite.example.com 的所有事实。

请求示例:

$ curl --request GET --user My_User_Name:My_Password \
https://satellite.example.com/api/v2/hosts/satellite.example.com/facts \
| python3 -m json.tool
Copy to Clipboard Toggle word wrap

响应示例:

{
    ...
    "results": {
        "satellite.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",
            ...
}
Copy to Clipboard Toggle word wrap

搜索具有匹配模式的主机

此查询返回与模式"example"匹配的所有主机。

请求示例:

$ curl --request GET --user My_User_Name:My_Password \
https://satellite.example.com/api/v2/hosts?search=example \
| python3 -m json.tool
Copy to Clipboard Toggle word wrap

响应示例:

{
    ...
    "results": [
        {
            "name": "satellite.example.com",
            ...
        }
    ],
    "search": "example",
    ...
}
Copy to Clipboard Toggle word wrap

搜索环境中的主机

此查询会返回生产环境中的所有主机。

请求示例:

$ curl --request GET --user My_User_Name:My_Password \
https://satellite.example.com/api/v2/hosts?search=environment=production \
| python3 -m json.tool
Copy to Clipboard Toggle word wrap

响应示例:

{
    ...
    "results": [
        {
            "environment_name": "production",
            "name": "satellite.example.com",
            ...
        }
    ],
    "search": "environment=production",
    ...
}
Copy to Clipboard Toggle word wrap

使用特定事实值搜索主机

此查询返回具有模型名称 RHV Hypervisor 的所有主机。

请求示例:

$ curl --request GET --user My_User_Name:My_Password \
https://satellite.example.com/api/v2/hosts?search=model=\"RHV+Hypervisor\" \
| python3 -m json.tool
Copy to Clipboard Toggle word wrap

响应示例:

{
    ...
    "results": [
        {
            "model_id": 1,
            "model_name": "RHV Hypervisor",
            "name": "satellite.example.com",
            ...
        }
    ],
    "search": "model=\"RHV Hypervisor\"",
    ...
}
Copy to Clipboard Toggle word wrap

删除主机

此请求删除名为 host1.example.com 的主机。

请求示例:

$ curl --request DELETE --user My_User_Name:My_Password \
https://satellite.example.com/api/v2/hosts/host1.example.com \
| python3 -m json.tool
Copy to Clipboard Toggle word wrap

下载全主机引导磁盘镜像

此请求通过其 ID 下载主机的完整引导磁盘镜像。

请求示例:

$ curl --request GET --user My_User_Name:My_Password \
https://satellite.example.com/api/bootdisk/hosts/host_ID?full=true \
--output image.iso
Copy to Clipboard Toggle word wrap

6.2. 使用生命周期环境

Satellite 将应用程序生命周期划分为生命周期环境,这代表应用程序生命周期的每个阶段。生命周期环境从环境路径链接到。要创建与 API 链接的生命周期环境,请使用 prior_id 参数。

您可以在 https://satellite.example.com/apidoc/v2/lifecycle_environments.html 中查找生命周期环境的内置 API 参考。API 路由包括 /katello/api/environments/katello/api/organizations/:organization_id/environments

列出生命周期环境

使用此 API 调用列出您 Satellite 上 ID 为 1 的默认组织的所有当前生命周期环境。

请求示例:

$ curl --header "Accept:application/json" \
--header "Content-Type:application/json" \
--request GET --user My_User_Name:My_Password \
https://satellite.example.com/katello/api/organizations/1/environments \
| python3 -m json.tool`
Copy to Clipboard Toggle word wrap

响应示例:

      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
Copy to Clipboard Toggle word wrap

创建链接的生命周期环境

使用本示例创建生命周期环境的路径。

此流程使用 ID 为 1 的默认库环境,作为创建生命周期环境的起点。

  1. 选择您要用作起点的现有生命周期环境。使用其 ID 列出环境,本例中为 ID 为 1 的环境:

    请求示例:

    $ curl --request GET --user My_User_Name:My_Password \
    https://satellite.example.com/katello/api/environments/1 \
    | python3 -m json.tool
    Copy to Clipboard Toggle word wrap

    响应示例:

    	output omitted
       "id": 1,
       "label": "Library",
    	output omitted
        "prior": null,
        "successor": null,
      output truncated
    Copy to Clipboard Toggle word wrap
  2. 创建包含以下内容的 JSON 文件,如 life-cycle.json

    {"organization_id":1,"label":"api-dev","name":"API Development","prior":1}
    Copy to Clipboard Toggle word wrap
  3. 使用 prior 选项设置为 1 来创建生命周期环境。

    请求示例:

    $ curl --header "Accept:application/json" \
    --header "Content-Type:application/json" \
    --request POST --user My_User_Name:My_Password \
    --data @life-cycle.json \
    https://satellite.example.com/katello/api/environments \
    | python3 -m json.tool
    Copy to Clipboard Toggle word wrap

    响应示例:

          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
    Copy to Clipboard Toggle word wrap

    在命令输出中,您可以看到此生命周期环境的 ID 是 2,并在这前看到生命周期环境为 1。使用 ID 2 的生命周期环境来创建此环境的后续者。

  4. 编辑之前创建的 life-cycle.json 文件,更新 标签namebefore 值。

    {"organization_id":1,"label":"api-qa","name":"API QA","prior":2}
    Copy to Clipboard Toggle word wrap
  5. 使用 prior 选项设置为 2 来创建生命周期环境。

    请求示例:

    $ curl --header "Accept:application/json" \
    --header "Content-Type:application/json" \
    --request POST --user My_User_Name:My_Password \
    --data @life-cycle.json \
    https://satellite.example.com/katello/api/environments \
    | python3 -m json.tool
    Copy to Clipboard Toggle word wrap

    响应示例:

          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
    Copy to Clipboard Toggle word wrap

    在命令输出中,您可以看到此生命周期环境的 ID 是 3,在这前的生命周期环境为 2

更新生命周期环境

您可以使用 PUT 命令更新生命周期环境。

这个示例请求使用 ID 3 更新生命周期环境的描述。

请求示例:

$ curl --header "Accept:application/json" \
--header "Content-Type:application/json" \
--request POST --user My_User_Name:My_Password \
--data '{"description":"Quality Acceptance Testing"}' \
https://satellite.example.com/katello/api/environments/3 \
| python3 -m json.tool
Copy to Clipboard Toggle word wrap

响应示例:

      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
Copy to Clipboard Toggle word wrap

删除生命周期环境

您可以删除没有后续者的生命周期环境。因此,使用以下格式的命令以相反的顺序删除它们:

请求示例:

$ curl --request DELETE --user My_User_Name:My_Password \
https://satellite.example.com/katello/api/environments/:id
Copy to Clipboard Toggle word wrap

6.3. 将内容上传到 Satellite 服务器

您可以使用 Satellite API 将大型文件上传并导入到您的 Satellite 服务器。这个过程涉及四个步骤:

  1. 创建上传请求。
  2. 上传内容。
  3. 导入内容。
  4. 删除上传请求。

您可以上传的最大文件大小为 2 MB。有关上传大量内容的详情,请参考 上传大于 2 MB 的内容

流程

  1. 为变量 name 分配软件包名称:

    请求示例:

    $ export name=jq-1.6-2.el7.x86_64.rpm
    Copy to Clipboard Toggle word wrap
  2. 将文件的校验和分配给变量 checksum

    请求示例:

    $ export checksum=$(sha256sum $name|cut -c 1-65)
    Copy to Clipboard Toggle word wrap
  3. 将文件大小分配给变量 大小

    请求示例:

    $ export size=$(du -bs $name|cut -f 1)
    Copy to Clipboard Toggle word wrap
  4. 创建一个上传请求,以使用 大小和 校验和 返回请求的上传 ID。

    请求示例:

    $ curl -H 'Content-Type: application/json' -X POST -k \
    -u My_User_Name:My_Password \
    -d "{\"size\": \"$size\", \"checksum\":\"$checksum\"}" \
    https://satellite.example.com/katello/api/v2/repositories/76/content_uploads
    Copy to Clipboard Toggle word wrap

    其中 76,本例中为 Repository ID 示例。

    请求示例:

    {"upload_id":"37eb5900-597e-4ac3-9bc5-2250c302fdc4"}
    Copy to Clipboard Toggle word wrap
  5. 将上传 ID 分配给变量 upload_id

    $ export upload_id=37eb5900-597e-4ac3-9bc5-2250c302fdc4
    Copy to Clipboard Toggle word wrap
  6. 分配您要上传到变量 路径的软件包路径

    $ export path=/root/jq/jq-1.6-2.el7.x86_64.rpm
    Copy to Clipboard Toggle word wrap
  7. 上传您的内容。确保在上传数据时使用正确的 MIME 类型。API 对 Satellite 的请求使用 application/json MIME 类型,除非另有说明。组合上传 ID、MIME 类型和其他参数以上传内容。

    请求示例:

    $ curl -u My_User_Name:My_Password -H Accept:application/json -H \
    Content-Type:multipart/form-data --request PUT --data-urlencode size=$size --data-urlencode offset=0 \
    --data-urlencode content@${path} \
    https://satellite.example.com/katello/api/v2/repositories/76/content_uploads/$upload_id
    Copy to Clipboard Toggle word wrap
  8. 将内容上传到 Satellite 服务器后,您需要将它导入到适当的存储库中。在完成此步骤前,Satellite 服务器不会检测到新内容。

    请求示例:

    $ curl -H "Content-Type:application/json" -X PUT -u \
    My_User_Name:My_Password -k -d \
    "{\"uploads\":[{\"id\": \"$upload_id\", \"name\": \"$name\", \
    \"checksum\": \"$checksum\" }]}" \
    https://satellite.example.com/katello/api/v2/repositories/76/import_uploads
    Copy to Clipboard Toggle word wrap
  9. 成功上传并导入内容后,您可以删除上传请求。这释放在上传过程中使用的任何临时磁盘空间。

    请求示例:

    $ curl -H 'Content-Type: application/json' -X DELETE -k \
    -u My_User_Name:My_Password -d "{}" \
    https://satellite.example.com/katello/api/v2/repositories/76/content_uploads/$upload_id
    Copy to Clipboard Toggle word wrap

上传大于 2 MB 的内容

以下示例演示了如何将大型文件分成块,创建上传请求,上传单个文件,将它们导入到 Satellite,然后删除上传请求。请注意,本示例使用示例内容、主机名、用户名、存储库 ID 和文件名。

  1. 为变量 name 分配软件包名称:

    $ export name=bpftool-3.10.0-1160.2.1.el7.centos.plus.x86_64.rpm
    Copy to Clipboard Toggle word wrap
  2. 将文件的校验和分配给变量 checksum

    $ export  checksum=$(sha256sum $name|cut -c 1-65)
    Copy to Clipboard Toggle word wrap
  3. 将文件大小分配给变量 大小

    $ export  size=$(du -bs $name|cut -f 1)
    Copy to Clipboard Toggle word wrap
  4. 以下命令创建新的上传请求,并使用 大小和 校验和 返回请求的上传 ID。

    请求示例:

    $ curl -H 'Content-Type: application/json' -X POST -k \
    -u My_User_Name:My_Password -d "{\"size\": \"$size\", \
    \"checksum\":\"$checksum\"}" \
    https://satellite.example.com/katello/api/v2/repositories/76/content_uploads
    Copy to Clipboard Toggle word wrap

    其中 76,本例中为 Repository ID 示例。

    输出示例

    {"upload_id":"37eb5900-597e-4ac3-9bc5-2250c302fdc4"}
    Copy to Clipboard Toggle word wrap
  5. 将上传 ID 分配给变量 upload_id

    $ export upload_id=37eb5900-597e-4ac3-9bc5-2250c302fdc4
    Copy to Clipboard Toggle word wrap
  6. 以 2MB 的块分割文件:

    $ split --bytes 2MB --numeric-suffixes \
    --suffix-length=1 bpftool-3.10.0-1160.2.1.el7.centos.plus.x86_64.rpm bpftool
    Copy to Clipboard Toggle word wrap

    输出示例

    $ ls bpftool[0-9] -l
    -rw-r--r--.
    1 root root 2000000 Mar 31 14:15 bpftool0
    -rw-r--r--.
    1 root root 2000000 Mar 31 14:15 bpftool1
    -rw-r--r--.
    1 root root 2000000 Mar 31 14:15 bpftool2
    -rw-r--r--.
    1 root root 2000000 Mar 31 14:15 bpftool3
    -rw-r--r--.
    1 root root  868648 Mar 31 14:15 bpftool4
    Copy to Clipboard Toggle word wrap
  7. 将分割文件的前缀分配给变量路径。

    $ export path=/root/tmp/bpftool
    Copy to Clipboard Toggle word wrap
  8. 上传文件块。偏移从第一个块的 0 字节开始,并为每个文件增加 2000000 字节。请注意使用 offset 参数,以及如何与文件大小相关。另请注意,索引在路径变量后使用,如 ${path}0, ${path}1。

    请求示例:

    $ curl -u My_User_Name:My_Password -H Accept:application/json -H \
    Content-Type:multipart/form-data  \
    -X PUT --data-urlencode size=$size --data-urlencode offset=0 \
    --data-urlencode content@${path}0 \
    https://satellite.example.com/katello/api/v2/repositories/76/content_uploads/$upload_id
    
    $ curl -u My_User_Name:My_Password -H Accept:application/json -H \
    Content-Type:multipart/form-data \
    -X PUT --data-urlencode size=$size --data-urlencode offset=2000000 \
    --data-urlencode content@${path}1 \
    https://satellite.example.com/katello/api/v2/repositories/76/content_uploads/$upload_id
    
    $ curl -u My_User_Name:My_Password -H Accept:application/json -H \
    Content-Type:multipart/form-data \
    -X PUT --data-urlencode size=$size --data-urlencode offset=4000000 \
    --data-urlencode content@${path}2 \
    https://satellite.example.com/katello/api/v2/repositories/76/content_uploads/$upload_id
    
    $curl -u My_User_Name:My_Password -H Accept:application/json -H \
    Content-Type:multipart/form-data \
    -X PUT --data-urlencode size=$size --data-urlencode offset=6000000
    --data-urlencode content@${path}3 \
    https://satellite.example.com/katello/api/v2/repositories/76/content_uploads/$upload_id
    
    $ curl -u My_User_Name:My_Password -H Accept:application/json -H \
    Content-Type:multipart/form-data \
    -X PUT --data-urlencode size=$size --data-urlencode offset=8000000 \
    --data-urlencode content@${path}4 \
    https://satellite.example.com/katello/api/v2/repositories/76/content_uploads/$upload_id
    Copy to Clipboard Toggle word wrap
  9. 将完整上传到存储库:

    $ curl -H "Content-Type:application/json" -X PUT -u \
    My_User_Name:My_Password -k -d \
    "{\"uploads\":[{\"id\": \"$upload_id\", \
    \"name\": \"$name\", \"checksum\": \"$checksum\" }]}" \
    https://satellite.example.com/katello/api/v2/repositories/76/import_uploads
    Copy to Clipboard Toggle word wrap
  10. 删除上传请求:

    $ curl -H 'Content-Type: application/json' -X DELETE -k \
    -u My_User_Name:My_Password -d "{}" \
    https://satellite.example.com/katello/api/v2/repositories/76/content_uploads/$upload_id
    Copy to Clipboard Toggle word wrap

上传重复内容

请注意,如果您尝试使用以下内容上传重复内容:

请求示例:

$ curl -H 'Content-Type: application/json' -X POST -k \
-u My_User_Name:My_Password -d "{\"size\": \"$size\", \"checksum\":\"$checksum\"}" \
https://satellite.example.com/katello/api/v2/repositories/76/content_uploads
Copy to Clipboard Toggle word wrap

调用将返回内容单元 ID 而不是上传 ID,如下所示:

{"content_unit_href":"/pulp/api/v3/content/file/files/c1bcdfb8-d840-4604-845e-86e82454c747/"}
Copy to Clipboard Toggle word wrap

您可以直接复制此输出并调用导入上传,将内容添加到存储库中:

请求示例:

$ curl -H "Content-Type:application/json" -X PUT -u \
My_User_Name:My_Password -k \-d \
"{\"uploads\":[{\"content_unit_id\": \"/pulp/api/v3/content/file/files/c1bcdfb8-d840-4604-845e-86e82454c747/\", \
\"name\": \"$name\", \ \"checksum\": \"$checksum\" }]}" \
https://satellite.example.com/katello/api/v2/repositories/76/import_uploads
Copy to Clipboard Toggle word wrap

请注意,调用从 使用 upload_id 更改为使用 content_unit_id

6.4. 将勘误应用到主机

您可以使用 API 将勘误表应用到主机、主机组或主机集合。以下是 PUT 请求的基本语法:

$ curl --header "Accept:application/json" \
--header "Content-Type:application/json" --request PUT \
--user My_User_Name:My_Password \
--data My_JSON_Formatted_Data https://satellite.example.com
Copy to Clipboard Toggle word wrap

您可以浏览内置的 API 文档,以查找用于应用勘误表的 URL。您可以使用 Satellite Web UI 来帮助发现搜索查询的格式。进入到 Hosts > Host Collections 并选择主机集合。进入 Collection Actions > Errata Installation,并注意搜索查询框内容。例如,对于名为 my-collection 的 Host Collection,搜索框包含 host_collection="my-collection"。

6.5. 使用扩展搜索

您可以在 Satellite Web UI 中找到可用于构建搜索查询的搜索参数。如需更多信息,请参阅管理 Red Hat Satellite 中的 构建搜索查询

例如,您可以搜索主机。

流程

  1. 在 Satellite Web UI 中,进入到 Hosts > All Hosts,然后点击 Search 字段来显示搜索参数列表。
  2. 找到您要使用的搜索参数。在本例中,找到 os_titlemodel
  3. 组合 API 查询中的搜索参数,如下所示:

    请求示例:

    $ curl --user My_User_Name:My_Password \
    https://satellite.example.com/api/v2/hosts?search=os_title=\"RedHat+7.7\",model=\"PowerEdge+R330\" \
    | python3 -m json.tool
    Copy to Clipboard Toggle word wrap

    响应示例:

      {
        ...
        "results": [
            {
                "model_id": 1,
                "model_name": "PowerEdge R330",
                "name": "satellite.example.com",
                "operatingsystem_id": 1,
                "operatingsystem_name": "RedHat 7.7",
                ...
            }
        ],
        "search": "os_title=\"RedHat 7.7\",model=\"PowerEdge R330\"",
        "subtotal": 1,
        "total": 11
    }
    Copy to Clipboard Toggle word wrap

6.6. 使用搜索分页控制

您可以使用 per_pagepage 分页参数来限制 API 搜索查询返回的搜索结果。per_ page 参数指定每个页面的结果数,page 参数指定根据 per_page 参数计算的页面,以返回。

当您没有指定任何分页参数时,要返回的默认项目数量被设置为 1000,但 per_page 值的默认值是 20,当您指定 page 参数时应用它。

列出内容视图

本例在页面中返回 Content Views 列表。列表中为每个页面包含 10 个键,并返回第三个页面。

请求示例:

$ curl --request GET --user My_User_Name:My_Password \
https://satellite.example.com/katello/api/content_views?per_page=10&amp;page=3
Copy to Clipboard Toggle word wrap

列出激活码

本例返回 ID 为 1 的机构的激活码列表。列表中包含每个页面 30 个键,并返回第二个页面。

请求示例:

$ curl --request GET --user My_User_Name:My_Password \
https://satellite.example.com/katello/api/activation_keys?organization_id=1&amp;per_page=30&amp;page=2
Copy to Clipboard Toggle word wrap

返回多个页面

您可以使用 for 循环结构来获取多个结果页面。

这个示例将第 1 页的 Content Views 的 3 页返回,每个页为 5 个结果:

$ for i in seq 1 3; do \
curl --request GET --user My_User_Name:My_Password \
https://satellite.example.com/katello/api/content_views?per_page=5&amp;page=$i; \
done
Copy to Clipboard Toggle word wrap

6.7. 覆盖智能类参数

您可以使用 API 搜索智能参数,并提供值来覆盖类中的智能参数。您可以在 https://satellite.example.com/apidoc/v2/smart_class_parameters/update.html 处在内置 API 引用中找到可以修改的属性的完整列表。

流程

  1. 查找您要更改的 Smart Class 参数的 ID:

    • 列出所有智能类参数。

      请求示例:

      $ curl --request GET --user My_User_Name:My_Password \
      https://satellite.example.com/api/smart_class_parameters
      Copy to Clipboard Toggle word wrap
    • 如果您知道 Puppet 类 ID,如 5,您可以限制 scope: Example 请求:

      $ curl --request GET --user My_User_Name:My_Password \
      https://satellite.example.com/api/puppetclasses/5/smart_class_parameters
      Copy to Clipboard Toggle word wrap

      这两个调用都接受 search 参数。您可以在 Satellite Web UI 中查看可搜索字段的完整列表。导航到 Configure > Smart variables,点搜索查询框中显示字段列表。

      两个特别有用的搜索参数是 puppetclass_name,可用于搜索特定参数。例如,使用 -data 选项传递 URL 编码数据。

      请求示例:

      $ curl --request GET --user My_User_Name:My_Password \
      --data 'search=puppetclass_name = access_insights_client and key = authmethod' \
      https://satellite.example.com/api/smart_class_parameters
      Copy to Clipboard Toggle word wrap

      Satellite 支持标准有范围的搜索语法。

  2. 当您找到参数的 ID 时,列出包括当前覆盖值在内的完整详情。

    请求示例:

    $ curl --request GET --user My_User_Name:My_Password \
    https://satellite.example.com/api/smart_class_parameters/63
    Copy to Clipboard Toggle word wrap
  3. 启用覆盖参数值。

    请求示例:

    $ curl --header "Accept:application/json" \
    --header "Content-Type:application/json" \
    --request PUT --user My_User_Name:My_Password \
    --data '{"smart_class_parameter":{"override":true}}' \
    https://satellite.example.com/api/smart_class_parameters/63
    Copy to Clipboard Toggle word wrap

    请注意,您无法手动创建或删除参数。您只能修改其属性。Satellite 仅在从 Capsules 导入类时创建和删除参数。

  4. 添加自定义覆盖匹配器。

    请求示例:

    $ curl --header "Accept:application/json" \
    --header "Content-Type:application/json" \
    --request PUT --user My_User_Name:My_Password \
    --data '{"smart_class_parameter":{"override_value":{"match":"hostgroup=Test","value":"2.4.6"}}}' \
    https://satellite.example.com/api/smart_class_parameters/63
    Copy to Clipboard Toggle word wrap

    有关覆盖值的更多信息,请参阅 https://satellite.example.com/apidoc/v2/override_values.html

  5. 您可以删除覆盖值。

    请求示例:

    $ curl --request DELETE --user My_User_Name:My_Password \
    https://satellite.example.com/api/smart_class_parameters/63/override_values/3
    Copy to Clipboard Toggle word wrap

6.8. 使用外部文件修改智能类参数

您可以使用外部文件修改 Puppet 智能类参数。

使用外部文件简化了使用 JSON 数据的过程。您可以使用带有语法高亮显示的编辑器来避免并查找错误。

使用外部文件修改智能类参数

本例使用 MOTD Puppet 清单。

  1. 本例中为 motd,按名称搜索 Puppet 类。

    请求示例:

    $ curl --header "Accept:application/json" \
    --header "Content-Type:application/json" \
    --request GET --user My_User_Name:My_Password \
    https://satellite.example.com/api/smart_class_parameters?search=puppetclass_name=motd \
    | python3 -m json.tool
    Copy to Clipboard Toggle word wrap
  2. 检查以下输出。每个智能类参数都有一个 ID,对于同一 Satellite 实例是全局的。motd 类的 content 参数具有 id=3。不要将其与 Puppet 类名称前面显示的 Puppet 类 ID 混淆。

    响应示例:

    {
    	"avoid_duplicates": false,
    		"created_at": "2017-02-06 12:37:48 UTC", # Remove this line.
    			"default_value": "", # Add a new value here.
    			"description": "",
    		"hidden_value": "",
    		"hidden_value?": false,
    		"id": 3,
    		"merge_default": false,
    		"merge_overrides": false,
    		"override": false, # Set the override value to true.
    			"override_value_order": "fqdn\nhostgroup\nos\ndomain",
    		"override_values": [], # Remove this line.
    			"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", # Remove this line.
    			"use_puppet_default": false,
    		"validator_rule": null,
    		"validator_type": ""
    }
    Copy to Clipboard Toggle word wrap
  3. 使用参数 ID 3 获取特定于 motd 参数的信息,并将输出重定向到文件,如 output_file.json

    请求示例:

    $ curl --header "Accept:application/json" \
    --header "Content-Type:application/json" --request GET \
    --user My_User_Name:My_Password \
    https://satellite.example.com/api/smart_class_parameters/3 \
    | python3 -m json.tool > output_file.json
    Copy to Clipboard Toggle word wrap
  4. 将上一步中创建的文件复制到新文件以进行编辑,例如 changed_file.json

    $ cp output_file.json changed_file.json
    Copy to Clipboard Toggle word wrap
  5. 修改 文件中所需的值。在本例中,更改 motd 模块的 content 参数,该参数需要将 覆盖选项false 改为 true

    {
    	"avoid_duplicates": false,
    		"created_at": "2017-02-06 12:37:48 UTC", # Remove this line.
    			"default_value": "", # Add a new value here.
    			"description": "",
    		"hidden_value": "",
    		"hidden_value?": false,
    		"id": 3,
    		"merge_default": false,
    		"merge_overrides": false,
    		"override": false, # Set the override value to true.
    			"override_value_order": "fqdn\nhostgroup\nos\ndomain",
    		"override_values": [], # Remove this line.
    			"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", # Remove this line.
    			"use_puppet_default": false,
    		"validator_rule": null,
    		"validator_type": ""
    }
    Copy to Clipboard Toggle word wrap
  6. 编辑该文件后,验证是否如下所示,然后保存更改:

    {
    	"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": ""
    }
    Copy to Clipboard Toggle word wrap
  7. 将文件提交到 Satellite:

    $ curl --header "Accept:application/json" \
    --header "Content-Type:application/json" \
    --request PUT --user My_User_Name:My_Password \
    --data @changed_file.json \
    https://satellite.example.com/api/smart_class_parameters/3
    Copy to Clipboard Toggle word wrap

6.9. 删除 OpenSCAP 报告

在 Satellite 服务器中,您可以删除一个或多个 OpenSCAP 报告。但是,当您删除报告时,您必须一次删除一个页面。如果要删除所有 OpenSCAP 报告,请使用如下 bash 脚本。

流程

  1. 列出所有 OpenSCAP 报告。请注意您要删除的报告 ID。

    请求示例:

    $ curl --user My_User_Name:My_Password \
    https://satellite.example.com/api/v2/compliance/arf_reports/ | python3 -m json.tool
    Copy to Clipboard Toggle word wrap

    响应示例:

      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                     Dload  Upload   Total   Spent    Left  Speed
    100  3252    0  3252    0     0   4319      0 --:--:-- --:--:-- --:--:--  4318
    {
        "page": 1,
        "per_page": 20,
        "results": [
            {
                "created_at": "2017-05-16 13:27:09 UTC",
                "failed": 0,
                "host": "host1.example.com",
                "id": 404,
                "othered": 0,
                "passed": 0,
                "updated_at": "2017-05-16 13:27:09 UTC"
            },
            {
                "created_at": "2017-05-16 13:26:07 UTC",
                "failed": 0,
                "host": "host2.example.com,
                "id": 405,
                "othered": 0,
                "passed": 0,
                "updated_at": "2017-05-16 13:26:07 UTC"
            },
            {
                "created_at": "2017-05-16 13:25:07 UTC",
                "failed": 0,
                "host": "host3.example.com",
                "id": 406,
                "othered": 0,
                "passed": 0,
                "updated_at": "2017-05-16 13:25:07 UTC"
            },
            {
                "created_at": "2017-05-16 13:24:07 UTC",
                "failed": 0,
                "host": "host4.example.com",
                "id": 407,
                "othered": 0,
                "passed": 0,
                "updated_at": "2017-05-16 13:24:07 UTC"
            },
        ],
        "search": null,
        "sort": {
            "by": null,
            "order": null
        },
        "subtotal": 29,
        "total": 29
    Copy to Clipboard Toggle word wrap
  2. 使用上一步中的 ID,删除 OpenSCAP 报告。对您要删除的每个 ID 重复此操作。

    请求示例:

    $ curl --user My_User_Name:My_Password \
    --header "Content-Type: application/json" \
    --request DELETE https://satellite.example.com/api/v2/compliance/arf_reports/405
    Copy to Clipboard Toggle word wrap

    响应示例:

    HTTP/1.1 200 OK
    Date: Thu, 18 May 2017 07:14:36 GMT
    Server: Apache/2.4.6 (Red Hat Enterprise Linux)
    X-Frame-Options: SAMEORIGIN
    X-XSS-Protection: 1; mode=block
    X-Content-Type-Options: nosniff
    Foreman_version: 1.11.0.76
    Foreman_api_version: 2
    Apipie-Checksum: 2d39dc59aed19120d2359f7515e10d76
    Cache-Control: max-age=0, private, must-revalidate
    X-Request-Id: f47eb877-35c7-41fe-b866-34274b56c506
    X-Runtime: 0.661831
    X-Powered-By: Phusion Passenger 4.0.18
    Set-Cookie: request_method=DELETE; path=/
    Set-Cookie: _session_id=d58fe2649e6788b87f46eabf8a461edd; path=/; secure; HttpOnly
    ETag: "2574955fc0afc47cb5394ce95553f428"
    Status: 200 OK
    Vary: Accept-Encoding
    Transfer-Encoding: chunked
    Content-Type: application/json; charset=utf-8
    Copy to Clipboard Toggle word wrap

删除所有 OpenSCAP 报告的 BASH 脚本示例

使用以下 bash 脚本删除所有 OpenSCAP 报告:

#!/bin/bash

#this script removes all the ARF reports from your Satellite Server

#settings
USER=username
PASS=password
URI=https://satellite.example.com

#check amount of reports
 while [ $(curl --user $USER:$PASS $URI/api/v2/compliance/arf_reports/ | python3 -m json.tool | grep \"\total\": | cut --fields=2 --delimiter":" | cut --fields=1 --delimiter"," | sed "s/ //g") -gt 0 ]; do

#fetch reports
 for i in $(curl --user $USER:$PASS $URI/api/v2/compliance/arf_reports/ | python3 -m json.tool | grep \"\id\": | cut --fields=2 --delimiter":" | cut --fields=1 --delimiter"," | sed "s/ //g")

#delete reports
  do
  curl --user $USER:$PASS --header "Content-Type: application/json" --request DELETE $URI/api/v2/compliance/arf_reports/$i
  done
done
Copy to Clipboard Toggle word wrap

附录 A. API 响应代码

Red Hat Satellite 6 API 为 API 调用提供 HTTP 响应状态代码。以下代码是 Satellite API 中所有资源的通用代码。

Expand
表 A.1. API 响应代码
响应解释

200 OK

对于成功请求操作:显示、索引、更新或删除(GET、PUT、DELETE 请求)。

201 created

对于成功创建操作(POST 请求)。

301 永久移动

当 Satellite 限制为使用 HTTPS 但尝试使用 HTTP 时,会进行重定向。

400 错误请求

缺少需要的参数,或者搜索查询具有无效的语法。

401 未授权

授权用户失败,例如因为凭证不正确。

403 Forbidden

用户没有足够的权限来执行操作或读取资源,或者通常不支持该操作。

404 not Found

带有给定 ID 的记录不存在。当请求的记录不存在时,它可能会显示和删除操作,或者在其中一个关联的记录不存在时删除操作。

409 冲突

无法因为现有的依赖项删除记录,例如,仍然包含主机的主机组。

415 不支持的 Media Type

HTTP 请求的内容类型是 JSON。

422 Unprocessable Entity

由于一些验证错误,创建实体失败。仅适用于创建或更新操作。

500 内部服务器错误

意外的内部服务器错误。

503 服务不可用

服务器没有运行。

附录 B. 创建完整权限表

使用 Satellite CLI 创建权限表。

流程

  1. 使用以下命令启动 Satellite 控制台:

    # foreman-rake console
    Copy to Clipboard Toggle word wrap
  2. 在控制台中插入以下代码:

    f = File.open('/tmp/table.html', 'w')
    
    result = Foreman::AccessControl.permissions {|a,b| a.security_block <=> b.security_block}.collect do |p|
          actions = p.actions.collect { |a| "<li>#{a}</li>" }
          "<tr><td>#{p.name}</td><td><ul>#{actions.join('')}</ul></td><td>#{p.resource_type}</td></tr>"
    end.join("\n")
    
    f.write(result)
    Copy to Clipboard Toggle word wrap

    以上语法会创建一个权限表,并将其保存到 /tmp/table.html 文件中。

  3. Ctrl + D 退出 Satellite 控制台。
  4. 将以下文本插入到 /tmp/table.html 的第一行:

    <table border="1"><tr><td>Permission name</td><td>Actions</td><td>Resource type</td></tr>
    Copy to Clipboard Toggle word wrap
  5. 将以下文本附加到 /tmp/table.html 的末尾:

    </table>
    Copy to Clipboard Toggle word wrap
  6. 在 Web 浏览器中打开 /tmp/table.html 以查看表。

法律通告

Copyright © 2025 Red Hat, Inc.
The text of and illustrations in this document are licensed by Red Hat under a Creative Commons Attribution–Share Alike 3.0 Unported license ("CC-BY-SA"). An explanation of CC-BY-SA is available at http://creativecommons.org/licenses/by-sa/3.0/. In accordance with CC-BY-SA, if you distribute this document or an adaptation of it, you must provide the URL for the original version.
Red Hat, as the licensor of this document, waives the right to enforce, and agrees not to assert, Section 4d of CC-BY-SA to the fullest extent permitted by applicable law.
Red Hat, Red Hat Enterprise Linux, the Shadowman logo, the Red Hat logo, JBoss, OpenShift, Fedora, the Infinity logo, and RHCE are trademarks of Red Hat, Inc., registered in the United States and other countries.
Linux® is the registered trademark of Linus Torvalds in the United States and other countries.
Java® is a registered trademark of Oracle and/or its affiliates.
XFS® is a trademark of Silicon Graphics International Corp. or its subsidiaries in the United States and/or other countries.
MySQL® is a registered trademark of MySQL AB in the United States, the European Union and other countries.
Node.js® is an official trademark of Joyent. Red Hat is not formally related to or endorsed by the official Joyent Node.js open source or commercial project.
The OpenStack® Word Mark and OpenStack logo are either registered trademarks/service marks or trademarks/service marks of the OpenStack Foundation, in the United States and other countries and are used with the OpenStack Foundation's permission. We are not affiliated with, endorsed or sponsored by the OpenStack Foundation, or the OpenStack community.
All other trademarks are the property of their respective owners.
返回顶部
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

Theme

© 2026 Red Hat