<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sachin Shinde on Medium]]></title>
        <description><![CDATA[Stories by Sachin Shinde on Medium]]></description>
        <link>https://medium.com/@sachin.d.shinde?source=rss-b01de00d59f1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*renRFa5cHHyL6bfHzD4PUQ.png</url>
            <title>Stories by Sachin Shinde on Medium</title>
            <link>https://medium.com/@sachin.d.shinde?source=rss-b01de00d59f1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 17:14:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sachin.d.shinde/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Azure Application Gateway — as Shared Service for multiple application team & manage it as IaC…]]></title>
            <link>https://medium.com/@sachin.d.shinde/azure-application-gateway-as-shared-service-for-multiple-application-team-manage-it-as-iac-8059dea90c1a?source=rss-b01de00d59f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8059dea90c1a</guid>
            <category><![CDATA[shared-services]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[azure-application-gateway]]></category>
            <category><![CDATA[azur]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Sachin Shinde]]></dc:creator>
            <pubDate>Mon, 02 May 2022 05:20:12 GMT</pubDate>
            <atom:updated>2022-05-02T05:20:12.921Z</atom:updated>
            <content:encoded><![CDATA[<h3>Azure Application Gateway — as Shared Service for multiple application team &amp; manage it as IaC through Terraform</h3><p>Azure Application Gateway (AGW) is a web traffic load balancer that enables you to manage traffic to your web applications, it works with Layer 7 traffic, and specifically with HTTP/S. It can make routing decisions based on additional attributes of an HTTP request, for example URI path or host headers. <strong><em>We will explore in this blog, why &amp; how you can use this as Shared Service in your organization (this is my personal opinion), and how to maintain/manage it via Terraform.</em></strong></p><p><strong><em>Azure Application Gateway</em></strong><br>Traditional Azure Load Balancers operate at the layer 4 TCP/UDP and route traffic based on source IP address and port, to a destination IP address and port.<br>Azure Application Gateway is a web traffic manager for your web applications (one or multiple) operate at the layer 7. With AGW, on top of load balancing your workloads, you can make routing decisions based on URI path or host headers. For example, you can route traffic based on the incoming URL. If /images are in the inbound URL, you can route traffic to a specific set of servers (or pool) configured for images. If /video is in the URL, that traffic is routed to another pool that’s optimized for videos processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*PcHhTEps2mnOcOVbVMSE2g.png" /></figure><p>It can be used to do TLS/SSL termination. TLS/SSL termination can be useful to allow unencrypted traffic between AGW and backend servers saving some of processing load needed to encrypt and decrypt said traffic. However, sometimes unencrypted communication to the servers is not acceptable because of security requirements, compliance requirements, or application may only accept a secure connection. In these situations, Application Gateway also supports end-to-end TLS/SSL encryption</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/597/1*8nLscH2QBtUHOoPFBa_24A.png" /></figure><p>It includes firewall called Web application firewall (WAF) that protects your workload from common exploits like SQL injection attacks or cross-site scripting attacks, to name a few.</p><p>Application Gateway is available in 3 flavor tier of SKU - Standard (v1), Standard_v2 &amp; WAF_v2 SKU. Existing features under the Standard SKU continue to be supported in the new v2 SKU, with new enhancements like<br><strong><em>Autoscaling, Zone redundancy, Static VIP, Header Rewrite , Key Vault Integration, Mutual Authentication(mTLS), AKS Ingress Controller, <br>Performance enhancements, Faster Deployment and update time</em></strong><em>.</em><br>See feature comparison between v1 SKU and v2 SKU <a href="https://docs.microsoft.com/en-us/azure/application-gateway/overview-v2#feature-comparison-between-v1-sku-and-v2-sku">here</a></p><blockquote><strong><em>Why share Application Gateway? </em></strong><br><strong>One reason is cost</strong>. As of Apr 30th, 2022 the lowest monthly price for Application Gateway with Web Application Firewall is ~$278 (31 days Fixed Gateway hours with 1 capacity unit) as per Azure Pricing Calculator <a href="https://azure.microsoft.com/en-in/pricing/calculator">here </a>. To get understanding on AGW pricing, see <a href="https://docs.microsoft.com/en-us/azure/application-gateway/understanding-pricing">here </a>.<br><strong>Other reason is dedicated subnet requirement</strong>. Within your virtual network, a dedicated subnet is required for the application gateway. You can have multiple instances of a given application gateway deployment in a subnet. You can also deploy other application gateways in the subnet. But you can’t deploy any other resource in the application gateway subnet. <br>Although a <strong><em>/24 subnet </em></strong>is not required per Application Gateway v2 SKU deployment, however it is highly recommended by Azure. This is to ensure that Application Gateway v2 has sufficient space for autoscaling expansion and maintenance upgrades.</blockquote><p><strong><em>Multiple Applications sharing one Application Gateway</em></strong><br>Azure Application Gateway uses one private and one public IP address on which it listens for traffic. Therefore if several applications share Application Gateway you need ensure your applications can be accessed via the same Application Gateway front-end port. Following are the options to allow multiple applications to be deployed and share the same port on Azure Application Gateway.</p><p><strong>Multi-site Hosting:</strong><br>Application Gateway configured with multi-site hosting determines the back-end pool that will serve the request received by AGW based on the value of Host header in http request.<br>To enable multi-site hosting configure multi-site listeners (rather than basic listeners) on application gateway. Essentially specify host that every listener will serve.</p><p><strong>Path-based routing rules:</strong><br>URL Path Based Routing allows you to route traffic to AGW back-end server pools based on URL Paths of the request</p><p><strong><em>Application Gateway Deployment via Terraform</em></strong><br>Deployment of AGW can be achieved by Terraform. If you are using single application per AGW, input configuration parameters will be less and its easy to manage and operate it. For deployment, you will create Terraform module and will split input parameters as below. Have a look at sample main.tf file of module <a href="https://github.com/sachinblogs/azure_app_gateway/blob/main/module_main.tf">here</a> to understand how this input parameters used.</p><pre>backend_address_pools = [],<br>backend_http_settings = [],<br>http_listeners = [],<br>basic_request_routing_rules = [],<br>path_based_request_routing_rules = [],<br>redirect_request_routing_rules = [],<br>redirect_configurations = [],<br>ssl_certificate_configs = [],<br>url_path_map_configs = [],<br>probe_configs = [],<br>rewrite_rule_sets = []</pre><p>However, when you use AGW as shared service for multiple application, providing input configuration parameters for all application will become cumbersome, difficult to maintain, and operate it. Any single input parameter should include requirement for that configuration from all multiple applications. Example, if you have 10 applications, your <em>“backend_address_pools”</em> input parameter should have configuration details for all 10 application backends. To overcome this challenge, we will take input file per application, which will be process and validated by wrapper code (in go language), merge into respective single input parameter, and will pass to Terraform module as <strong><em>tfvars.json</em></strong>. This approach, help you to formulate naming of rules, handle configuration error by validating references in rules and then merge it. You can write wrapper code in your choice of programming language. <a href="https://github.com/sachinblogs/azure_app_gateway/blob/main/tf_agw_wrapper_sample.go">Here </a>is snippet of <em>go </em>code for reference.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Ux7raowvS39AbmXNMIEQg.png" /></figure><p>With this, your Terraform module invocation code directory structure will be as below. Trusted root certificate and Rewrite rule set are global for AGW and not bound to specific application, hence need to be treated differently.</p><pre>.<br>├── configs              ==&gt; directory for application Config files<br>│   ├── app1_config.json<br>│   ├── app2_config.json<br>│   ├── rewrite_rule_set.json<br>├── cert                 ==&gt; directory for trusted root certs  <br>│   ├── root_cert1.crt<br>│   ├── root_cert2.crt<br>├── provider.tf<br>├── main.tf<br>├── build-pipeline.yaml  ==&gt;  include task for wrapper code<br>├── README.md<br>├── tf_agw_wrapper<br>└── variables.tf</pre><p>Each application config file will have</p><pre>{<br>    &quot;app_id&quot;: &quot;1234&quot;,<br>    &quot;env&quot; : &quot;qty&quot;,<br>    &quot;backend_address_pools&quot; : [],<br>    &quot;backend_http_settings&quot; : [],<br>    &quot;http_listeners&quot; : [],<br>    &quot;basic_request_routing_rules&quot; : [],<br>    &quot;path_based_request_routing_rules&quot; : [],<br>    &quot;redirect_request_routing_rules&quot; : [],<br>    &quot;redirect_configurations&quot; : [],<br>    &quot;ssl_certificate_configs&quot; : [],<br>    &quot;url_path_map_configs&quot; : [],<br>    &quot;probe_configs&quot; : []<br>}</pre><p>Here is sample application config input file. Complete input template is available <a href="https://github.com/sachinblogs/azure_app_gateway/blob/main/InputTemplate.json.sample">here</a> for reference</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b3d22d5eb856084925a4e6f4d060b5b/href">https://medium.com/media/0b3d22d5eb856084925a4e6f4d060b5b/href</a></iframe><p><strong><em>Managing listeners certificates in Azure Key Vault</em></strong><br>To enable TLS/SSL termination at AGW, we need to add TLS/SSL certificates to AGW listeners. TLS certificate should be in PFX format. Azure Key Vault is a service where we can store secrets, keys, certificates securely.</p><p>Application Gateway can read certificates from Key Vault and install them locally for TLS termination. For this, we need to create a user-assigned managed identity, assign it to AGW and give “Get” access on Key Vault. Application gateway keeps polling Key Vault for every 4 hours to check if any renewed version of the certificate is added or not. If Application gateway finds a renewed certificate then it automatically rotates the existing certificate.</p><p>Using this feature and integrating it in our code, removes storing this certificates in git repo. This also enable, individual team to maintain their own application certificate in their own Azure Key Vault. They only need to provide “Get” access on Key Vault to AGW use-assigned managed identity.</p><pre>&quot;http_listeners&quot; : [<br>        {<br>            &quot;name&quot; : &quot;demo2&quot;,                  <br>            &quot;frontend_port_number&quot; : 443,<br>            &quot;protocol&quot; : &quot;Https&quot; ,<br>            &quot;ssl_certificate_name&quot; : &quot;democrt1&quot;    <br>        }<br>    ],<br>&quot;ssl_certificate_configs&quot; : [<br>        {<br>            &quot;name&quot; : &quot;democrt1&quot;,   <br>            &quot;key_vault_secret_id&quot; : &quot;<a href="https://dummyvault1234.vault.azure.net/secrets/demo">https://dummyvault1234.vault.azure.net/secrets/demo</a>&quot;<br>        }<br>    ]</pre><p>Hope this blog help you to give an idea on how you can use Azure Application Gateway as Shared Service to reduce cost and maximize its usage within multiple application teams.</p><p>Note: My code snippet is available <a href="https://github.com/sachinblogs/azure_app_gateway">here </a>for reference. Please note this is not complete code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8059dea90c1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cloud Resource Labeling Strategy Using Terraform]]></title>
            <link>https://medium.com/@sachin.d.shinde/cloud-resource-labeling-strategy-using-terraform-bee51364b0fe?source=rss-b01de00d59f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/bee51364b0fe</guid>
            <category><![CDATA[labeling-strategy]]></category>
            <category><![CDATA[azure-tags]]></category>
            <category><![CDATA[gcp-labels]]></category>
            <category><![CDATA[terraform]]></category>
            <dc:creator><![CDATA[Sachin Shinde]]></dc:creator>
            <pubDate>Fri, 01 Oct 2021 07:35:59 GMT</pubDate>
            <atom:updated>2021-10-01T07:38:15.379Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Resource labeling</em></strong><em> is an incredibly useful yet often overlooked feature of most cloud computing platforms. Once created they let you manage your infrastructure more effectively by providing the ability to filter resources and perform tasks and actions based on nominated labeling values.</em></p><p>In Azure these are referred to as “Tags” whereas GCP refers to these as “Labels”</p><p><strong>Always use Labeling <br></strong>Resource without labels is a black box. Labels are not mandatory field when creating Azure/GCP resource so they are easily forgotten.<br>Having labels on a resource helps to:</p><ul><li>easily track how much specific resource costs in your billing data</li><li>have filtering and reporting on resource</li><li>formulate configuration action via configuration management tools post resource provisioning. Example in <a href="https://docs.saltproject.io/en/latest/">Salt Stack</a> , converting these into grains help to define action to take during resource configuration.</li></ul><p>The rules related to labels do differ between platforms so some thought needs to be put into the naming conventions</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72395a00803ceb582aad606770849bad/href">https://medium.com/media/72395a00803ceb582aad606770849bad/href</a></iframe><p>Please refer the respective cloud providers best practices to define your strategy <a href="https://cloud.google.com/compute/docs/labeling-resources">GCP Labeling</a> &amp; <a href="https://docs.microsoft.com/en-us/azure/cloud-adoption-framework/ready/azure-best-practices/resource-tagging">Azure Tagging</a></p><p>Here are some examples of widely used labels:<br> <em>Cost Center<br> Business Unit ID<br> Environment<br> Requestor/Owner<br> Creator<br> Maintainer<br> Data Classification<br> Creation Date</em></p><p>You may wondering why <strong><em>creation date !!!</em></strong><br>There are situations where you would like to know when a resource was created. Google do show this on Google Console when you select that resource. Unfortunately in Azure Portal, the properties blade of a resource doesn’t reveal the creation timestamp. If you want to find this, you need to use Azure REST API and its Pretty Time Consuming (<a href="https://www.azureblue.io/get-azure-resource-creation-timestamp/">see here</a>).</p><p><strong>Enforce Labeling</strong><br>Make sure to follow strict labeling guidelines and is part of your workflow, to always create them automatically via a script or enforce a labeling policy when creating resources.<br>In this era, Terraform (TF) is prefer choice to manage Infrastructure as Code (IaC) for provision resources in cloud providers. So I will describe here how you can define resource labeling strategy using Terraform in efficient way.</p><p><strong>Terraform Label Module (That Does… Nothing?)</strong><br>You can take labeling input while each resource getting provision using Terraform. But what if you have a dozen teams managing their own code? Soon each team will start using their own implementation and labeling standard will start deviating. So lets move resource labeling creation into separate Terraform module which<em> </em><strong><em>builds no resource,</em></strong> but it does return pre-formatted label output and each team will consume it, during resource provisioning as input.<br>Moving into as a separate module has below benefits:</p><ul><li>define labeling strategy as per cloud provider</li><li>validate input values provided for label by integrating with other echo system in your environment. i.e. business unit &amp; Cost Center validation</li><li>help to formulate resource naming convention to fulfill your DNS standards</li><li>save overall Terraform provision time, by validating and formatting input only once</li><li>use module output as valid input label for further resources creation</li></ul><p>You can even extend this module to have optional labels (as shown below) in addition to mandatory ones. This will give flexibility to accommodate extra labels as per individual teams requirement who want to consume this module.</p><p><strong>Terraform locals block<br></strong>Let’s talk about what the locals block is in Terraform, and how we can use it to provide this label data in a super-easy way for teams to access.</p><p>The locals block is a storage block that permits you to store data within terraform. It can use any function, so you can happily concat, combine, sort, filter, unique, etc. It can be great in modules to standardize naming or prepare any other often-used data.</p><p>Below is sample code from Google <em>labels </em>module. You can create similar module for Azure <em>tags</em></p><pre>locals {<br>  #Get current date<br>  cur_date = { cur_date = data.external.current_date.result.value }</pre><pre>  #Convert labels to lower case<br>  mandatory_lbls = { for key, value in var.mandatory : lower(key) =&gt;  lower(value) }<br>  optional_lbls = { for key, value in var.optional : lower(key) =&gt; lower(value) }<br>  <br>  #Check environment attribute provided<br>  envs = [ &quot;poc&quot;, &quot;dev&quot;, &quot;test&quot;, &quot;qa&quot; , &quot;prod&quot; ]<br>  input_env = lower(var.mandatory[&quot;environment&quot;])<br>  env_check_flg = contains(local.envs, local.input_env) == true ? true : false<br>  <br>  ....<br>  .... add your validation codes ...<br>  ....<br>  <br>  #Merge all labels to return after validation<br>  resource_labels = merge(local.cur_date,local.mandatory_lbls,local.optional_lbls)<br>}</pre><pre>#Retrun validated and pre-formatted labels from output.tf<br>output &quot;resource_labels&quot; {<br>  value = local.resource_labels<br>  description = &quot;Resource Labels&quot;<br>}</pre><p>It can store data in maps, or in lists, too — any data structure supported in terraform is supported in locals. This can be a huge help in standardizing naming, or tags, or anything else that is potentially computed or constructed based on input sent each time resources getting provisioned.</p><p><strong>Module Usage</strong><br>Below is example of Terraform (.tf) file for Google VM provisioning leveraging <em>labels</em> TF module</p><pre>module &quot;labels&quot; {<br>  source = &quot;<a href="https://url/">https://url</a>_of_terraform_registry/labels/google&quot;<br>  version = &quot;x.x.x&quot;  <br>  mandatory = {<br>    cost_center      = &quot;xx&quot;<br>    business_unit_id = &quot;xx&quot;<br>    environment      = &quot;prd&quot;<br>    requestor        = &quot;xyz&quot;<br>    creator          = &quot;abc&quot;<br>    maintainer       = &quot;Ops&quot;<br>    data_class       = &quot;xx&quot;<br>  } <br>  optional = {<br>    service_tier     = 1<br>    app_nm           = &quot;xx&quot;<br>  }<br>}</pre><pre>output &quot;resource_labels&quot; {<br>    value = module.labels.resource_labels<br>}</pre><pre>module &quot;gcp_linux_vm&quot; {<br>  source   = &quot;<a href="https://url_of_terraform_registry/labels/google">https://url_of_terraform_registry/linux_vm/google</a>&quot;<br>  version  = &quot;x.x.x&quot;<br>  labels   = module.labels.resource_labels<br>  image    = &quot;rhel-7-v20191210&quot;<br>  ..<br>  ..<br>}</pre><p>Using this approach, all resources which will get provision through Terraform will have consistent way of labeling in each cloud provider.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bee51364b0fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automate Inventory of Google Cloud Resources]]></title>
            <link>https://medium.com/@sachin.d.shinde/automate-inventory-of-google-cloud-resources-636bfd704146?source=rss-b01de00d59f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/636bfd704146</guid>
            <category><![CDATA[asset-inventory]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[automation]]></category>
            <dc:creator><![CDATA[Sachin Shinde]]></dc:creator>
            <pubDate>Mon, 11 May 2020 04:01:57 GMT</pubDate>
            <atom:updated>2020-05-11T04:01:57.149Z</atom:updated>
            <content:encoded><![CDATA[<h4>To visualize or policy enforcement, or meet compliance auditing requirement</h4><p><em>How to answer questions like, “How many total Compute Engine VMs is my company using?” “What is the percentage of our cloud resources growth compare to last month?” “What are all the IAM policies in my projects?” and “What changes have there been to my firewalls till today?”</em></p><p>As an organization with a large number of cloud resources to track and manage, it requires clarity and visibility into your Google Cloud Platform (GCP) resources, such as firewall rules, buckets, and VMs, and policies like IAM policies and org policies. But without a great inventory service, identifying resources and policies across hundreds or even thousands of projects is no trivial task. And, If you’re responsible for managing your organization’s cloud resources, you will have lots of questions as above.</p><p><strong>In the past getting answers to these questions were non-trivial. You had to write scripts to enumerate through hundreds of projects, thousands of VMs, and other types of resources.</strong></p><p>To answer this, Google is offering <a href="https://cloud.google.com/asset-inventory/docs/quickstart"><strong><em>Asset Inventory</em></strong></a><strong><em> </em></strong>service. With this service, you can either export all your inventory at a given point of time or export the full event change history of particular resources within a specific timeframe, to Big Query or Cloud Storage Bucket. Google Asset Inventory service supports most of the GCP assets, the full list can be found <a href="https://cloud.google.com/asset-inventory/docs/supported-asset-types"><strong><em>here</em></strong></a>. The exported data can then be used by automation tools for monitoring or policy enforcement or visualize it in a Data Studio or meet compliance auditing requirements.</p><blockquote>This blog will cover, how to automate the GCP resource inventory from all the projects to Big Query, using Azure DevOps pipeline and background Cloud Function, and its visualization in Data Studio.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*_SQMuM9-1f2DWBu315dTOA.png" /><figcaption>Inventory Pipeline Flow</figcaption></figure><p><strong>Note :-</strong> You can also export assets data to Big Query directly, but you do not have control over table schema created. Please see the schema mapping <a href="https://cloud.google.com/asset-inventory/docs/exporting-to-bigquery#bigquery_table_schema"><strong><em>here</em></strong></a>. If you are comfortable with writing complex queries, you can opt for this route as well.</p><p><strong>Prerequisites :-</strong></p><ul><li>Create Google Cloud Storage bucket in the project in which asset files will be pushed via the Asset Inventory service. Also, create Big Query Dataset which would hold process asset records by Cloud Function.</li><li>You can have two separate service accounts, one for Azure pipeline and another for Cloud Function. For simplicity, I use a single service account. This service account need ‘<em>cloudasset.viewer</em>’, ‘<em>browser</em>’ roles on each project from which asset inventory needs to pull.</li></ul><pre>#gcloud projects add-iam-policy-binding [prj nm] --role roles/cloudasset.viewer --member serviceAccount:<a href="/service/mailto:asset-export-srvact@slb-it-dataplatform-dev.iam.gserviceaccount.com">[</a>srv act nm]<br>#gcloud projects add-iam-policy-binding [prj nm] --role roles/browser --member serviceAccount:<a href="/service/mailto:asset-export-srvact@slb-it-dataplatform-dev.iam.gserviceaccount.com">[</a>srv act nm]</pre><ul><li>Enable ‘<em>cloudasset.googleapis.com</em>’ API on each project from which asset inventory needs to be a pull. Once asset API enabled, provide write permission to Goggle manage asset service account(<a href="/service/mailto:service-360290316647@gcp-sa-cloudasset.iam.gserviceaccount.com"><em>service-[project number]@gcp-sa-cloudasset.iam.gserviceaccount.com</em></a>) on the bucket, created above. Google uses this service account to trigger asset export and hence needs the write permission.</li></ul><pre>#gcloud services enable cloudasset.googleapis.com --project [prj nm]<br>#g_srv_act=`gcloud projects get-iam-policy [prj_nm]|grep gcp-sa-cloudasset.iam.gserviceaccount.com|awk &#39;{print $2}&#39;`<br>#gsutil iam ch ${g_srv_act}:objectAdmin gs://[bucket nm]</pre><ul><li>Provide service account used to deploy Cloud Function, ‘<em>monitoring.viewer</em>’ role on each project, if you want to incorporate code mention in my <a href="https://medium.com/@sachin.d.shinde/calculating-google-cloud-storage-bucket-size-82f485d8c390"><strong><em>previous blog</em></strong></a><strong> </strong>into Cloud Function to calculate Cloud Storage bucket size while processing storage asset record.</li></ul><p>Script <a href="https://github.com/sachinblogs/google-inventory/blob/master/set_iam_permission.sh"><strong><em>set_iam_permission.sh</em></strong></a> in a repository can be used for the same.</p><p><strong>Azure DevOps Pipeline :-</strong></p><p>Use <a href="https://github.com/sachinblogs/google-inventory/blob/master/asset_export_trigger.py"><strong><em>asset_export_trigger.py</em></strong></a> python code in your Azure DevOps pipeline with the service account JSON key file as an input parameter, to trigger asset export on a scheduled basis. The mention python code, loop through all projects in which the service account has permission to trigger asset export. The pipeline run will create asset files per project per resource type into bucket mention in code. Example — Compute Engine Instance resource asset entry will be in</p><pre><strong><em>gs://[bucknm]/[date]/[prjnm]/object_name_prefix/compute.googleapis.com/Instance/0</em></strong></pre><p>Sample o/p from bucket</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*jqwmxXwjEk4p-9zTeaU4cw.png" /><figcaption>Asset files structure in bucket</figcaption></figure><p><strong>Cloud Function :-</strong></p><p>Background Cloud Function get triggered on ‘<em>google.storage.object.finalize</em>’ event from each asset file (object) gets created in a bucket, by Auze DevOps pipeline. The sample single JSON record for compute resource type (i.e. Instance) will look like as shown in <a href="https://github.com/sachinblogs/google-inventory/blob/master/sample_compute_vm_record.txt"><strong><em>sample_compute_vm_record.txt</em></strong></a> file. The asset file will have multiple such record based on number of Instances in the project. You will add code in Cloud Function to process those resources assets file whose inventory you want to maintain.</p><p>Sample code mention in <a href="https://github.com/sachinblogs/google-inventory/blob/master/main.py"><strong><em>main.py</em></strong></a> of Cloud Function process Compute Instance and Cloud Storage Bucket resource asset files and capture required attributes from each record within those files. You may need to amend this code based on your use case and attributes you want to maintain for those resource types. Deploy Cloud Function as below, with Big Query Project and Dataset name as environment variables.</p><pre>gcloud functions deploy asset_inventory_trigger \<br>  --region [region] \<br>  --runtime python37 \<br>  --trigger-resource [bucket name] \<br>  --trigger-event google.storage.object.finalize \<br>  --entry-point gcs_inventory_trigger \<br>  --ingress-settings all \<br>  --service-account [srv act name]\<br>  --set-env-vars DATASET_NM=[name],DATASET_PROJECT=[prj name]<br>  --project [prj name]</pre><p>Once the Cloud Function process targeted resource type asset file, you will have records created along with the inventory date into Big Query “Dataset.Instances” table.</p><p><strong>Note:-</strong> You have to manually create required tables into Big Query Dataset, for each resource type you are going to process via Cloud Function with required schema(column) based on attributes you will be pulling from JSON record and want to maintain in inventory.</p><p><strong>Inventory Visualization :-</strong></p><p>Now you have all the data available in Big Query Dataset, to visualize it by creating the required dashboard in Data Studio. Create the required Data Sources connection to Big Query Dataset and use them in the report. Sample dashboard for references —</p><p><em>Project Summary Report</em> dashboard on resources such as Instances, Disks, CloudSQL, used in it as on selected inventory date. Network details such as VPC, Subnet in use by resources per project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/483/1*wjlZEHHR8EhM1NHuBBf0Ig.png" /><figcaption>Project Summary</figcaption></figure><p><em>Compute Engine Instance</em> dashboard can quickly give summary of OS version deployed on Project or Org level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*yqeHF-TJj9d8nXJhN7sgYg.png" /><figcaption>Compute Engine Instance Dashboard</figcaption></figure><p>You can also show the percentage change in the number of resources deployed compare to the last inventory period, as highlighted above.</p><p><em>Cloud Storage Bucket</em> dashboard can provide a summary of the total number of buckets base on Storage class per project or Org level, with the total usage of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*4MS5mDJ5f6ADUffhgo1oYQ.png" /><figcaption>Cloud Storage Bucket Dashboard</figcaption></figure><p>As you have all cloud resources data into Big Query with inventory date per record, you can take advantage of SQL Query to get the required information from it, taking full advantage of the query language.</p><p>I hope, you have now found a way to answer questions mention at the start of the blog.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=636bfd704146" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Calculating Google Cloud Storage Bucket Size]]></title>
            <link>https://medium.com/@sachin.d.shinde/calculating-google-cloud-storage-bucket-size-82f485d8c390?source=rss-b01de00d59f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/82f485d8c390</guid>
            <category><![CDATA[bucket]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[stackdriver-monitoring]]></category>
            <dc:creator><![CDATA[Sachin Shinde]]></dc:creator>
            <pubDate>Mon, 27 Apr 2020 04:45:00 GMT</pubDate>
            <atom:updated>2020-04-27T04:45:00.952Z</atom:updated>
            <content:encoded><![CDATA[<p><em>An inexpensive way to get Google Cloud Storage Bucket size using python code to read Stackdriver metrics.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*5GvpNDWSoIfrqaLXe0wwyw.png" /></figure><p>Most organizations choose Google Cloud Storage Buckets to fulfill their storage requirement because its highly durable object storage that scales to exabytes of data, different storage classes for different workloads with Object Lifecycle Management, and Optimize price for usage.</p><p>However, it is not easy to see how much data is present in these buckets as you start using this service over time. Tracking their usage becomes difficult as the number for projects and buckets increases over the period. Google provides various solutions to calculate bucket size based on your use case. These options are -<br><em> gsutil<br>Access logs and Storage logs<br>Stackdriver Monitoring Metrics</em></p><p><strong>Option 1 </strong>— gsutil<br>You could use gsutil du command to get the total space used by all of your objects in the bucket. This command calculates space usage by making object listing requests, which can take a long time for large buckets and can also be pretty expensive each time you run this command per bucket.The storage.objects.list operation is a Class A Operation e.g. the most expensive operation Cloud Storage has to offer. Refer to <a href="https://cloud.google.com/storage/pricing#operations-pricing">Operation Pricing details</a>. So if you have a use case of leveraging CLI, you can use this option with additional cost as mention above for operation. Find more options with this command <a href="https://cloud.google.com/storage/docs/gsutil/commands/du">here</a>.</p><p><strong>Option 2</strong> — Access logs and Storage logs<br>Cloud Storage offers access logs and storage logs in the form of CSV files that you can download and view. <em>Access logs</em> provide information for all of the requests made on a specified bucket and are created hourly. <em>Storage logs</em> provide information about the storage consumption of that bucket for the last day and are created daily. Please refer to <a href="https://cloud.google.com/storage/docs/access-logs">Access logs and Storage logs</a> documentation on how to configure and use this service. With this option, you have to provide additional resources like buckets and need to manage the Lifecycle of logs file generated from it.</p><p><strong>Option 3 </strong>— Stackdriver Monitoring Metrics<br>Cloud Stackdriver Monitoring measures bucket size once a day. You can use storage.googleapis.com/storage/total_bytes metric to get bucket size in Cloud Console. Please refer to <a href="https://cloud.google.com/storage/docs/getting-bucket-information#cloud-monitoring">Getting Bucket Information</a> on how to view this metric in Google Cloud Console. You can create a dashboard, track, and alert bucket usage accordingly.</p><blockquote>Google recommends using Cloud Monitoring over other options for measuring storage consumption. <a href="https://cloud.google.com/storage/docs/access-logs#use-monitoring">Reference</a></blockquote><p>Let’s say Option 3 is most suitable for your use case considering the pros and cons of other options. However, these metrics are retained by default only for 30 days and you want to track, and keep an inventory of all your buckets usage over a period. You may look for a programmatic way to pull this data and maintain it. Here is a small python code to achieve this.</p><p><strong>Prerequisites </strong>— Install google-cloud-monitoring python package and provide Monitoring Viewer role to account or service account which running this code, on the project in which bucket is hosted. Replace <em>buck_nm, buck_loc</em> and <em>project_nm</em> as per your use case.</p><pre>import os<br>from google.cloud import monitoring_v3</pre><pre>buck_nm = &#39;[bucket Name]&#39;<br>buck_loc = &#39;[bucket Location]&#39;<br>project_nm = &#39;[project Name]&#39;</pre><pre>client = monitoring_v3.MetricServiceClient()<br>project_name = client.project_path(project_nm)<br>interval = monitoring_v3.types.TimeInterval()<br>now = time.time()<br>interval.end_time.seconds = int(now)<br>interval.end_time.nanos = int(<br>                    (now - interval.end_time.seconds) * 10**9)<br>interval.start_time.seconds = int(now - 3600)<br>interval.start_time.nanos = interval.end_time.nanos<br>aggregation = monitoring_v3.types.Aggregation()<br>aggregation.alignment_period.seconds = 3600  <br>aggregation.per_series_aligner = (                    monitoring_v3.enums.Aggregation.Aligner.ALIGN_MEAN)</pre><pre>#Define filter base on resource<br>filter = &#39;resource.type = &quot;gcs_bucket&quot; AND resource.labels.bucket_name = \&quot;&#39;+buck_nm+&#39;\&quot; AND resource.labels.location = &#39;+buck_loc+&#39; AND resource.labels.project_id = &#39;+project_nm+&#39; AND metric.type = &quot;storage.googleapis.com/storage/total_bytes&quot;&#39;</pre><pre>results = client.list_time_series(<br>                    project_name,<br>                    filter,<br>                    interval,                 monitoring_v3.enums.ListTimeSeriesRequest.TimeSeriesView.FULL,<br>                    aggregation)<br>for result in results:<br>     buck_sz = result.points[0].value.double_value/(1024*1024)<br>print(&#39;Bucket {} size is {}Mb&#39;.format(buck_nm,buck_sz))</pre><p>I hope the above code is useful and suitable for your use case.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82f485d8c390" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker Compose in Container-Optimized OS]]></title>
            <link>https://medium.com/@sachin.d.shinde/docker-compose-in-container-optimized-os-159b12e3d117?source=rss-b01de00d59f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/159b12e3d117</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[docker-compose]]></category>
            <dc:creator><![CDATA[Sachin Shinde]]></dc:creator>
            <pubDate>Tue, 10 Dec 2019 06:34:09 GMT</pubDate>
            <atom:updated>2019-12-10T06:34:09.977Z</atom:updated>
            <content:encoded><![CDATA[<h4>Series 2: Google Container-Optimized OS (COS)</h4><p>In previous post, ‘<a href="https://medium.com/@sachin.d.shinde/secrets-management-in-container-optimized-os-3341d5a2ee79"><em>Secret Management in Container-Optimized OS</em></a>’, I covered simple scenario of running single container image in Compute Engine Instance (COS) and how to securely inject secrets into container using metadata startup script. Couple of things happen under the hood when you specify ‘<strong>create-with-container’ </strong>option to ‘<em>gcloud</em>’ command, authentication to Private Google Container Registry get managed and Stack Driver logging get enabled for container logs.</p><p>Creating an Instance with advanced scenario method enable us, to select a specific Container-Optimized OS image, to deploy multiple containers or to customized environment for container run such as using <strong>docker-compose</strong>. In this post, I will cover, how to achieve authentication with Private Google Container Registry and running multiple containers with their dependency set using docker-compose. We will achieve this during provision phase of Instance itself using metadata startup script though ‘<strong><em>cloud-init</em></strong>’.We covered startup script using ‘<strong>shell’</strong> approach in previous post, let’s explore ‘<em>cloud-init</em>’ approach as well. You can found more details about this tools here — <a href="https://cloudinit.readthedocs.io/en/latest/">https://cloudinit.readthedocs.io/en/latest/</a></p><h4>Authenticating with Private Google Container Registry</h4><p>Google has documented multiple ways to achieve this, some of them as below:</p><pre>##1. Using Service Account File ##<br>#cat keyfile.json | docker login -u _json_key --password-stdin <a href="https://[HOSTNAME">https://[HOSTNAME</a>]<br>OR <strong><br></strong>##2. Using default service account of Instance via gcloud ##<br>#gcloud auth print-access-token | docker login -u oauth2accesstoken --password-stdin <a href="https://[HOSTNAME]">https://[HOSTNAME]</a><br>where [HOSTNAME] is gcr.io, us.gcr.io, eu.gcr.io, or asia.gcr.io<br>OR<strong><br></strong>##3. Using default service account of Instance via CURL ##<br>#TOKEN=$(curl --silent --header  &quot;Metadata-Flavor: Google&quot; \<br><a href="http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token">http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token</a>)<br>#ACCESS=$(echo ${TOKEN}|grep --extended-regexp --only-matching &quot;(ya29.[0-9a-zA-Z._-]*)&quot;)<br>#/usr/bin/docker login -u oauth2accesstoken -p &quot;${ACCESS}&quot; <a href="https://gcr.io/">https://</a>[HOSTNAME]<br>OR<br>##4. For COS Instance ##<br>#docker-credential-gcr configure-docker</pre><p>In first glance, using ‘<em>docker-credential-gcr</em>’ seems to be easy approach and it is, however authentication that way does not work with docker compose. docker compose is not available in COS by default, you have to use and run it’s docker image, hence authentication issue still popup when you run that container and try to pull docker image’s mention in your ‘<em>docker-compose.yml</em>’ file,from Private Google Container Registry. We will use third option i.e. ‘docker login’ approach mention from above list, which create authentication file in user home directory /home/[user]/.docker/config.json. Our ‘cloud-init’ startup script looks like as below:</p><pre>#cloud-config<br>users:<br>- name: composer<br>  uid: 2000<br>  groups: docker<br>write_files:<br>- path: /home/composer/auth.sh<br>  permissions: 0755<br>  owner: composer<br>  content: |<br>    TOKEN=$(curl --silent --header  &quot;Metadata-Flavor: Google&quot; \      <br> <a href="http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token">http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token</a>)<br>    ACCESS=$(echo ${TOKEN} \<br>    | grep --extended-regexp --only-matching &quot;(ya29.[0-9a-zA-Z._-]*)&quot;)<br>    /usr/bin/docker login -u oauth2accesstoken -p &quot;${ACCESS}&quot; <a href="https://gcr.io/">https://gcr.io</a></pre><p>When cloud-init script runs during Instance boot, it run as root. So if you run ‘docker login’ command in this phase, it’s going to failed, because ‘/root’ File System is <strong>ReadOnly</strong> in COS instance. Let’s see in next section, how we are going to solve this problem.</p><h4>Docker Compose tool</h4><p>Compose is tool for defining and running multi-container Docker applications. With compose you use YAML file to configure your application services. Then, with single command, you create and start all services from your configuration file. You can find more details about this here — <a href="https://docs.docker.com/compose/">https://docs.docker.com/compose/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*P-Wksfa3FX28Oz_RVmBl7Q.png" /></figure><p>We are going to manage docker compose via ‘systemctl’ service. Code in ‘cloud-init’ file will be as below:</p><pre>#cloud-config<br>write_files:<br>- path: /etc/systemd/system/composer.service<br>  permissions: 0644<br>  owner: root<br>  content: |<br>    [Unit]<br>    Description=Composer Service<br>    Requires=docker.service network-online.target<br>    After=docker.service network-online.target<br>    [Service]<br>    User=composer<br>    Environment=&quot;HOME=/home/composer&quot;<br>    ExecStartPre=/home/composer/auth.sh  <br>    ExecStart=/usr/bin/docker run --rm -v  /var/run/docker.sock:/var/run/docker.sock -v &quot;/home/composer/.docker:/root/.docker&quot; -v &quot;/home/composer:/home/composer&quot; -w=&quot;/home/composer&quot; docker/compose:1.24.0 up<br>    ExecStop=/usr/bin/docker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v &quot;/home/composer/.docker:/root/.docker&quot; -v &quot;/home/composer:/home/composer&quot; -w=&quot;/home/composer&quot; docker/compose:1.24.0 rm -f<br>    Restart=on-failure<br>    RestartSec=10<br>    [Install]<br>    WantedBy=multi-user.target</pre><pre>runcmd:<br>- systemctl daemon-reload<br>- systemctl enable --now --no-block composer.service                                                </pre><p>Lets understand above code, service will be run as ‘composer’ user and so authentication to Private Google Container Registry, using ExecStartPre option which will create docker authentication config file /home/composer/.docker/config.json, and which will be passed to ‘docker compose’ container environment as volume mounted using -v /home/composer/.docker:/root/.docker option. Composer YAML file will be kept under /home/composer directory, so during ‘<em>compose up</em>’ command it refer to services that need to bring up.</p><h4>Docker Compose file</h4><p>You can read about how to write docker compose file here: <a href="https://docs.docker.com/compose/compose-file/">https://docs.docker.com/compose/compose-file</a>. We can create this docker composer file from cloud-init script or can be pulled from google bucket, during Instance initialize phase. For this exercise, we will add it into ‘cloud-init’ script and it’s content will be as below:</p><pre>#cloud-config<br>write_files:<br>- path: /home/composer/docker-compose.yml<br>  permissions: 0644<br>  owner: composer<br>  content: |<br>    version: &quot;3.7&quot;<br>    services:<br>      app:<br>        image: gcr.io/[PROJ_NAME]/[APP_IMAGE]<br>        environment:<br>          DATABASE_URL: mysql://dbuser:dbpassword@db:3306/database<br>        ports:<br>          - 80:80   <br>        depends_on:<br>          - db<br>      db:<br>        image: gcr.io/[PROJ_NAME]/[DB_IMAGE]<br>        ports:<br>          - 3306:3306</pre><h4>Creating an Instance for advanced scenario</h4><p>Let’s now create Google Compute Engine COS Instance with metadata script via ‘cloud-init’ option.</p><pre># Instance Creation<br>#gcloud compute --project=[project-name] instances \<br>create [inst-name] --zone=us-central1-a \<br>--machine-type=n1-standard-1 --subnet=default \<br>--metadata-from-file user-data=cos-cloudinit.sh \<br>--maintenance-policy=MIGRATE \<br>--service-account=demo-svc-account@[project -name].iam.gserviceaccount.com \<br>--scopes=https://www.googleapis.com/auth/cloud-platform \<br>--image=cos-stable-78-12499-59-0 --image-project=cos-cloud \<br>--boot-disk-size=50GB --boot-disk-type=pd-standard \<br>--boot-disk-device-name=[inst-name] --tags http-traffic</pre><p>For reference, our complete cloud-init script (cos-cloudinit-.sh) will now has below contents:</p><pre>#cloud-config<br>users:<br>- name: composer<br>  uid: 2000<br>  groups: docker<br>write_files:<br>- path: /home/composer/auth.sh<br>  permissions: 0755<br>  owner: composer<br>  content: |<br>    TOKEN=$(curl --silent --header  &quot;Metadata-Flavor: Google&quot; \      <br> <a href="http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token">http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token</a>)<br>    ACCESS=$(echo ${TOKEN} \<br>    | grep --extended-regexp --only-matching &quot;(ya29.[0-9a-zA-Z._-]*)&quot;)<br>    /usr/bin/docker login -u oauth2accesstoken -p &quot;${ACCESS}&quot; <a href="https://gcr.io/">https://gcr.io</a><br>- path: /home/composer/docker-compose.yml<br>  permissions: 0644<br>  owner: composer<br>  content: |<br>    version: &quot;3.7&quot;<br>    services:<br>      app:<br>        image: gcr.io/[PROJ_NAME]/[APP_IMAGE]<br>        environment:<br>          DATABASE_URL: mysql://dbuser:dbpassword@db:3306/database<br>        ports:<br>          - 80:80   <br>        depends_on:<br>          - db<br>      db:<br>        image: gcr.io/[PROJ_NAME]/[DB_IMAGE]<br>        ports:<br>          - 3306:3306<br>- path: /etc/systemd/system/composer.service<br>  permissions: 0644<br>  owner: root<br>  content: |<br>    [Unit]<br>    Description=Composer Service<br>    Requires=docker.service network-online.target<br>    After=docker.service network-online.target<br>    [Service]<br>    User=composer<br>    Environment=&quot;HOME=/home/composer&quot;<br>    ExecStartPre=/home/composer/auth.sh  <br>    ExecStart=/usr/bin/docker run --rm -v  /var/run/docker.sock:/var/run/docker.sock -v &quot;/home/composer/.docker:/root/.docker&quot; -v &quot;/home/composer:/home/composer&quot; -w=&quot;/home/composer&quot; docker/compose:1.24.0 up<br>    ExecStop=/usr/bin/docker run --rm -v /var/run/docker.sock:/var/run/docker.sock -v &quot;/home/composer/.docker:/root/.docker&quot; -v &quot;/home/composer:/home/composer&quot; -w=&quot;/home/composer&quot; docker/compose:1.24.0 rm -f<br>    Restart=on-failure<br>    RestartSec=10<br>    [Install]<br>    WantedBy=multi-user.target<br>runcmd:<br>- systemctl daemon-reload<br>- systemctl enable --now --no-block composer.service</pre><p>Once Instance provision completed, you can see two container&#39;s (i.e. app &amp; db) up and running. You can view activity logs of docker compose through your ‘systemctl’ service.</p><pre>#systemctl status composer.service<br>#journalctl -u composer.service</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=159b12e3d117" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secrets Management in Container-Optimized OS]]></title>
            <link>https://medium.com/@sachin.d.shinde/secrets-management-in-container-optimized-os-3341d5a2ee79?source=rss-b01de00d59f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/3341d5a2ee79</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[container-optimized-os]]></category>
            <category><![CDATA[google-kms]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Sachin Shinde]]></dc:creator>
            <pubDate>Mon, 02 Dec 2019 03:45:14 GMT</pubDate>
            <atom:updated>2019-12-02T03:45:14.390Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Series 1 : Google Container-Optimized OS (COS)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/650/1*vfs6tQrnVkezTWh5FANTPw.png" /></figure><p><a href="https://cloud.google.com/">Google Cloud Platform</a> (GCP) provides two ways to run docker container into <a href="https://cloud.google.com/container-optimized-os/">Container-Optimized OS</a> (aka “COS”) while creating Google Compute Engine Instances -</p><blockquote>COS is based on Chromium OS having minimal Linux OS focused on security and running containers.</blockquote><ul><li>For simple scenarios, you specify a container image and few optional configuration when you define the instance. #gcloud beta compute instances <strong>create-with-container </strong>[inst_name] --<strong>container-image</strong> ...</li><li>For advanced scenarios, where you deploy multiple containers and you configure those run-time based on your use case using cloud-init or metadata startup-script. Absence of “create-with-container” flag. <em>I will cover more about this in next series</em></li></ul><p>In this post, I will cover first scenario with aim of securely inject secrets like password, Service Account Credential (“<em>json</em>”) which required to authenticate with other services within Google from application running in container.</p><p>For security reason, you do not embed application credential or service account file into docker image, when you build and publish it to <a href="https://cloud.google.com/container-registry/">Google Container Registry.</a> We need to inject them securely in run-time and here is, how we are going to achieve it -</p><ol><li>Encrypt secret using Google KMS</li><li>Used base64 encode form of encrypted secret into Google Compute Engine startup-script</li><li>Pass startup-script as metadata when you define COS Instance</li><li>During Instance boot, startup-script will pull secret, decrypt it, decode it and make available to container environment</li></ol><h4>Prerequisites</h4><ul><li>Storage bucket for storing startup-script</li><li>Google KMS key which use to encrypt application credential or service account json file</li><li>Service Account which has access permission to pull image from Google Container registry and IAM role to access required services in Google, based on application need</li></ul><pre>##Storage Bucket##<br>gs://[project-name]-scripts</pre><pre>##KMS Key URL##<br>projects/[project-name]/locations/[keyring-location]/keyRings/[keyring-name]/cryptoKeys/[key-name]</pre><pre>##Service Account##<br>demo-svc-account@[project-name].iam.gserviceaccount.com<br>IAM role&#39;s:<br>   - &#39;Storage Object Viewer&#39; role on artifacts.[project- name].appspot.com (Container Image Bucket)<br>   - &#39;Cloud KMS CryptoKey Decrypter&#39; role on [project-name]/locations/[keyring-location]/keyRings/[keyring-name]/cryptoKeys/[key-name]<br>   - &#39;Storage Object Viewer&#39; role on gs://[project-name]-scripts<br>..<br>.. - any other role based on container application functionality</pre><h4>Encrypting Secrets</h4><p>If want to understand more about Google KMS service, this article is great to start — <a href="https://cloud.google.com/kms/docs/quickstart">https://cloud.google.com/kms/docs/quickstart</a></p><pre># Create a local file with the secret<br>echo &quot;YourPassword&quot; &gt; credential.txt</pre><pre># To encrypt a secret using KMS<br>gcloud kms encrypt \<br>  --plaintext-file=credential.txt \<br>  --ciphertext-file=credential.enc.txt \<br>  --location=global \<br>  --keyring=[keyring-name] \<br>  --key=[key-name]</pre><pre># Encode the binary encoded secret as base64 string<br>base64 credential.enc.txt -w 0 &gt; credential.enc.64.txt</pre><h4>Google Compute Engine startup-script</h4><p>Replace [password-cipher] in below script with base64 encode value from above step</p><pre>#cos-script.sh<br>#! /bin/bash<br>mkdir -p /etc/secr_dir<br>KMS_KEY=&quot;[project-name]/locations/[keyring-location]/keyRings/[keyring-name]/cryptoKeys/[key-name]&quot;<br>CIPHER_TEXT=&quot;[password-cipher]&quot;  </pre><pre>TOKEN=$(curl --silent --header  &quot;Metadata-Flavor: Google&quot; \<br><a href="http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token">http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token</a>)</pre><pre>ACCESS=$(echo ${TOKEN} \<br>  | grep --extended-regexp --only-matching &quot;(ya29.[0-9a-zA-Z._-]*)&quot;)</pre><pre>RESULT=$(curl -s -X POST -H &quot;Authorization: Bearer ${ACCESS}&quot; \<br>-H &quot;Content-Type:application/json&quot; \<br>-d &quot;{\&quot;ciphertext\&quot;: \&quot;${CIPHER_TEXT}\&quot;}&quot; \<br><a href="https://cloudkms.googleapis.com/v1/projects/$%7BKMS_KEY%7D:decrypt">https://cloudkms.googleapis.com/v1/projects/${KMS_KEY}:decrypt</a>)</pre><pre>BASE64_SEC=$( echo ${RESULT} |awk -F&quot;:&quot; &#39;{ print $2 }&#39;|grep --extended-regexp --only-matching &quot;(\&quot;.*\&quot;)&quot;|tr -d &#39;&quot;&#39;)</pre><pre>SECRET=$(echo ${BASE64_SEC}|base64 -d)<br>echo $SECRET &gt; /etc/secr_dir/app_secret</pre><h4>Compute Engine Instance Definition</h4><pre># Instance creation<br>gcloud beta compute --project=[project-name] instances \<br>create-with-container [inst_name] \<br>--metadata=google-logging-enabled=true,\<br>startup-script-url=gs://[project-name]-scripts/cos-script.sh\<br>--service-account=demo-svc-account@[project -name].iam.gserviceaccount.com \<br>--scopes=<a href="https://www.googleapis.com/auth/cloud-platform">https://www.googleapis.com/auth/cloud-platform</a> \<br>--container-image=gcr.io/[project-name]/[image-name] \<br>--container-mount-host-path=mount-path=/mnt, \<br>host-path=/etc/secr_dir,mode=ro</pre><h4>Konlet-startup Service</h4><p>Konlet container agent is responsible to bring up user container if gcloud command has “create-with-container” flag. COS run metadata startup script prior to running this service. Hence Compute engine startup script is good place to make required environment available for container. You can read more about this service here -<a href="https://github.com/GoogleCloudPlatform/konlet">https://github.com/GoogleCloudPlatform/konlet</a></p><pre>#konlet-statup service  <br>[Unit]<br>Description=Containers on GCE Setup<br>Wants=network-online.target google-startup-scripts.service gcr-online.target docker.socket<br>After=network-online.target google-startup-scripts.service gcr-online.target docker.socket</pre><blockquote>Please note konlet container agent do authentication with your Google Container Registry when it pull user container image. This is not the case, when you use advance scenario option (mention before i.e. absence of “create-with-container” flag), you have to manage authentication with registry.</blockquote><h4>Docker Image</h4><p>Entry point in your docker image, should read secret from “/mnt” volume during container run and amend required configuration file before starting application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3341d5a2ee79" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>