0% found this document useful (0 votes)
8 views5 pages

D306 Code Snipets

The document provides C# code for creating a virtual machine (VM) in Azure, defining necessary resources such as a resource group, virtual network, subnet, network interface, and security group. It includes two examples: one for a basic VM setup and another that incorporates a public IP and network security group rules. Additionally, it contains an ARM template for detailed resource deployment and a bash script to create a service principal and run a container in Azure Container Instances.

Uploaded by

Eric Isberg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views5 pages

D306 Code Snipets

The document provides C# code for creating a virtual machine (VM) in Azure, defining necessary resources such as a resource group, virtual network, subnet, network interface, and security group. It includes two examples: one for a basic VM setup and another that incorporates a public IP and network security group rules. Additionally, it contains an ARM template for detailed resource deployment and a bash script to create a service principal and run a container in Azure Container Instances.

Uploaded by

Eric Isberg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

C# VM creation

using System;
using Microsoft.Azure.Management.Compute.Fluent;
using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;

namespace ch1_1_1
{
class Program
{
static void Main(string[] args)
{
var credentials =
SdkContext.AzureCredentialsFactory.FromFile("./azureauth.properties");
var azure =
Azure.Configure().WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials).WithDefaultSubscription();

var groupName = "az204-ResourceGroup";


var vmName = "az204VMTesting";
var location = Region.USWest2;
var vNetName = "az204VNET";
var vNetAddress = "172.16.0.0/16";
var subnetName = "az204Subnet";
var subnetAddress = "172.16.0.0/24";
var nicName = "az204NIC";
var adminUser = "azureadminuser";
var adminPassword = "Pa$$w0rd!2019";

var resourceGroup =
azure.ResourceGroups.Define(groupName).WithRegion(location).Create();
var network =
azure.Networks.Define(vNetName).WithRegion(location).WithExistingResourceGroup(grou
pName)
.WithAddressSpace(vNetAddress).WithSubnet(subnetName,
subnetAddress).Create();
var nic =
azure.NetworkInterfaces.Define(nicName).WithRegion(location).WithExistingResourceGr
oup(groupName)
.WithExistingPrimaryNetwork(network).WithSubnet(subnetName).WithPri
maryPrivateIPAddressDynamic().Create();

azure.VirtualMachines.Define(vmName).WithRegion(location).WithExistingResourceGroup
(groupName)
.WithExistingPrimaryNetworkInterface(nic).WithLatestWindowsImage("M
icrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter")
.WithAdminUsername(adminUser).WithAdminPassword(adminPassword).With
ComputerName(vmName)
.WithSize(VirtualMachineSizeTypes.StandardDS2V2).Create();
}
}
}
-
===================================================================================
===========================================================
//dotnet core 2.2
using System;
using Microsoft.Azure.Management.Compute.Fluent;
using Microsoft.Azure.Management.Compute.Fluent.Models;
using Microsoft.Azure.Management.Network.Fluent;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.Network.Fluent.Models;

namespace ch1_1_2
{
class Program
{
static void Main(string[] args)
{
var credentials =
SdkContext.AzureCredentialsFactory.FromFile("./azureauth.properties");
var azure = Azure.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic
)
.Authenticate(credentials)
.WithDefaultSubscription();

var groupName = "az204-ResourceGroup";


var vmName = "az204VMTesting";
var location = Region.USWest2;
var vNetName = "az204VNET";
var vNetAddress = "172.16.0.0/16";
var subnetName = "az204Subnet";
var subnetAddress = "172.16.0.0/24";
var nicName = "az204NIC";
var adminUser = "azureadminuser";
var adminPassword = "Pa$$w0rd!2019";
var publicIPName = "az204publicIP";
var nsgName = "az204VNET-NSG";

var resourceGroup = azure.ResourceGroups.Define(groupName)


.WithRegion(location)
.Create();

var network = azure.Networks.Define(vNetName)


.WithRegion(location)
.WithExistingResourceGroup(groupName)
.WithAddressSpace(vNetAddress)
.WithSubnet(subnetName, subnetAddress)
.Create();

var publicIP = azure.PublicIPAddresses.Define(publicIPName)


.WithRegion(location)
.WithExistingResourceGroup(groupN
ame)
.Create();

var nsg = azure.NetworkSecurityGroups.Define(nsgName)


.WithRegion(location)
.WithExistingResourceGroup(groupNa
me)
.Create();
nsg.Update()
.DefineRule("Allow-RDP")
.AllowInbound()
.FromAnyAddress()
.FromAnyPort()
.ToAnyAddress()
.ToPort(3389)
.WithProtocol(SecurityRuleProtocol.Tcp)
.WithPriority(100)
.WithDescription("Allow-RDP")
.Attach()
.Apply();

var nic = azure.NetworkInterfaces.Define(nicName)


.WithRegion(location)
.WithExistingResourceGroup(groupName)
.WithExistingPrimaryNetwork(network)
.WithSubnet(subnetName)
.WithPrimaryPrivateIPAddressDynamic()
.WithExistingPrimaryPublicIPAddress(pu
blicIP)
.WithExistingNetworkSecurityGroup(nsg)
.Create();

azure.VirtualMachines.Define(vmName)
.WithRegion(location)
.WithExistingResourceGroup(groupName)
.WithExistingPrimaryNetworkInterface(nic)
.WithLatestWindowsImage("MicrosoftWindowsServer",
"WindowsServer", "2012-R2-Datacenter")
.WithAdminUsername(adminUser)
.WithAdminPassword(adminPassword)
.WithComputerName(vmName)
.WithSize(VirtualMachineSizeTypes.StandardDS2V2)
.Create();
}
}
}
==-=--------------=-=-=-=-=-=-=-=-=-=--=-==--==--=-==-=-=--==--=-==-=-=--=-=-==-
=----------------------------------------------------------=-==-=--=

Detailed ARM

{
"$schema":
"https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"virtualNetworks_az204VNET_name": { "defaultValue": "az204demoVNET", "type":
"string" },
"networkInterfaces_az204NIC_name": { "defaultValue": "az204demoNIC", "type":
"string" },
"virtualMachines_az204VMTesting_name": { "defaultValue": "az204demoVM", "type":
"string" },
"subnets_az204Subnet_name": { "defaultValue": "az204demoSubnet", "type":
"string" },
"virtualMachines_az204VMTesting_id": { "defaultValue":
"[concat(parameters('virtualMachines_az204VMTesting_name'), '_OSDisk1_1')]",
"type": "string" },
"virtualMachines_adminUser": { "defaultValue": "azureadminuser", "type":
"string" },
"virtualMachines_adminpassword": { "defaultValue": "Pa$$w0rd", "type":
"securestring" }
},
"variables": {
"osDiskName": "_OSDisk1_1_39c654d89d88405e968db84b722002d1"
},
"resources": [
{
"type": "Microsoft.Compute/virtualMachines",
"name": "[parameters('virtualMachines_az204VMTesting_name')]",
"apiVersion": "2018-06-01",
"location": "westus2",
"properties": {
"hardwareProfile": { "vmSize": "Standard_DS2_v2" },
"storageProfile": {
"imageReference": { "publisher": "MicrosoftWindowsServer", "offer":
"WindowsServer", "sku": "2012-R2-Datacenter", "version": "latest" },
"osDisk": { "osType": "Windows", "name":
"[concat(parameters('virtualMachines_az204VMTesting_name'),
variables('osDiskName'))]", "createOption": "FromImage", "caching": "ReadWrite" }
},
"osProfile": { "computerName":
"[parameters('virtualMachines_az204VMTesting_name')]", "adminUsername":
"azureadminuser", "adminPassword": "Pa$$w0rd", "windowsConfiguration":
{ "provisionVMAgent": true, "enableAutomaticUpdates": true } },
"networkProfile": { "networkInterfaces": [ { "id":
"[resourceId('Microsoft.Network/networkInterfaces',
parameters('networkInterfaces_az204NIC_name'))]", "properties": { "primary": true }
} ] }
},
"dependsOn": [ "[resourceId('Microsoft.Network/networkInterfaces',
parameters('networkInterfaces_az204NIC_name'))]" ]
},
{
"type": "Microsoft.Network/networkInterfaces",
"name": "[parameters('networkInterfaces_az204NIC_name')]",
"apiVersion": "2018-10-01",
"location": "westus2",
"properties": {
"ipConfigurations": [ { "name": "primary", "properties":
{ "privateIPAllocationMethod": "Dynamic", "subnet": { "id":
"[resourceId('Microsoft.Network/virtualNetworks/subnets',
parameters('virtualNetworks_az204VNET_name'),
parameters('subnets_az204Subnet_name'))]" }, "primary": true,
"privateIPAddressVersion": "IPv4" } } ]
},
"dependsOn": [ "[resourceId('Microsoft.Network/virtualNetworks/subnets',
parameters('virtualNetworks_az204VNET_name'),
parameters('subnets_az204Subnet_name'))]" ]
},
{
"type": "Microsoft.Network/virtualNetworks",
"name": "[parameters('virtualNetworks_az204VNET_name')]",
"apiVersion": "2018-10-01",
"location": "westus2",
"properties": {
"addressSpace": { "addressPrefixes": [ "172.16.0.0/16" ] },
"subnets": [ { "name": "[parameters('subnets_az204Subnet_name')]",
"properties": { "addressPrefix": "172.16.0.0/24" } } ]
},
"dependsOn": []
},
{
"type": "Microsoft.Network/virtualNetworks/subnets",
"name": "[concat(parameters('virtualNetworks_az204VNET_name'), '/',
parameters('subnets_az204Subnet_name'))]",
"apiVersion": "2018-10-01",
"properties": { "addressPrefix": "172.16.0.0/24" },
"dependsOn": [ "[resourceId('Microsoft.Network/virtualNetworks',
parameters('virtualNetworks_az204VNET_name'))]" ]
}
]
}
=-=-=-==-=-=-==-=--==-=--==-=--==--=-=-==--==-
Script to Create Service Principal and Run Container:
bash
Copy code
#!/bin/bash
# Variable definitions
ACR_NAME=az204demo
SP_NAME=az204demo_sp
IMAGE_TAG=az204demo.azurecr.io/develop/foobar:latest
RESOURCE_GROUP=AKSdemo-RG
APP_NAME=foobar
APP_DNS_NAME=prueba

# Get the registry ID


ACR_ID=$(az acr show --name $ACR_NAME --query id --output tsv)
# Get the ACR login server
ACR_SERVER=$(az acr show --name $ACR_NAME --query loginServer --output tsv)
# Generate service principal password
echo "Generating Service Principal password"
SP_PASS=$(az ad sp create-for-rbac --name http://$SP_NAME --scopes $ACR_ID --role
acrpull --query password --output tsv)
# Get the App ID associated with the service principal
SP_ID=$(az ad sp show --id http://$SP_NAME --query appId --output tsv)
echo "Service principal ID: $SP_ID"
echo "Service principal password: $SP_PASS"
# Create the container in ACI
az container create --resource-group $RESOURCE_GROUP --name $APP_NAME --image
$IMAGE_TAG --cpu 1 --memory 1 --registry-login-server $ACR_SERVER --registry-
username $SP_ID --registry-password $SP_PASS --dns-name-label $APP_DNS_NAME --ports
80

You might also like