Skip to main content

openstack_cli_network/v2/subnet/
create.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//! Create Subnet command
19//!
20//! Wraps invoking of the `v2.0/subnets` with `POST` method
21
22use clap::Args;
23use eyre::WrapErr;
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 clap::ValueEnum;
32use openstack_sdk::api::QueryAsync;
33use openstack_sdk::api::network::v2::subnet::create;
34use openstack_types::network::v2::subnet::response;
35use serde_json::Value;
36
37/// Creates a subnet on a network.
38///
39/// OpenStack Networking does not try to derive the correct IP version from the
40/// CIDR. If you do not specify the `gateway_ip` attribute, OpenStack
41/// Networking allocates an address from the CIDR for the gateway for the
42/// subnet.
43///
44/// To specify a subnet without a gateway, set the `gateway_ip` attribute to
45/// `null` in the request body. If you do not specify the `allocation_pools`
46/// attribute, OpenStack Networking automatically allocates pools for covering
47/// all IP addresses in the CIDR, excluding the address reserved for the subnet
48/// gateway. Otherwise, you can explicitly specify allocation pools as shown in
49/// the following example.
50///
51/// When you specify both the `allocation_pools` and `gateway_ip` attributes,
52/// you must ensure that the gateway IP does not overlap with the allocation
53/// pools; otherwise, the call returns the `Conflict (409)` response code.
54///
55/// A subnet can have one or more name servers and host routes. Hosts in this
56/// subnet use the name servers. Devices with IP addresses from this subnet,
57/// not including the local subnet route, use the host routes.
58///
59/// Specify the `ipv6_ra_mode` and `ipv6_address_mode` attributes to create
60/// subnets that support IPv6 configurations, such as stateless address
61/// autoconfiguration (SLAAC), DHCPv6 stateful, and DHCPv6 stateless
62/// configurations.
63///
64/// A subnet can optionally be associated with a network segment when it is
65/// created by specifying the `segment_id` of a valid segment on the specified
66/// network. A network with subnets associated in this way is called a routed
67/// network. On any given network, all of the subnets must be associated with
68/// segments or none of them can be. Neutron enforces this invariant.
69/// Currently, routed networks are only supported for provider networks.
70///
71/// Normal response codes: 201
72///
73/// Error response codes: 400, 401, 403, 404, 409
74#[derive(Args)]
75#[command(about = "Create subnet")]
76pub struct SubnetCommand {
77    /// Request Query parameters
78    #[command(flatten)]
79    query: QueryParameters,
80
81    /// Path parameters
82    #[command(flatten)]
83    path: PathParameters,
84
85    /// A `subnet` object.
86    #[command(flatten)]
87    subnet: Subnet,
88}
89
90/// Query parameters
91#[derive(Args)]
92struct QueryParameters {}
93
94/// Path parameters
95#[derive(Args)]
96struct PathParameters {}
97
98#[derive(Clone, Eq, Ord, PartialEq, PartialOrd, ValueEnum)]
99enum Ipv6AddressMode {
100    Dhcpv6Stateful,
101    Dhcpv6Stateless,
102    Slaac,
103}
104
105#[derive(Clone, Eq, Ord, PartialEq, PartialOrd, ValueEnum)]
106enum Ipv6RaMode {
107    Dhcpv6Stateful,
108    Dhcpv6Stateless,
109    Slaac,
110}
111
112/// Subnet Body data
113#[derive(Args, Clone)]
114struct Subnet {
115    /// Allocation pools with `start` and `end` IP addresses for this subnet.
116    /// If allocation_pools are not specified, OpenStack Networking
117    /// automatically allocates pools for covering all IP addresses in the
118    /// CIDR, excluding the address reserved for the subnet gateway by default.
119    ///
120    /// Parameter is an array, may be provided multiple times.
121    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long, value_name="JSON", value_parser=openstack_cli_core::common::parse_json)]
122    allocation_pools: Option<Vec<Value>>,
123
124    /// The CIDR of the subnet.
125    #[arg(help_heading = "Body parameters", long)]
126    cidr: Option<String>,
127
128    /// Set explicit NULL for the cidr
129    #[arg(help_heading = "Body parameters", long, action = clap::ArgAction::SetTrue, conflicts_with = "cidr")]
130    no_cidr: bool,
131
132    /// A human-readable description for the resource. Default is an empty
133    /// string.
134    #[arg(help_heading = "Body parameters", long)]
135    description: Option<String>,
136
137    /// List of dns name servers associated with the subnet. Default is an
138    /// empty list.
139    ///
140    /// Parameter is an array, may be provided multiple times.
141    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long)]
142    dns_nameservers: Option<Vec<String>>,
143
144    /// Whether to publish DNS records for IPs from this subnet. Default is
145    /// `false`.
146    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
147    dns_publish_fixed_ip: Option<bool>,
148
149    /// Indicates whether dhcp is enabled or disabled for the subnet. Default
150    /// is `true`.
151    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
152    enable_dhcp: Option<bool>,
153
154    /// Gateway IP of this subnet. If the value is `null` that implies no
155    /// gateway is associated with the subnet. If the gateway_ip is not
156    /// specified, OpenStack Networking allocates an address from the CIDR for
157    /// the gateway for the subnet by default.
158    #[arg(help_heading = "Body parameters", long)]
159    gateway_ip: Option<String>,
160
161    /// Set explicit NULL for the gateway_ip
162    #[arg(help_heading = "Body parameters", long, action = clap::ArgAction::SetTrue, conflicts_with = "gateway_ip")]
163    no_gateway_ip: bool,
164
165    /// Additional routes for the subnet. A list of dictionaries with
166    /// `destination` and `nexthop` parameters. Default value is an empty list.
167    ///
168    /// Parameter is an array, may be provided multiple times.
169    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long, value_name="JSON", value_parser=openstack_cli_core::common::parse_json)]
170    host_routes: Option<Vec<Value>>,
171
172    /// The IP protocol version. Value is `4` or `6`.
173    #[arg(help_heading = "Body parameters", long)]
174    ip_version: i32,
175
176    /// The IPv6 address modes specifies mechanisms for assigning IP addresses.
177    /// Value is `slaac`, `dhcpv6-stateful`, `dhcpv6-stateless`.
178    #[arg(help_heading = "Body parameters", long)]
179    ipv6_address_mode: Option<Ipv6AddressMode>,
180
181    /// The IPv6 router advertisement specifies whether the networking service
182    /// should transmit ICMPv6 packets, for a subnet. Value is `slaac`,
183    /// `dhcpv6-stateful`, `dhcpv6-stateless`.
184    #[arg(help_heading = "Body parameters", long)]
185    ipv6_ra_mode: Option<Ipv6RaMode>,
186
187    /// Human-readable name of the resource. Default is an empty string.
188    #[arg(help_heading = "Body parameters", long)]
189    name: Option<String>,
190
191    /// The ID of the network to which the subnet belongs.
192    #[arg(help_heading = "Body parameters", long)]
193    network_id: String,
194
195    /// The prefix length to use for subnet allocation from a subnet pool. If
196    /// not specified, the `default_prefixlen` value of the subnet pool will be
197    /// used.
198    #[arg(help_heading = "Body parameters", long)]
199    prefixlen: Option<u32>,
200
201    /// The ID of a network segment the subnet is associated with. It is
202    /// available when `segment` extension is enabled.
203    #[arg(help_heading = "Body parameters", long)]
204    segment_id: Option<String>,
205
206    /// Set explicit NULL for the segment_id
207    #[arg(help_heading = "Body parameters", long, action = clap::ArgAction::SetTrue, conflicts_with = "segment_id")]
208    no_segment_id: bool,
209
210    /// The service types associated with the subnet.
211    ///
212    /// Parameter is an array, may be provided multiple times.
213    #[arg(action=clap::ArgAction::Append, help_heading = "Body parameters", long)]
214    service_types: Option<Vec<String>>,
215
216    /// The ID of the subnet pool associated with the subnet.
217    #[arg(help_heading = "Body parameters", long)]
218    subnetpool_id: Option<String>,
219
220    /// Set explicit NULL for the subnetpool_id
221    #[arg(help_heading = "Body parameters", long, action = clap::ArgAction::SetTrue, conflicts_with = "subnetpool_id")]
222    no_subnetpool_id: bool,
223
224    /// The ID of the project that owns the resource. Only administrative and
225    /// users with advsvc role can specify a project ID other than their own.
226    /// You cannot change this value through authorization policies.
227    #[arg(help_heading = "Body parameters", long)]
228    tenant_id: Option<String>,
229
230    /// Whether to allocate this subnet from the default subnet pool.
231    #[arg(action=clap::ArgAction::Set, help_heading = "Body parameters", long)]
232    use_default_subnetpool: Option<bool>,
233}
234
235impl SubnetCommand {
236    /// Perform command action
237    pub async fn take_action<C: CliArgs>(
238        &self,
239        parsed_args: &C,
240        client: &mut AsyncOpenStack,
241    ) -> Result<(), OpenStackCliError> {
242        info!("Create Subnet");
243
244        let op = OutputProcessor::from_args(parsed_args, Some("network.subnet"), Some("create"));
245        op.validate_args(parsed_args)?;
246
247        let mut ep_builder = create::Request::builder();
248
249        // Set body parameters
250        // Set Request.subnet data
251        let args = &self.subnet;
252        let mut subnet_builder = create::SubnetBuilder::default();
253        if let Some(val) = &args.allocation_pools {
254            let allocation_pools_builder: Vec<create::AllocationPools> = val
255                .iter()
256                .flat_map(|v| serde_json::from_value::<create::AllocationPools>(v.to_owned()))
257                .collect::<Vec<create::AllocationPools>>();
258            subnet_builder.allocation_pools(allocation_pools_builder);
259        }
260
261        if let Some(val) = &args.cidr {
262            subnet_builder.cidr(Some(val.into()));
263        } else if args.no_cidr {
264            subnet_builder.cidr(None);
265        }
266
267        if let Some(val) = &args.description {
268            subnet_builder.description(val);
269        }
270
271        if let Some(val) = &args.dns_nameservers {
272            subnet_builder.dns_nameservers(val.iter().map(Into::into).collect::<Vec<_>>());
273        }
274
275        if let Some(val) = &args.dns_publish_fixed_ip {
276            subnet_builder.dns_publish_fixed_ip(*val);
277        }
278
279        if let Some(val) = &args.enable_dhcp {
280            subnet_builder.enable_dhcp(*val);
281        }
282
283        if let Some(val) = &args.gateway_ip {
284            subnet_builder.gateway_ip(Some(val.into()));
285        } else if args.no_gateway_ip {
286            subnet_builder.gateway_ip(None);
287        }
288
289        if let Some(val) = &args.host_routes {
290            let host_routes_builder: Vec<create::HostRoutes> = val
291                .iter()
292                .flat_map(|v| serde_json::from_value::<create::HostRoutes>(v.to_owned()))
293                .collect::<Vec<create::HostRoutes>>();
294            subnet_builder.host_routes(host_routes_builder);
295        }
296
297        subnet_builder.ip_version(args.ip_version);
298
299        if let Some(val) = &args.ipv6_address_mode {
300            let tmp = match val {
301                Ipv6AddressMode::Dhcpv6Stateful => create::Ipv6AddressMode::Dhcpv6Stateful,
302                Ipv6AddressMode::Dhcpv6Stateless => create::Ipv6AddressMode::Dhcpv6Stateless,
303                Ipv6AddressMode::Slaac => create::Ipv6AddressMode::Slaac,
304            };
305            subnet_builder.ipv6_address_mode(tmp);
306        }
307
308        if let Some(val) = &args.ipv6_ra_mode {
309            let tmp = match val {
310                Ipv6RaMode::Dhcpv6Stateful => create::Ipv6RaMode::Dhcpv6Stateful,
311                Ipv6RaMode::Dhcpv6Stateless => create::Ipv6RaMode::Dhcpv6Stateless,
312                Ipv6RaMode::Slaac => create::Ipv6RaMode::Slaac,
313            };
314            subnet_builder.ipv6_ra_mode(tmp);
315        }
316
317        if let Some(val) = &args.name {
318            subnet_builder.name(val);
319        }
320
321        subnet_builder.network_id(&args.network_id);
322
323        if let Some(val) = &args.prefixlen {
324            subnet_builder.prefixlen(*val);
325        }
326
327        if let Some(val) = &args.segment_id {
328            subnet_builder.segment_id(Some(val.into()));
329        } else if args.no_segment_id {
330            subnet_builder.segment_id(None);
331        }
332
333        if let Some(val) = &args.service_types {
334            subnet_builder.service_types(val.iter().map(Into::into).collect::<Vec<_>>());
335        }
336
337        if let Some(val) = &args.subnetpool_id {
338            subnet_builder.subnetpool_id(Some(val.into()));
339        } else if args.no_subnetpool_id {
340            subnet_builder.subnetpool_id(None);
341        }
342
343        if let Some(val) = &args.tenant_id {
344            subnet_builder.tenant_id(val);
345        }
346
347        if let Some(val) = &args.use_default_subnetpool {
348            subnet_builder.use_default_subnetpool(*val);
349        }
350
351        ep_builder.subnet(
352            subnet_builder
353                .build()
354                .wrap_err("error preparing the request data")?,
355        );
356
357        let ep = ep_builder
358            .build()
359            .map_err(|x| OpenStackCliError::EndpointBuild(x.to_string()))?;
360
361        let data: serde_json::Value = ep.query_async(client).await?;
362
363        op.output_single::<response::create::SubnetResponse>(data.clone())?;
364        // Show command specific hints
365        op.show_command_hint()?;
366        Ok(())
367    }
368}