openstack_cli 0.13.5

OpenStack client rewritten in Rust
Documentation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
//
// WARNING: This file is automatically generated from OpenAPI schema using
// `openstack-codegenerator`.

//! Create Keypair command [microversion = 2.2]
//!
//! Wraps invoking of the `v2.1/os-keypairs` with `POST` method

use clap::Args;
use eyre::WrapErr;
use tracing::info;

use openstack_sdk::AsyncOpenStack;

use crate::Cli;
use crate::OpenStackCliError;
use crate::output::OutputProcessor;

use clap::ValueEnum;
use openstack_sdk::api::QueryAsync;
use openstack_sdk::api::compute::v2::keypair::create_22;
use openstack_types::compute::v2::keypair::response::create::KeypairResponse;

/// Imports (or generates) a keypair.
///
/// Normal response codes: 200, 201
///
/// Error response codes: badRequest(400), unauthorized(401), forbidden(403),
/// conflict(409)
#[derive(Args)]
#[command(about = "Import (or create) Keypair (microversion = 2.2)")]
pub struct KeypairCommand {
    /// Request Query parameters
    #[command(flatten)]
    query: QueryParameters,

    /// Path parameters
    #[command(flatten)]
    path: PathParameters,

    /// Keypair object
    #[command(flatten)]
    keypair: Keypair,
}

/// Query parameters
#[derive(Args)]
struct QueryParameters {}

/// Path parameters
#[derive(Args)]
struct PathParameters {}

#[derive(Clone, Eq, Ord, PartialEq, PartialOrd, ValueEnum)]
enum Type {
    Ssh,
    X509,
}

/// Keypair Body data
#[derive(Args, Clone)]
struct Keypair {
    /// A name for the keypair which will be used to reference it later.
    ///
    /// Note
    ///
    /// Since microversion 2.92, allowed characters are ASCII letters
    /// `[a-zA-Z]`, digits `[0-9]` and the following special characters:
    /// `[@._- ]`.
    #[arg(help_heading = "Body parameters", long)]
    name: String,

    /// The public ssh key to import. Was optional before microversion 2.92 :
    /// if you were omitting this value, a keypair was generated for you.
    #[arg(help_heading = "Body parameters", long)]
    public_key: Option<String>,

    /// The type of the keypair. Allowed values are `ssh` or `x509`.
    ///
    /// **New in version 2.2**
    #[arg(help_heading = "Body parameters", long)]
    _type: Option<Type>,
}

impl KeypairCommand {
    /// Perform command action
    pub async fn take_action(
        &self,
        parsed_args: &Cli,
        client: &mut AsyncOpenStack,
    ) -> Result<(), OpenStackCliError> {
        info!("Create Keypair");

        let op = OutputProcessor::from_args(parsed_args, Some("compute.keypair"), Some("create"));
        op.validate_args(parsed_args)?;

        let mut ep_builder = create_22::Request::builder();
        ep_builder.header(
            http::header::HeaderName::from_static("openstack-api-version"),
            http::header::HeaderValue::from_static("compute 2.2"),
        );

        // Set body parameters
        // Set Request.keypair data
        let args = &self.keypair;
        let mut keypair_builder = create_22::KeypairBuilder::default();

        keypair_builder.name(&args.name);

        if let Some(val) = &args.public_key {
            keypair_builder.public_key(val);
        }

        if let Some(val) = &args._type {
            let tmp = match val {
                Type::Ssh => create_22::Type::Ssh,
                Type::X509 => create_22::Type::X509,
            };
            keypair_builder._type(tmp);
        }

        ep_builder.keypair(
            keypair_builder
                .build()
                .wrap_err("error preparing the request data")?,
        );

        let ep = ep_builder
            .build()
            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;

        let data = ep.query_async(client).await?;
        op.output_single::<KeypairResponse>(data)?;
        // Show command specific hints
        op.show_command_hint()?;
        Ok(())
    }
}