sdkclient

package module
v0.9.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 26, 2026 License: MIT Imports: 23 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

awslim

awslim is a CLI for AWS services by Go. This CLI is generated from the AWS SDK Go v2 service client.

(The old name is aws-sdk-client-go.)

Motivation

While the AWS CLI is very useful, it can be resource intensive to boot up. awslim offers a simpler and faster alternative for limited use cases. It acts as a simple wrapper around AWS SDK Go v2, providing essential functionality without the full feature set of the AWS CLI.

Features
  • Call any method(API) of the AWS service client.
  • Use JSON or Jsonnet for input.
  • Output the result in JSON format.
  • Bind a file to the input/output struct of the method.
  • Query the output by JMESPath.
  • Use the AWS CLI configuration file. (i.e., ~/.aws/config)
Limitations
  • Not 100% compatible with the AWS CLI.
  • No support for AWS CLI plugins. (i.e., session-manager-plugin)
  • Some service names and different from the AWS CLI. (i.e., logs -> cloudwatchlogs, ce -> costexplorer)

Installation

Note: The release binaries are large (about 640MB after being extracted) and have a slight startup delay (about 100ms), due to the inclusion of code to access all AWS services. However, it is still faster than the AWS CLI.

For optimized performance, build your own binary tailored to the specific services you need. See the Build section for details.

Release binary

Download the binary from the release page.

Homebrew
$ brew install fujiwara/tap/awslim

Build

You can build the client yourself, including only the needed services and methods. This produces a smaller, faster binary.

The client is built by using a AWSLIM_GEN environment variable or a gen.yaml configuration file.

AWSLIM_GEN environment variable

Set the AWSLIM_GEN environment variable to specify the services you want to include, separated by commas.

For example, to build the client for ECS, Firehose, and S3:

$ export AWSLIM_GEN="ecs,firehose,s3"

This will generate all methods for the specified services. If you want to generate only specific methods, use the gen.yaml configuration file.

gen.yaml configuration file
# gen.yaml
services:
  ecs:
    - DescribeClusters
    - DescribeTasks
  firehose:
    - DescribeDeliveryStream
    - ListDeliveryStreams
  s3:
    # all methods of the service

Keys under services are AWS service names (github.com/aws/aws-sdk-go-v2/service/*), and values are method names of the service client (for example, s3 is s3.Client). If you don't specify the method names, all methods of the service client are generated.

Pin the version of the service SDK

By default, the latest version of each service module (github.com/aws/aws-sdk-go-v2/service/*) is fetched by go get when the service is not yet in go.mod. To use a specific version, append @version to the service name. The version is passed to go get as is, so any module query (v1.100.0, latest, etc.) is accepted.

# gen.yaml
services:
  ecs@v1.70.0:
    - DescribeClusters
  s3@v1.100.0:
$ export AWSLIM_GEN="ecs@v1.70.0,s3@v1.100.0,firehose"

Note that go get may also update shared modules (such as github.com/aws/aws-sdk-go-v2) to satisfy the requirements of the specified version. You can check the embedded versions with awslim -v <service> or awslim --sdk-versions.

Binary size

The binary size is dominated by the SDK code for each API (request serializers and response deserializers), so it grows roughly in proportion to the number of methods included. Methods that are not listed in gen.yaml are removed by the Go linker.

Examples (linux/amd64):

Services Size
sts only (baseline) 16MB
ec2 with 2 methods 17MB
ec2 with all methods 46MB
All services (423) 642MB

To get a small binary, list only the methods you need in gen.yaml. Note that a large binary does not start noticeably slower, since only the pages actually used are loaded; the cost of a large binary is download and disk space.

Build binary for specified OS/Architecture

Set the AWSLIM_OS and AWSLIM_ARCH environment variables to specify the OS and architecture for the build. If these variables are not set, awslim will build based on the architecture of the build environment. These variables can also be specified when building with Docker. The values that can be set for AWSLIM_OS and AWSLIM_ARCH are the same as for GOOS and GOARCH.

Build on your machine

To build the client, run the following commands (or simply run make):

$ go generate ./cmd/awslim-gen .
$ go build -o your-client ./cmd/awslim/main.go
  1. go generate ./cmd/awslim-gen . generates the generator by gen.yaml.
  2. go build -o your-client ./cmd/awslim/main.go builds your client.

If you change the configuration, run make clean before make to purge the generated files.

Build with Docker

Use the ghcr.io/fujiwara/awslim:builder builder image to build the client inside a container.

Environment variables:

  • GIT_REF: Git reference to checkout the repository. Default is main. You can specify a branch, tag, or commit hash.

Example using the AWSLIM_GEN environment variable:

$ docker run -it -e AWSLIM_GEN=ecs,firehose,s3 ghcr.io/fujiwara/awslim:builder
...

Example to specify build for OS and Architecture:

$ docker run -it -e AWSLIM_GEN=ecs,firehose,s3 -e AWSLIM_OS=linux -e AWSLIM_ARCH=arm64 ghcr.io/fujiwara/awslim:builder
...

Example using the gen.yaml configuration file:

$ docker run -it -v $(pwd)/gen.yaml:/app/gen.yaml ghcr.io/fujiwara/awslim:builder
...
Completed. Please extract /app/awslim from this container!
For example, run the following command:
docker cp $(docker ps -lq):/app/awslim .

After the build is complete, copy the binary to your host machine with the docker cp command.

$ docker cp $(docker ps -lq):/app/awslim .
Docker Multi-stage build

It is also possible to use the ghcr.io/fujiwara/awslim:builder builder image in a multi-stage build.

Run ./build-in-docker.sh in the container to build the client. The built binary will be located in the /app directory. You can then copy it to the final image.

FROM ghcr.io/fujiwara/awslim:builder AS builder
ENV AWSLIM_GEN=ecs,firehose,s3
ENV GIT_REF=v0.7.0
RUN ./build-in-docker.sh

FROM debian:trixie-slim
COPY --from=builder /app/awslim /usr/local/bin/awslim

Performance comparison

Example of executing sts get-caller-identity on a Linux desktop (AMD Ryzen 7 255, 16 cores), measured with /usr/bin/time (median of 5 runs).

command CPU time(user, sys) Elapsed time(s) Max memory(MB) Size(MB)
aws 0.52 + 0.09 = 0.61 0.68 83.8 326
awslim(all) 0.08 + 0.07 = 0.15 0.14 171.2 642
awslim(40) 0.01 + 0.02 = 0.03 0.06 42.4 153
  • awslim(built for all 423 AWS services): 4.9x faster than aws
  • awslim(built for 40 AWS services): 11.3x faster than aws

aws-cli/2.34.28 Python/3.14.3, awslim v0.7.0. Elapsed time includes the network round trip to the STS API, so the difference in CPU time is more representative of the startup cost.

Usage

Usage: awslim [<service> [<method> [<input> [<args> ...]]]] [flags]

Arguments:
  [<service>]     service name
  [<method>]      method name
  [<input>]       input JSON/Jsonnet struct or filename
  [<args> ...]    additional flags/args

Flags:
  -h, --help                      Show context-sensitive help.
  -i, --input-stream=STRING       bind input filename or '-' to io.Reader field in the input struct
  -o, --output-stream=STRING      bind output filename or '-' to io.ReadCloser field in the output struct
      --[no-]api-output           output API response into stdout (stderr when --output-stream is '-')
  -r, --raw-output                output raw strings, not JSON texts
  -c, --compact                   compact JSON output
  -q, --query=STRING              JMESPath query to apply to output
      --ext-str=KEY=VALUE;...     external variables for Jsonnet
      --ext-code=KEY=VALUE;...    external code for Jsonnet
      --[no-]strict               strict input JSON unmarshaling
  -f, --follow-next=""            OutputField=InputField format. follow the next token.
      --camel                     convert keys to camelCase
  -C, --client-option=STRING      client options JSON/Jsonnet struct or filename (e.g. '{UsePathStyle: true}')
  -n, --dry-run                   dry-run mode
  -v, --version                   show version (with SDK version of the specified service)
      --sdk-versions              show versions of all embedded AWS SDK modules
      --debug                     turn on debug logging
  • service: AWS service name.
  • method: Method name of the service client.
  • input: JSON input for the method.

The output is JSON format.

Show versions

awslim -v shows the version of awslim and the core AWS SDK module (github.com/aws/aws-sdk-go-v2). When a service name is given, the version of that service's SDK module embedded in the binary is also shown.

$ awslim -v
awslim v0.7.0
aws-sdk-go-v2 v1.45.1

$ awslim -v s3
awslim v0.7.0
aws-sdk-go-v2 v1.45.1
aws-sdk-go-v2/service/s3 v1.109.1

awslim --sdk-versions lists the versions of all aws-sdk-go-v2 modules embedded in the binary.

All flags can also be set by environment variables prefixed with AWSLIM_ (e.g., AWSLIM_COMPACT=true, AWSLIM_CLIENT_OPTION='{"UsePathStyle":true}').

Example usage
Show supported services
$ awslim
Show methods of the service
$ awslim ecs
Call method of the service

The third argument is a JSON or Jsonnet input for the method. This can be omitted if the method requires no input ({} is passed implicitly).

$ awslim ecs ListTasks '{Cluster:"default"}'   # JSON

$ awslim ecs ListTasks '{Cluster:"default"}'   # Jsonnet

If the method name is "kebab-case", it automatically converts to "PascalCase" (i.e., list-tasks -> ListTasks).

$ awslim ecs list-tasks '{Cluster:"default"}'

In v0.3.0, flag arguments can be specified, like the AWS CLI!

$ awslim ecs list-tasks --cluster default

Note: Currently, flag arguments do not support setting non-string fields (array, object, number, and boolean). Use JSON or Jsonnet for such fields.

$ awslim ecs list-tasks '{MaxResults:10}' --cluster default

The third argument can be a filename that contains JSON or Jsonnet input.

$ awslim ecs list-tasks input.jsonnet

Note: By default, the input JSON is unmarshaled strictly. Unknown fields for the input struct in the input JSON cause an error. If you want to unmarshal the input JSON non-strictly, use --no-strict option.

Jsonnet functions

awslim supports Jsonnet functions for the input JSON.

$ awslim ecs list-tasks '{Cluster: _(0)}' foo

$ CLUSTER=foo awslim ecs list-tasks '{Cluster: env("CLUSTER","default")}'

$ CLUSTER=foo awslim ecs list-tasks '{Cluster: must_env("CLUSTER")}'
  • _(n) returns the n-th argument.
  • env(n, d) returns the environment variable n. If the environment variable is not set, it returns d.
  • must_env(n) returns the environment variable n. If the environment variable is not set, it causes an error.

When you specify the input JSON as a file, you must define the function in the Jsonnet file.

local _ = std.native('args');
local env = std.native('env');
local must_env = std.native('must_env');
{
  Cluster: _(0),
}
--ext-str and --ext-code options

Pass external variables to Jsonnet.

This is useful when you want to use variables in Jsonnet.

$ awslim ecs list-tasks my.jsonnet --ext-str Cluster=default
// my.jsonnet
{
  Cluster: std.extVar("Cluster"),
}
--input-stream (-i) option

Bind a file or stdin to the input struct.

$ awslim s3 put-object '{Bucket:"my-bucket",Key:"my.txt"}' --input-stream my.txt

s3#PutObjectInput has Body field of io.Reader. --input-stream option binds the file to the field.

When the input struct has only one field of io.Reader, awslim reads the file and binds it to the field automatically. (Currently, all SDK input structs have at most one io.Reader field.)

When the input struct has a "*Length" field for the size of the content, awslim sets the size of the content to the field automatically. For example, s3#PutObjectInput has ContentLength field.

If --input-stream is "-", awslim reads from stdin. In this case, awslim reads all contents into memory, so it is not suitable for large files. Consider using a file for large content.

--output-stream (-o) option

Bind the io.ReadCloser of the API output to a file or stdout.

$ awslim s3 get-object '{Bucket:"my-bucket",Key:"my.txt"}' --output-stream my.txt

s3#GetObjectOutput has Body field of io.ReadeCloser. --output-stream option binds the file to the field.

When the output struct has only one field of io.ReadCloser, awslim copies it to the file automatically. (Currently, all SDK output structs have at most one io.ReadCloser field.)

If --output-stream is "-", awslim writes into stdout. In this case, the result of the API is written to stderr instead of stdout, so the stream is not mixed with it. If you don't want to output the result, use --no-api-output.

$ awslim s3 get-object '{Bucket:"my-bucket",Key:"archive.tar.gz"}' -o - --no-api-output | tar -xz
--raw-output (-r) option

Output raw strings, not JSON texts.

This option is like jq -r.

--follow-next (-f) option

Set the output/input field name of the next token. This option is useful for paginated APIs.

For example, s3#ListObjectsV2Output has a NextContinuationToken field, and s3#ListObjectsV2Input has a ContinuationToken field. You can follow the next token by the following command.

{FieldInOutput}={FieldInInput} format is used for --follow-next option.

$ awslim s3 list-objects-v2 '{Bucket:"my-bucket"}' \
  --follow-next NextContinuationToken=ContinuationToken

If the same field name is used in the output and input, you can omit the input field name.

$ awslim ecs list-tasks '{Cluster:"default"}' \
  --follow-next NextToken
--camel option

Convert JSON keys to camelCase.

By default, the output JSON keys are the same as the SDK struct field names (equivalent to PascalCase).

In the JSON output produced by AWS CLI, the key naming conventions are either PascalCase or camelCase, determined by the service. For example, aws ecs uses camelCase, while aws lambda uses PascalCase.

If you want to convert the keys to camelCase, use the --camel option.

$ awslim ecs describe-clusters '{Clusters:["default"]}' --camel
{
  "clusters": [
    {
      "activeServicesCount": 1,
      "capacityProviders": [],
      "clusterArn": "arn:aws:ecs:ap-northeast-1:123456789012:cluster/default",
      "clusterName": "default",
      "defaultCapacityProviderStrategy": [],
      "pendingTasksCount": 0,
      "registeredContainerInstancesCount": 0,
      "runningTasksCount": 0,
      "settings": [],
      "statistics": [],
      "status": "ACTIVE",
      "tags": []
    }
  ],
  "failures": [],
  "resultMetadata": {}
}

This conversion is performed mechanically, so objects for which any key can be specified (such as the dockerLabels element in an ECS task definition) are also subject to conversion.

It is not guaranteed that the results will match those in the AWS CLI output.

--client-option (-C) option

--client-option sets the options of the service client (Options struct of the service package, e.g. s3.Options). The value is a JSON/Jsonnet struct or a filename, same as the input.

For example, to access an S3 compatible storage (e.g. MinIO) with path-style URLs:

$ awslim s3 list-objects-v2 '{Bucket: "mybucket"}' \
    -C '{UsePathStyle: true, BaseEndpoint: "http://localhost:9000"}'

The keys are the field names of the Options struct. Only fields which can be unmarshaled from JSON (e.g. bool, string, int) are supported. Fields of function or interface types (e.g. HTTPClient, EndpointResolverV2, APIOptions) cannot be set. Unknown fields cause an error unless --no-strict is specified.

The client options can also be defined per service in the runtime configuration file. Options specified by --client-option override the options in the configuration file.

Query output by JMESPath

Query the output by JMESPath like the AWS CLI.

$ awslim sts get-caller-identity --query 'Account'
"012345678901"

The query is applied to the JSON representation of the API response, so JMESPath functions (ends_with, sort_by, length, etc.) work with any field.

$ awslim s3 list-objects-v2 --bucket my-bucket --query "Contents[?ends_with(Key, '.meta')].Key"

When --camel is specified, the query is applied to the camelCase keys. Keys written in the query (e.g. multi-select hash) are output as is.

$ awslim ecs describe-clusters '{Clusters:["default"]}' --camel --query 'clusters[].clusterName'
Show help

Use the help argument to display the URL of the method's documentation. Since awslim is a simple wrapper for the AWS SDK Go v2 service client, its usage is the same as the SDK.

$ awslim ecs DescribeClusters help
See https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/service/ecs#Client.DescribeClusters
Runtime Configurations

awslim reads the configuration file (~/.config/awslim/config.(json|jsonnet|yaml|yml)). The configuration file can contain the following fields:

open: /usr/bin/open
aliases:
  whoami: sts get-caller-identity
  regions: ec2 describe-regions --query Regions[].RegionName
client_options:
  s3:
    UsePathStyle: true
    BaseEndpoint: http://localhost:9000
  • open: The command to open the URL to the documentation.
  • aliases: The alias of the cli arguments. For example, awslim whoami is equivalent to awslim sts get-caller-identity.
  • client_options: The default client options for each service. See --client-option.

XDG_CONFIG_HOME environment variable is used for the configuration file path. If XDG_CONFIG_HOME is not set, ~/.config is used.

LICENSE

MIT

Author

Fujiwara Shunichiro

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrDryRun = fmt.Errorf("dry-run mode")
View Source
var LogLevel = new(slog.LevelVar)
View Source
var Version = "v0.9.0"

Version is the version of awslim. Updated by tagpr, and overridden by -ldflags at build time.

Functions

func Run

func Run(ctx context.Context) error

func RuntimeConfigDir added in v0.2.0

func RuntimeConfigDir() string

func UnmarshalJSON

func UnmarshalJSON[T any](b []byte, v T, strict bool) error

Types

type Alias added in v0.2.0

type Alias string

func (Alias) Parse added in v0.2.0

func (a Alias) Parse() ([]string, error)

type CLI

type CLI struct {
	Service string   `arg:"" help:"service name" default:""`
	Method  string   `arg:"" help:"method name" default:""`
	Input   string   `arg:"" help:"input JSON/Jsonnet struct or filename" default:"{}"`
	Args    []string `arg:"" optional:"" help:"additional flags/args"`

	InputStream  string            `short:"i" help:"bind input filename or '-' to io.Reader field in the input struct"`
	OutputStream string            `short:"o" help:"bind output filename or '-' to io.ReadCloser field in the output struct"`
	APIOutput    bool              `help:"output API response into stdout (stderr when --output-stream is '-')" default:"true" negatable:""`
	RawOutput    bool              `short:"r" help:"output raw strings, not JSON texts"`
	Compact      bool              `short:"c" help:"compact JSON output"`
	Query        string            `short:"q" help:"JMESPath query to apply to output"`
	ExtStr       map[string]string `help:"external variables for Jsonnet"`
	ExtCode      map[string]string `help:"external code for Jsonnet"`
	Strict       bool              `name:"strict" help:"strict input JSON unmarshaling" default:"true" negatable:""`
	FollowNext   string            `short:"f" help:"OutputField=InputField format. follow the next token." default:""`
	CamelCase    bool              `name:"camel" help:"convert keys to camelCase"`
	ClientOption string            `short:"C" help:"client options JSON/Jsonnet struct or filename (e.g. '{UsePathStyle: true}')"`

	DryRun      bool `short:"n" help:"dry-run mode"`
	Version     bool `short:"v" help:"show version (with SDK version of the specified service)"`
	SDKVersions bool `name:"sdk-versions" help:"show versions of all embedded AWS SDK modules"`
	Debug       bool `help:"turn on debug logging"`
	// contains filtered or unexported fields
}

func NewCLI added in v0.3.0

func NewCLI(ctx context.Context, args []string) (*CLI, error)

func (*CLI) CallMethod

func (c *CLI) CallMethod(ctx context.Context) error

func (*CLI) Dispatch

func (c *CLI) Dispatch(ctx context.Context) error

func (*CLI) ListMethods

func (c *CLI) ListMethods(_ context.Context) error

func (*CLI) ListServices

func (c *CLI) ListServices(_ context.Context) error

func (*CLI) SetWriter

func (c *CLI) SetWriter(w io.Writer)

func (*CLI) ShowSDKVersions added in v0.7.1

func (c *CLI) ShowSDKVersions(_ context.Context) error

ShowSDKVersions prints versions of all aws-sdk-go-v2 modules embedded in the binary.

func (*CLI) ShowVersion added in v0.7.1

func (c *CLI) ShowVersion(_ context.Context) error

ShowVersion prints the version of awslim and the core AWS SDK. If a service is specified, the version of the service module is also printed.

type ClientMethod

type ClientMethod func(context.Context, *clientMethodParam) (any, error)

type RuntimeConfig added in v0.2.0

type RuntimeConfig struct {
	Open          string                    `json:"open" yaml:"open"`
	Aliases       map[string]Alias          `json:"aliases" yaml:"aliases"`
	ClientOptions map[string]map[string]any `json:"client_options" yaml:"client_options"`
}

Directories

Path Synopsis
cmd
awslim command
awslim-gen command
awslim-gen-gen command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址