Skip to main content

openstack_cli_compute/v2/keypair/
delete.rs

1// Licensed under the Apache License, Version 2.0 (the "License");
2// you may not use this file except in compliance with the License.
3// You may obtain a copy of the License at
4//
5//     http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing, software
8// distributed under the License is distributed on an "AS IS" BASIS,
9// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10// See the License for the specific language governing permissions and
11// limitations under the License.
12//
13// SPDX-License-Identifier: Apache-2.0
14//
15// WARNING: This file is automatically generated from OpenAPI schema using
16// `openstack-codegenerator`.
17
18//! Delete Keypair command
19//!
20//! Wraps invoking of the `v2.1/os-keypairs/{id}` with `DELETE` method
21
22use clap::Args;
23use eyre::OptionExt;
24use tracing::info;
25
26use openstack_cli_core::cli::CliArgs;
27use openstack_cli_core::error::OpenStackCliError;
28use openstack_cli_core::output::OutputProcessor;
29use openstack_sdk::AsyncOpenStack;
30
31use openstack_sdk::api::QueryAsync;
32use openstack_sdk::api::compute::v2::keypair::delete;
33use openstack_sdk::api::find_by_name;
34use openstack_sdk::api::identity::v3::user::find as find_user;
35use tracing::warn;
36
37/// Deletes a keypair.
38///
39/// Normal response codes: 202, 204
40///
41/// Error response codes: unauthorized(401), forbidden(403), itemNotFound(404)
42#[derive(Args)]
43#[command(about = "Delete Keypair")]
44pub struct KeypairCommand {
45    /// Request Query parameters
46    #[command(flatten)]
47    query: QueryParameters,
48
49    /// Path parameters
50    #[command(flatten)]
51    path: PathParameters,
52}
53
54/// Query parameters
55#[derive(Args)]
56struct QueryParameters {
57    /// User resource for which the operation should be performed.
58    #[command(flatten)]
59    user: UserInput,
60}
61
62/// User input select group
63#[derive(Args)]
64#[group(required = false, multiple = false)]
65struct UserInput {
66    /// User Name.
67    #[arg(long, help_heading = "Path parameters", value_name = "USER_NAME")]
68    user_name: Option<String>,
69    /// User ID.
70    #[arg(long, help_heading = "Path parameters", value_name = "USER_ID")]
71    user_id: Option<String>,
72    /// Current authenticated user.
73    #[arg(long, help_heading = "Path parameters", action = clap::ArgAction::SetTrue)]
74    current_user: bool,
75}
76
77/// Path parameters
78#[derive(Args)]
79struct PathParameters {
80    /// id parameter for /v2.1/os-keypairs/{id} API
81    #[arg(
82        help_heading = "Path parameters",
83        id = "path_param_id",
84        value_name = "ID"
85    )]
86    id: String,
87}
88
89impl KeypairCommand {
90    /// Perform command action
91    pub async fn take_action<C: CliArgs>(
92        &self,
93        parsed_args: &C,
94        client: &mut AsyncOpenStack,
95    ) -> Result<(), OpenStackCliError> {
96        info!("Delete Keypair");
97
98        let op = OutputProcessor::from_args(parsed_args, Some("compute.keypair"), Some("delete"));
99        op.validate_args(parsed_args)?;
100
101        let mut ep_builder = delete::Request::builder();
102
103        ep_builder.id(&self.path.id);
104        // Set query parameters
105        if let Some(id) = &self.query.user.user_id {
106            // user_id is passed. No need to lookup
107            ep_builder.user_id(id);
108        } else if let Some(name) = &self.query.user.user_name {
109            // user_name is passed. Need to lookup resource
110            let mut sub_find_builder = find_user::Request::builder();
111            warn!(
112                "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."
113            );
114
115            sub_find_builder.id(name);
116            let find_ep = sub_find_builder
117                .build()
118                .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
119            let find_data: serde_json::Value = find_by_name(find_ep).query_async(client).await?;
120            // Try to extract resource id
121            match find_data.get("id") {
122                Some(val) => match val.as_str() {
123                    Some(id_str) => {
124                        ep_builder.user_id(id_str.to_owned());
125                    }
126                    None => {
127                        return Err(OpenStackCliError::ResourceAttributeNotString(
128                            serde_json::to_string(&val)?,
129                        ));
130                    }
131                },
132                None => {
133                    return Err(OpenStackCliError::ResourceAttributeMissing(
134                        "id".to_string(),
135                    ));
136                }
137            };
138        } else if self.query.user.current_user {
139            ep_builder.user_id(
140                client
141                    .get_auth_info()
142                    .ok_or_eyre("Cannot determine current authentication information")?
143                    .token
144                    .user
145                    .id,
146            );
147        }
148
149        let ep = ep_builder
150            .build()
151            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
152        openstack_sdk::api::ignore(ep).query_async(client).await?;
153        // Show command specific hints
154        op.show_command_hint()?;
155        Ok(())
156    }
157}