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 ApplicationCredential command
//!
//! Wraps invoking of the `v3/users/{user_id}/application_credentials` with `POST` method

use clap::Args;
use eyre::{OptionExt, WrapErr};
use tracing::info;

use openstack_sdk::AsyncOpenStack;

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

use openstack_sdk::api::QueryAsync;
use openstack_sdk::api::find_by_name;
use openstack_sdk::api::identity::v3::user::application_credential::create;
use openstack_sdk::api::identity::v3::user::find as find_user;
use openstack_types::identity::v3::user::application_credential::response::create::ApplicationCredentialResponse;
use serde_json::Value;
use tracing::warn;

/// Creates an application credential for a user on the project to which the
/// current token is scoped.
///
/// Relationship:
/// `https://docs.openstack.org/api/openstack-identity/3/rel/application_credentials`
#[derive(Args)]
#[command(about = "Create application credential")]
pub struct ApplicationCredentialCommand {
    /// Request Query parameters
    #[command(flatten)]
    query: QueryParameters,

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

    /// An application credential object.
    #[command(flatten)]
    application_credential: ApplicationCredential,
}

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

/// Path parameters
#[derive(Args)]
struct PathParameters {
    /// User resource for which the operation should be performed.
    #[command(flatten)]
    user: UserInput,
}

/// User input select group
#[derive(Args)]
#[group(required = true, multiple = false)]
struct UserInput {
    /// User Name.
    #[arg(long, help_heading = "Path parameters", value_name = "USER_NAME")]
    user_name: Option<String>,
    /// User ID.
    #[arg(long, help_heading = "Path parameters", value_name = "USER_ID")]
    user_id: Option<String>,
    /// Current authenticated user.
    #[arg(long, help_heading = "Path parameters", action = clap::ArgAction::SetTrue)]
    current_user: bool,
}
/// ApplicationCredential Body data
#[derive(Args, Clone)]
struct ApplicationCredential {
    /// A list of `access_rules` objects
    ///
    /// Parameter is an array, may be provided multiple times.
    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long, value_name="JSON", value_parser=crate::common::parse_json)]
    access_rules: Option<Vec<Value>>,

    /// A description of the application credential’s purpose.
    #[arg(help_heading = "Body parameters", long)]
    description: Option<String>,

    /// Set explicit NULL for the description
    #[arg(help_heading = "Body parameters", long, action = clap::ArgAction::SetTrue, conflicts_with = "description")]
    no_description: bool,

    /// An optional expiry time for the application credential. If unset, the
    /// application credential does not expire.
    #[arg(help_heading = "Body parameters", long)]
    expires_at: Option<String>,

    /// Set explicit NULL for the expires_at
    #[arg(help_heading = "Body parameters", long, action = clap::ArgAction::SetTrue, conflicts_with = "expires_at")]
    no_expires_at: bool,

    /// The UUID for the credential.
    #[arg(help_heading = "Body parameters", long)]
    id: Option<String>,

    /// The name of the application credential. Must be unique to a user.
    #[arg(help_heading = "Body parameters", long)]
    name: String,

    /// The ID of the project the application credential was created for and
    /// that authentication requests using this application credential will be
    /// scoped to.
    #[arg(help_heading = "Body parameters", long)]
    project_id: Option<String>,

    /// An optional list of role objects, identified by ID or name. The list
    /// may only contain roles that the user has assigned on the project. If
    /// not provided, the roles assigned to the application credential will be
    /// the same as the roles in the current token.
    ///
    /// Parameter is an array, may be provided multiple times.
    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long, value_name="JSON", value_parser=crate::common::parse_json)]
    roles: Option<Vec<Value>>,

    /// The secret that the application credential will be created with. If not
    /// provided, one will be generated.
    #[arg(help_heading = "Body parameters", long)]
    secret: Option<String>,

    /// Set explicit NULL for the secret
    #[arg(help_heading = "Body parameters", long, action = clap::ArgAction::SetTrue, conflicts_with = "secret")]
    no_secret: bool,

    #[arg(help_heading = "Body parameters", long)]
    system: Option<String>,

    /// Set explicit NULL for the system
    #[arg(help_heading = "Body parameters", long, action = clap::ArgAction::SetTrue, conflicts_with = "system")]
    no_system: bool,

    /// An optional flag to restrict whether the application credential may be
    /// used for the creation or destruction of other application credentials
    /// or trusts. Defaults to false.
    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
    unrestricted: Option<Option<bool>>,
}

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

        let op = OutputProcessor::from_args(
            parsed_args,
            Some("identity.user/application_credential"),
            Some("create"),
        );
        op.validate_args(parsed_args)?;

        let mut ep_builder = create::Request::builder();

        // Process path parameter `user_id`
        if let Some(id) = &self.path.user.user_id {
            // user_id is passed. No need to lookup
            ep_builder.user_id(id);
        } else if let Some(name) = &self.path.user.user_name {
            // user_name is passed. Need to lookup resource
            let mut sub_find_builder = find_user::Request::builder();
            warn!(
                "Querying user by name (because of `--user-name` parameter passed) may not be definite. This may fail in which case parameter `--user-id` should be used instead."
            );

            sub_find_builder.id(name);
            let find_ep = sub_find_builder
                .build()
                .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
            let find_data: serde_json::Value = find_by_name(find_ep).query_async(client).await?;
            // Try to extract resource id
            match find_data.get("id") {
                Some(val) => match val.as_str() {
                    Some(id_str) => {
                        ep_builder.user_id(id_str.to_owned());
                    }
                    None => {
                        return Err(OpenStackCliError::ResourceAttributeNotString(
                            serde_json::to_string(&val)?,
                        ));
                    }
                },
                None => {
                    return Err(OpenStackCliError::ResourceAttributeMissing(
                        "id".to_string(),
                    ));
                }
            };
        } else if self.path.user.current_user {
            ep_builder.user_id(
                client
                    .get_auth_info()
                    .ok_or_eyre("Cannot determine current authentication information")?
                    .token
                    .user
                    .id,
            );
        }

        // Set body parameters
        // Set Request.application_credential data
        let args = &self.application_credential;
        let mut application_credential_builder = create::ApplicationCredentialBuilder::default();
        if let Some(val) = &args.access_rules {
            let access_rules_builder: Vec<create::AccessRules> = val
                .iter()
                .flat_map(|v| serde_json::from_value::<create::AccessRules>(v.to_owned()))
                .collect::<Vec<create::AccessRules>>();
            application_credential_builder.access_rules(access_rules_builder);
        }

        if let Some(val) = &args.description {
            application_credential_builder.description(Some(val.into()));
        } else if args.no_description {
            application_credential_builder.description(None);
        }

        if let Some(val) = &args.expires_at {
            application_credential_builder.expires_at(Some(val.into()));
        } else if args.no_expires_at {
            application_credential_builder.expires_at(None);
        }

        if let Some(val) = &args.id {
            application_credential_builder.id(val);
        }

        application_credential_builder.name(&args.name);

        if let Some(val) = &args.project_id {
            application_credential_builder.project_id(val);
        }

        if let Some(val) = &args.roles {
            let roles_builder: Vec<create::Roles> = val
                .iter()
                .flat_map(|v| serde_json::from_value::<create::Roles>(v.to_owned()))
                .collect::<Vec<create::Roles>>();
            application_credential_builder.roles(roles_builder);
        }

        if let Some(val) = &args.secret {
            application_credential_builder.secret(Some(val.into()));
        } else if args.no_secret {
            application_credential_builder.secret(None);
        }

        if let Some(val) = &args.system {
            application_credential_builder.system(Some(val.into()));
        } else if args.no_system {
            application_credential_builder.system(None);
        }

        if let Some(val) = &args.unrestricted {
            application_credential_builder.unrestricted(*val);
        }

        ep_builder.application_credential(
            application_credential_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::<ApplicationCredentialResponse>(data)?;
        // Show command specific hints
        op.show_command_hint()?;
        Ok(())
    }
}