Skip to main content

openstack_cli_dns/v2/zone/recordset/
set.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//! Set Recordset command
19//!
20//! Wraps invoking of the `v2/zones/{zone_id}/recordsets/{recordset_id}` with `PUT` 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::recordset::find;
33use openstack_sdk::api::dns::v2::zone::recordset::set;
34use openstack_sdk::api::find;
35use openstack_sdk::api::find_by_name;
36use openstack_types::dns::v2::zone::recordset::response;
37use tracing::warn;
38
39/// Update a recordset
40#[derive(Args)]
41#[command(about = "Update a Recordset")]
42pub struct RecordsetCommand {
43    /// Request Query parameters
44    #[command(flatten)]
45    query: QueryParameters,
46
47    /// Path parameters
48    #[command(flatten)]
49    path: PathParameters,
50
51    /// Description for this recordset
52    #[arg(help_heading = "Body parameters", long)]
53    description: Option<String>,
54
55    /// A list of data for this recordset. Each item will be a separate record
56    /// in Designate These items should conform to the DNS spec for the record
57    /// type - e.g. A records must be IPv4 addresses, CNAME records must be a
58    /// hostname.
59    ///
60    /// Parameter is an array, may be provided multiple times.
61    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long)]
62    records: Option<Vec<String>>,
63
64    /// TTL (Time to Live) for the recordset.
65    #[arg(help_heading = "Body parameters", long)]
66    ttl: Option<i32>,
67}
68
69/// Query parameters
70#[derive(Args)]
71struct QueryParameters {}
72
73/// Path parameters
74#[derive(Args)]
75struct PathParameters {
76    /// recordset_id parameter for
77    /// /v2/zones/{zone_id}/recordsets/{recordset_id} API
78    #[arg(
79        help_heading = "Path parameters",
80        id = "path_param_id",
81        value_name = "ID"
82    )]
83    id: String,
84
85    /// Zone resource for which the operation should be performed.
86    #[command(flatten)]
87    zone: ZoneInput,
88}
89
90/// Zone input select group
91#[derive(Args)]
92#[group(required = true, multiple = false)]
93struct ZoneInput {
94    /// Zone Name.
95    #[arg(long, help_heading = "Path parameters", value_name = "ZONE_NAME")]
96    zone_name: Option<String>,
97    /// Zone ID.
98    #[arg(long, help_heading = "Path parameters", value_name = "ZONE_ID")]
99    zone_id: Option<String>,
100}
101
102impl RecordsetCommand {
103    /// Perform command action
104    pub async fn take_action<C: CliArgs>(
105        &self,
106        parsed_args: &C,
107        client: &mut AsyncOpenStack,
108    ) -> Result<(), OpenStackCliError> {
109        info!("Set Recordset");
110
111        let op = OutputProcessor::from_args(parsed_args, Some("dns.zone/recordset"), Some("set"));
112        op.validate_args(parsed_args)?;
113
114        let mut find_builder = find::Request::builder();
115
116        find_builder.id(&self.path.id);
117
118        // Process path parameter `zone_id`
119        if let Some(id) = &self.path.zone.zone_id {
120            // zone_id is passed. No need to lookup
121            find_builder.zone_id(id);
122        } else if let Some(name) = &self.path.zone.zone_name {
123            // zone_name is passed. Need to lookup resource
124            let mut sub_find_builder = find_zone::Request::builder();
125            warn!(
126                "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."
127            );
128
129            sub_find_builder.id(name);
130            let find_ep = sub_find_builder
131                .build()
132                .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
133            let find_data: serde_json::Value = find_by_name(find_ep).query_async(client).await?;
134            // Try to extract resource id
135            match find_data.get("id") {
136                Some(val) => match val.as_str() {
137                    Some(id_str) => {
138                        find_builder.zone_id(id_str.to_owned());
139                    }
140                    None => {
141                        return Err(OpenStackCliError::ResourceAttributeNotString(
142                            serde_json::to_string(&val)?,
143                        ));
144                    }
145                },
146                None => {
147                    return Err(OpenStackCliError::ResourceAttributeMissing(
148                        "id".to_string(),
149                    ));
150                }
151            };
152        }
153
154        let find_ep = find_builder
155            .build()
156            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
157        let find_data: serde_json::Value = find(find_ep).query_async(client).await?;
158
159        let mut ep_builder = set::Request::builder();
160
161        let resource_id = find_data["id"]
162            .as_str()
163            .ok_or_else(|| eyre::eyre!("resource ID must be a string"))?
164            .to_string();
165        ep_builder.id(resource_id.clone());
166
167        // Process path parameter `zone_id`
168        if let Some(id) = &self.path.zone.zone_id {
169            // zone_id is passed. No need to lookup
170            ep_builder.zone_id(id);
171        } else if let Some(name) = &self.path.zone.zone_name {
172            // zone_name is passed. Need to lookup resource
173            let mut sub_find_builder = find_zone::Request::builder();
174            warn!(
175                "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."
176            );
177
178            sub_find_builder.id(name);
179            let find_ep = sub_find_builder
180                .build()
181                .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
182            let find_data: serde_json::Value = find_by_name(find_ep).query_async(client).await?;
183            // Try to extract resource id
184            match find_data.get("id") {
185                Some(val) => match val.as_str() {
186                    Some(id_str) => {
187                        ep_builder.zone_id(id_str.to_owned());
188                    }
189                    None => {
190                        return Err(OpenStackCliError::ResourceAttributeNotString(
191                            serde_json::to_string(&val)?,
192                        ));
193                    }
194                },
195                None => {
196                    return Err(OpenStackCliError::ResourceAttributeMissing(
197                        "id".to_string(),
198                    ));
199                }
200            };
201        }
202
203        // Set body parameters
204        // Set Request.description data
205        if let Some(arg) = &self.description {
206            ep_builder.description(arg);
207        }
208
209        // Set Request.records data
210        if let Some(arg) = &self.records {
211            ep_builder.records(arg.iter().map(Into::into).collect::<Vec<_>>());
212        }
213
214        // Set Request.ttl data
215        if let Some(arg) = &self.ttl {
216            ep_builder.ttl(*arg);
217        }
218
219        let ep = ep_builder
220            .build()
221            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
222
223        let data: serde_json::Value = ep.query_async(client).await?;
224
225        op.output_single::<response::set::RecordsetResponse>(data.clone())?;
226        // Show command specific hints
227        op.show_command_hint()?;
228        Ok(())
229    }
230}