Ondřej Budai
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
      • Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
Invitee
Publish Note

Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

Your note will be visible on your profile and discoverable by anyone.
Your note is now live.
This note is visible on your profile and discoverable online.
Everyone on the web can find and read all notes of this public team.
See published notes
Unpublish note
Please check the box to agree to the Community Guidelines.
View profile
Engagement control
Commenting
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
  • Everyone
Suggest edit
Permission
Disabled Forbidden Owners Signed-in users Everyone
Enable
Permission
  • Forbidden
  • Owners
  • Signed-in users
Emoji Reply
Enable
Import from Dropbox Google Drive Gist Clipboard
   owned this note    owned this note      
Published Linked with GitHub
1
Subscribed
  • Any changes
    Be notified of any changes
  • Mention me
    Be notified of mention me
  • Unsubscribe
Subscribe
# Using hosted Image Builder programmatically # OUTDATED, SEE https://docs.google.com/document/d/1JezrLQ4HVnMT8grhwuNbfQyiJaGbxF-yKwsWddyqTxU/edit?usp=sharing https://source.redhat.com/groups/public/blog_bounty_program ### Inspiration - [Building a customized Azure VM image with Image Builder and libvirt](https://www.redhat.com/en/blog/building-customized-azure-vm-image-image-builder-and-libvirt) - [Announcing full support for new Red Hat Enterprise Linux image builder service](https://www.redhat.com/en/blog/announcing-full-support-new-red-hat-enterprise-linux-image-builder-service) - [Using the no-cost Developer Subscription with the new Red Hat Enterprise Linux Image Builder hosted service](https://www.redhat.com/en/blog/using-no-cost-developer-subscription-new-red-hat-enterprise-linux-image-builder-hosted-service) - [Build RHEL images for Azure with Image Builder](https://www.redhat.com/en/blog/build-rhel-images-azure-image-builder) - [Introducing the hosted beta experience Red Hat Enterprise Linux Image Builder](https://www.redhat.com/en/blog/introducing-hosted-beta-experience-red-hat-enterprise-linux-image-builder) - [Build a custom CentOS Stream 9 cloud image](https://major.io/2022/05/06/build-a-custom-centos-stream-9-cloud-image/) The post starts here: --- Image Builder is a new hosted Red Hat offering for building customized cloud images. In this blog post, I want to show you how to use it from the command line. ## Introducing Image Builder is a hosted service in Red Hat Hybrid Cloud Console allowing you to quickly assemble a customized image. Hybrid cloud solutions can be developed super-quickly using the service because it can simultaneously upload your image to all the most popular hyperscalers - AWS, Google Cloud and Azure. You can read more about it in our [blog post](https://www.redhat.com/en/blog/announcing-full-support-new-red-hat-enterprise-linux-image-builder-service) announcing its general availability. In order to access it, you can use the no-cost developer subscription, we also have a [blog post](https://www.redhat.com/en/blog/using-no-cost-developer-subscription-new-red-hat-enterprise-linux-image-builder-hosted-service) about that. ![](https://i.imgur.com/gLEEVcP.png) ## Why would I want to use Image Builder programmatically? Although we made the graphical interface as easy to use as possible, if you are planning of making 10s, or even 1000s of images, the interface might become a hurdle. Fortunately, the service has an [API](https://console.redhat.com/docs/api/image-builder) that you can use to automate all your image building needs. ## Authentication Image Builder uses OAuth 2.0 for authorization. Firstly, you need to generate an offline token for Red Hat APIs on [this page](https://access.redhat.com/management/api). This token cannot be used directly with Image Builder. Secondly, you need to exchange it for an access token. You can do that simply using `curl`, just remember to save your offline to a variable named `OFFLINE_TOKEN` prior running this command: ``` $ curl --silent \ --request POST \ --data grant_type=refresh_token \ --data client_id=rhsm-api \ --data refresh_token=$OFFLINE_TOKEN \ https://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/token \ | jq . ``` When you run this command, it should output something like this: ``` { "access_token": "oiZjo1Mjhk...", "expires_in": 900, "refresh_expires_in": 0, "refresh_token": "eyJhbG...", "token_type": "bearer", "not-before-policy": 0, "session_state": "f0dbb8d4-4e4e-4654-844c-6f3704c84422", "scope": "offline_access" } ``` You can use `jq` to get the actual access token from the JSON payload and save it in a variable using the following snippet: ``` $ access_token=$( \ curl --silent \ --request POST \ --data grant_type=refresh_token \ --data client_id=rhsm-api \ --data refresh_token=$OFFLINE_TOKEN \ https://sso.redhat.com/auth/realms/redhat-external/protocol/openid-connect/token \ | jq -r .access_token \ ) ``` Note that the access token has an expiration time. If Image Builder returns an authorization error, just rerun the command to get a new one. More details about Red Hat APIs and OAuth can be found in [this article](https://access.redhat.com/articles/3626371). ## Getting the API documentation In order to build images, you will use the Image Builder API. Hybrid Console handily embeds documentation for all of its APIs, Image Builder's one is available on [this page](https://console.redhat.com/docs/api/image-builder). This blog post is oriented on the CLI though, so let's also introduce a simple `curl` command to retrieve the API documentation from the command line: ``` $ curl --silent \ --header "Authorization: Bearer $access_token" \ https://console.redhat.com/api/image-builder/v1/openapi.json \ | jq . ``` This command prints the API documentation in the form of OpenAPI 3 specification encoded in JSON. Red Hat's code is open and so is Image Builder which means that you can also get the specification in a YAML format from our [upstream repository](https://github.com/osbuild/image-builder/blob/main/internal/v1/api.yaml). ## Building a simple Guest Image Now, we are ready to actually start building some images. Let's start with something basic: Building an up-to-date RHEL 9.0 Guest Image for x86_64 CPU architecture that can be used with libvirt or in OpenStack. Firstly, we need to create a compose request: ``` $ cat >request.json <<END { "image_name": "My up-to-date guest image", "distribution": "rhel-90", "image_requests": [ { "architecture": "x86_64", "image_type": "guest-image", "upload_request": { "type": "aws.s3", "options": {} } } ] } END ``` The most important fields are the distribution, the CPU architecture and the image type. I set these to build a RHEL 9.0 x86_64 Guest image as promised. The upload request's type is set to `aws.s3` as required by the API. The image can be also named to your liking, this example names the image "My up-to-date guest image". Now that we have the request body prepared, we are ready to send a request to the Image Builder's API: ``` $ curl --silent \ --request POST \ --header "Authorization: Bearer $access_token" \ --header "Content-Type: application/json" \ --data @request.json \ https://console.redhat.com/api/image-builder/v1/compose ``` If everything went alright, you should see output similar to this one: ``` {"id":"fd4ecf3c-f0ce-43dd-9fcc-6ad11208b939"} ``` Since we are going to need the ID to check the status of the image build, I suggest putting it directly into a variable with a small `jq` helper: ``` $ compose_id=$( \ curl --silent \ --request POST \ --header "Authorization: Bearer $access_token" \ --header "Content-Type: application/json" \ --data @request.json \ https://console.redhat.com/api/image-builder/v1/compose \ | jq -r .id \ ) ``` If you now look in the Red Hat Hybrid Cloud Console, you can see that the image is indeed building: ![](https://i.imgur.com/UDLuFyU.png) Image builds take usually a few minutes, you can check the status using the following call: ``` $ curl \ --silent \ --header "Authorization: Bearer $access_token" \ "https://console.redhat.com/api/image-builder/v1/composes/$compose_id" \ | jq . ``` When you run this immediately after you created your compose, you should see the call output the following message: ``` { "image_status": { "status": "building" } } ``` After some time, the returned message will change to: ``` { "image_status": { "status": "success", "upload_status": { "options": { "url": "https://image-builder-service-production.s3.amazonaws.com/composer-api-766eed27-bfa8-4801-806b-ad01e16e5a22-disk.qcow2?e42..." }, "status": "success", "type": "aws.s3" } } } ``` Yay, your image is ready. It's time to download it using the following command: ``` $ curl --location -O \ https://image-builder-service-production.s3.amazonaws.com/composer-api-766eed27-bfa8-4801-806b-ad01e16e5a22-disk.qcow2?e42... ``` Now, you can run it locally using libvirt, or upload it to OpenStack. Note that the S3 link currently has an expiration time of 6 hours so don't be surprised if it's gone the next day. ## Building a customized AWS image The previous example was cool as it always gives you a fresh and up-to-date image. Let's try something more complex this time: Let's target AWS, add extra packages into the image, customize the partition layout and embed an activation key so you don't need to care about subscriptions. You should already know everything about authentication and the OpenAPI specification so let's skip directly to the request: ``` $ cat >request.json <<EOF { "image_name": "My customized AMI", "distribution": "rhel-86", "image_requests": [ { "architecture": "x86_64", "image_type": "aws", "upload_request": { "type": "aws", "options": { "share_with_accounts": [ "438669297788" ] } } } ], "customizations": { "packages": [ "nginx" ], "filesystem": [ { "mountpoint": "/var", "min_size": 10737418240 } ], "subscription": { "organization": 123456789, "activation-key": "toucan", "server-url": "subscription.rhsm.redhat.com", "base-url": "http://cdn.redhat.com/", "insights": true } } } EOF ``` Let's go over the changes to the request: Firstly, the distribution was switched to RHEL 8.6 to showcase that RHEL 8.x is also supported. In the image request, the image type was changed to `aws` which is also reflected in the upload request. Hosted Image Builder uploads the images to Red Hat's AWS account and then it shares the image with you, so the `share_with_accounts` field needs to be filled in order to tell Image Builder with which account to share the image. Note that these images will go away after 14 days so if you want to use it for longer, you have to make a copy. In a comparison with the previous request, a big `customizations` object was added: - `nginx` will be preinstalled in the image - The root partition will be 4 GiB big. `/var` will be on a separate, 10GiB big partition. - Instances spun up from the image will be automatically subscribed using the given activation key. If you don't know how to create one, there's [an article](https://access.redhat.com/articles/1378093) about the process. Let's send the request: ``` $ compose_id=$( \ curl --silent \ --request POST \ --header "Authorization: Bearer $access_token" \ --header "Content-Type: application/json" \ --data @request.json \ https://console.redhat.com/api/image-builder/v1/compose \ | jq -r .id \ ) ``` and start checking its status: ``` $ curl --silent \ --header "Authorization: Bearer $access_token" \ "https://console.redhat.com/api/image-builder/v1/composes/$compose_id" \ | jq . ``` Once the image build is finished (it can take a bit longer as import to AWS tends to take few minutes), you should get the following response: ``` { "image_status": { "status": "success", "upload_status": { "options": { "ami": "ami-01f2c869485288e5e", "region": "us-east-1" }, "status": "success", "type": "aws" } } } ``` If you open the same image in the Red Hat Hybrid Cloud Console, you should see something like this: ![](https://i.imgur.com/5xCfkum.png) You can launch your new image using the link in the Console. This article is about the command line though, so let's use [AWS CLI](https://aws.amazon.com/cli/) to launch an instance and find its public IP address: ``` $ aws --region us-east-1 \ ec2 run-instances \ --image-id ami-01f2c869485288e5e \ --key-name KEY_NAME $ aws --region us-east-1 \ ec2 describe-instances \ --instance-ids INSTANCE_ID \ --query 'Reservations[*].Instances[*].PublicIpAddress' \ --output text 3.83.39.87 ``` When you ssh into the instance using `ssh ec2-user@3.83.39.87`, you can confirm that the instance has the requested disk layout, `nginx` is installed and new packages can be immediately installed because the machine is subscribed: ``` $ lsblk NAME MAJ:MIN RM SIZE RO TYPE MOUNTPOINT xvda 202:0 0 15G 0 disk |-xvda1 202:1 0 1M 0 part |-xvda2 202:2 0 14G 0 part | |-rootvg-rootlv 253:0 0 4G 0 lvm / | `-rootvg-varlv 253:1 0 10G 0 lvm /var `-xvda3 202:3 0 512M 0 part /boot xvdc 202:32 0 896M 0 disk [SWAP] $ rpm -q nginx nginx-1.14.1-9.module+el8.0.0+4108+af250afe.x86_64 $ sudo dnf install tmux Updating Subscription Management repositories. Red Hat Enterprise Linux 8 for x86_64 - BaseOS (RPMs) 6.7 MB/s | 47 MB 00:07 Red Hat Enterprise Linux 8 for x86_64 - AppStream (RPMs) 10 MB/s | 44 MB 00:04 Last metadata expiration check: 0:00:03 ago on Fri May 27 12:25:55 2022. Dependencies resolved. ======================================================================================================================= Package Architecture Version Repository Size ======================================================================================================================= Installing: tmux x86_64 2.7-1.el8 rhel-8-for-x86_64-baseos-rpms 317 k Transaction Summary ======================================================================================================================= Install 1 Package Total download size: 317 k Installed size: 770 k Is this ok [y/N]: ``` Note that this section about AWS CLI might not work for you if your default VPC, default subnet or default security group is set differently. ## Conclusion Hosted Image Builder can very simply be used via its API. You just need a few `curl` commands and you quickly get up-to-date and customizable RHEL images directly into a cloud of your choice. Start using it today at https://console.redhat.com/insights/image-builder/.

Import from clipboard

Paste your markdown or webpage here...

Advanced permission required

Your current role can only read. Ask the system administrator to acquire write and comment permission.

This team is disabled

Sorry, this team is disabled. You can't edit this note.

This note is locked

Sorry, only owner can edit this note.

Reach the limit

Sorry, you've reached the max length this note can be.
Please reduce the content or divide it to more notes, thank you!

Import from Gist

Import from Snippet

or

Export to Snippet

Are you sure?

Do you really want to delete this note?
All users will lose their connection.

Create a note from template

Create a note from template

Oops...
This template has been removed or transferred.
Upgrade
All
  • All
  • Team
No template.

Create a template

Upgrade

Delete template

Do you really want to delete this template?
Turn this template into a regular note and keep its content, versions, and comments.

This page need refresh

You have an incompatible client version.
Refresh to update.
New version available!
See releases notes here
Refresh to enjoy new features.
Your user state has changed.
Refresh to load new user state.

Sign in

Forgot password

or

By clicking below, you agree to our terms of service.

Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
Wallet ( )
Connect another wallet

New to HackMD? Sign up

Help

  • English
  • 中文
  • Français
  • Deutsch
  • 日本語
  • Español
  • Català
  • Ελληνικά
  • Português
  • italiano
  • Türkçe
  • Русский
  • Nederlands
  • hrvatski jezik
  • język polski
  • Українська
  • हिन्दी
  • svenska
  • Esperanto
  • dansk

Documents

Help & Tutorial

How to use Book mode

Slide Example

API Docs

Edit in VSCode

Install browser extension

Contacts

Feedback

Discord

Send us email

Resources

Releases

Pricing

Blog

Policy

Terms

Privacy

Cheatsheet

Syntax Example Reference
# Header Header 基本排版
- Unordered List
  • Unordered List
1. Ordered List
  1. Ordered List
- [ ] Todo List
  • Todo List
> Blockquote
Blockquote
**Bold font** Bold font
*Italics font* Italics font
~~Strikethrough~~ Strikethrough
19^th^ 19th
H~2~O H2O
++Inserted text++ Inserted text
==Marked text== Marked text
[link text](https:// "title") Link
![image alt](https:// "title") Image
`Code` Code 在筆記中貼入程式碼
```javascript
var i = 0;
```
var i = 0;
:smile: :smile: Emoji list
{%youtube youtube_id %} Externals
$L^aT_eX$ LaTeX
:::info
This is a alert area.
:::

This is a alert area.

Versions and GitHub Sync
Get Full History Access

  • Edit version name
  • Delete

revision author avatar     named on  

More Less

Note content is identical to the latest version.
Compare
    Choose a version
    No search result
    Version not found
Sign in to link this note to GitHub
Learn more
This note is not linked with GitHub
 

Feedback

Submission failed, please try again

Thanks for your support.

On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

Please give us some advice and help us improve HackMD.

 

Thanks for your feedback

Remove version name

Do you want to remove this version name and description?

Transfer ownership

Transfer to
    Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

      Link with GitHub

      Please authorize HackMD on GitHub
      • Please sign in to GitHub and install the HackMD app on your GitHub repo.
      • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
      Learn more  Sign in to GitHub

      Push the note to GitHub Push to GitHub Pull a file from GitHub

        Authorize again
       

      Choose which file to push to

      Select repo
      Refresh Authorize more repos
      Select branch
      Select file
      Select branch
      Choose version(s) to push
      • Save a new version and push
      • Choose from existing versions
      Include title and tags
      Available push count

      Pull from GitHub

       
      File from GitHub
      File from HackMD

      GitHub Link Settings

      File linked

      Linked by
      File path
      Last synced branch
      Available push count

      Danger Zone

      Unlink
      You will no longer receive notification when GitHub file changes after unlink.

      Syncing

      Push failed

      Push successfully