Skip to main content

openstack_cli_dns/v2/zone/nameserver/
list.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//! List Nameservers command
19//!
20//! Wraps invoking of the `v2/zones/{zone_id}/nameservers` with `GET` method
21
22use clap::Args;
23use tracing::info;
24
25use openstack_cli_core::cli::CliArgs;
26use openstack_cli_core::error::OpenStackCliError;
27use openstack_cli_core::output::OutputProcessor;
28use openstack_sdk::AsyncOpenStack;
29
30use openstack_sdk::api::QueryAsync;
31use openstack_sdk::api::dns::v2::zone::find as find_zone;
32use openstack_sdk::api::dns::v2::zone::nameserver::list;
33use openstack_sdk::api::find_by_name;
34use openstack_types::dns::v2::zone::nameserver::response;
35use tracing::warn;
36
37/// Show the nameservers for a zone
38#[derive(Args)]
39#[command(about = "Get the Name Servers for a Zone")]
40pub struct NameserversCommand {
41    /// Request Query parameters
42    #[command(flatten)]
43    query: QueryParameters,
44
45    /// Request Headers parameters
46    #[command(flatten)]
47    headers: HeaderParameters,
48
49    /// Path parameters
50    #[command(flatten)]
51    path: PathParameters,
52}
53
54/// Query parameters
55#[derive(Args)]
56struct QueryParameters {}
57
58/// Header parameters
59#[derive(Args)]
60struct HeaderParameters {
61    /// If enabled this will show results from all projects in Designate
62    #[arg(long)]
63    x_auth_all_projects: Option<bool>,
64
65    /// This allows a user to impersonate another project
66    #[arg(long)]
67    x_auth_sudo_project_id: Option<String>,
68}
69
70/// Path parameters
71#[derive(Args)]
72struct PathParameters {
73    /// Zone resource for which the operation should be performed.
74    #[command(flatten)]
75    zone: ZoneInput,
76}
77
78/// Zone input select group
79#[derive(Args)]
80#[group(required = true, multiple = false)]
81struct ZoneInput {
82    /// Zone Name.
83    #[arg(long, help_heading = "Path parameters", value_name = "ZONE_NAME")]
84    zone_name: Option<String>,
85    /// Zone ID.
86    #[arg(long, help_heading = "Path parameters", value_name = "ZONE_ID")]
87    zone_id: Option<String>,
88}
89
90impl NameserversCommand {
91    /// Perform command action
92    pub async fn take_action<C: CliArgs>(
93        &self,
94        parsed_args: &C,
95        client: &mut AsyncOpenStack,
96    ) -> Result<(), OpenStackCliError> {
97        info!("List Nameservers");
98
99        let op = OutputProcessor::from_args(parsed_args, Some("dns.zone/nameserver"), Some("list"));
100        op.validate_args(parsed_args)?;
101
102        let mut ep_builder = list::Request::builder();
103        // Set path parameters
104
105        // Process path parameter `zone_id`
106        if let Some(id) = &self.path.zone.zone_id {
107            // zone_id is passed. No need to lookup
108            ep_builder.zone_id(id);
109        } else if let Some(name) = &self.path.zone.zone_name {
110            // zone_name is passed. Need to lookup resource
111            let mut sub_find_builder = find_zone::Request::builder();
112            warn!(
113                "Querying zone by name (because of `--zone-name` parameter passed) may not be definite. This may fail in which case parameter `--zone-id` should be used instead."
114            );
115
116            sub_find_builder.id(name);
117            let find_ep = sub_find_builder
118                .build()
119                .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
120            let find_data: serde_json::Value = find_by_name(find_ep).query_async(client).await?;
121            // Try to extract resource id
122            match find_data.get("id") {
123                Some(val) => match val.as_str() {
124                    Some(id_str) => {
125                        ep_builder.zone_id(id_str.to_owned());
126                    }
127                    None => {
128                        return Err(OpenStackCliError::ResourceAttributeNotString(
129                            serde_json::to_string(&val)?,
130                        ));
131                    }
132                },
133                None => {
134                    return Err(OpenStackCliError::ResourceAttributeMissing(
135                        "id".to_string(),
136                    ));
137                }
138            };
139        }
140
141        // Set header parameters
142        if let Some(val) = &self.headers.x_auth_all_projects {
143            ep_builder.header(
144                http::header::HeaderName::from_static("x-auth-all-projects"),
145                http::header::HeaderValue::from_static(if *val { "true" } else { "false" }),
146            );
147        }
148        if let Some(val) = &self.headers.x_auth_sudo_project_id {
149            ep_builder.header(
150                http::header::HeaderName::from_static("x-auth-sudo-project-id"),
151                http::header::HeaderValue::from_str(val)?,
152            );
153        }
154
155        let ep = ep_builder
156            .build()
157            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
158
159        let data: Vec<serde_json::Value> = ep.query_async(client).await?;
160
161        op.output_list::<response::list::NameserverResponse>(data.clone())?;
162        // Show command specific hints
163        op.show_command_hint()?;
164        Ok(())
165    }
166}