<?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 Doug Sillars on Medium]]></title>
        <description><![CDATA[Stories by Doug Sillars on Medium]]></description>
        <link>https://medium.com/@dougsillars?source=rss-99312f6126fb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ls-CRsxU3AzCwTk2.png</url>
            <title>Stories by Doug Sillars on Medium</title>
            <link>https://medium.com/@dougsillars?source=rss-99312f6126fb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 22:43:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dougsillars/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[AWS Service Quotas: Discovering Where you Stand]]></title>
            <link>https://dougsillars.medium.com/aws-service-quotas-discovering-where-you-stand-7f26a4e6332c?source=rss-99312f6126fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f26a4e6332c</guid>
            <dc:creator><![CDATA[Doug Sillars]]></dc:creator>
            <pubDate>Fri, 17 Feb 2023 00:00:39 GMT</pubDate>
            <atom:updated>2023-02-21T13:57:53.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mECt1UJowFmAgVW-.jpeg" /></figure><p>We’ve written a few posts in the last week about AWS Service Quotas. These are restrictions on services that are set by AWS (but can often be increased).</p><p>If our <a href="https://unskript.com/aws-service-quotas-what-are-they-and-how-can-i-increase-them/">first post, we looked at New Actions in unSkript</a> that can be used to determine quota values and request a quota increase. In this post, we’ll take the Actions a step further, and build an Action that compares the AWS quota to actual usage — generating an alert when a threshold is met.</p><h3>Getting Started</h3><p>To begin, we will need to consider how the Action will work. For any given service, we’ll need to query AWS at least twice:</p><ol><li>Get the Quota Limit.</li><li>Determine the usage of a service.</li></ol><p>Every query requires one call to complete Step 1. However, Step two can require many queries to complete the usage query. In the simplest case, we can do just one query:</p><blockquote><em>Example: </em>Client VPN Endpoints per Region. <em>If we query AWS for the list of endpoints in a region, we can simply get the length of the response to know how many endpoints exist.</em></blockquote><p>However, there are times where there will be multiple queries:</p><blockquote><em>Example: </em>Routes per Client VPN Endpoint<em>. In the first query, we get the list of VPN endpoints. In step 2, we must query every VPN endpoint to get the count of Routes. If there are 4 VPN endpoints, there will be a total of 5 calls made (On call to get the list of 4 VPN endpoints, and then one call to each of the four endpoints).</em></blockquote><p>To account for these two options, we create an input Dictionary.</p><h3>The Simple, one pass Dictionary</h3><p>For the <em>Describe AMIs</em> call (only one Usage query is required), the Dict looks like this:</p><pre>{ &#39;QuotaName&#39;:&#39;AMIs&#39;,<br>  &#39;ServiceCode&#39;:&#39;ec2&#39;,<br>  &#39;QuotaCode&#39;: &#39;L-B665C33B&#39;, <br>  &#39;ApiName&#39;: &#39;describe_images&#39;, <br>  &#39;ApiFilter&#39; : &#39;[]&#39;,<br>  &#39;ApiParam&#39;: &#39;Images&#39;, <br>  &#39;initialQuery&#39;: &#39;&#39;<br>}</pre><p>To get the Quota, we need the ServiceCode and the QuotaCode (If you need to obtain these variables, you can use the unSkript Action, or you can refer to the table in the <a href="https://docs.unskript.com/unskript-product-documentation/lists/test">unSkript Docs)</a>. The one usage API call will be made to the <em>describe_images</em> endpoint, and retrieve a list of <em>Images</em>. Counting this length gives us our usage.</p><h3>The Two Pass Dictionary</h3><p>To determine the <em>Attachments per transit gateway</em>, we must again get the quota from the Service Code and Quota Code. To get the count of attachments per transit gateway, we us the <em>initalQuery</em> array to make a first query.</p><p>The first query probes the <em>describe_transit_gateways</em> endpoint, to give a list of <em>TransitGateways. </em>In the second set of calls, we call the <em>describe_transit_gateway_attachments </em>endpoint for each transit gateway. The filter has a string VARIABLE that is replaced with the <em>TransitGatewayId</em> for each gateway -ensuring that each call is made to a different transit gateway. We can then count the length of the response to find out how many attachments are in each transit gateway. If we have 12 transit gateways. we will have 12 usage reports.</p><pre>{&#39;QuotaName&#39;:&#39;Attachments per transit gateway&#39;,<br>&#39;ServiceCode&#39;:&#39;ec2&#39;,<br>&#39;QuotaCode&#39;: &#39;L-E0233F82&#39;, <br>&#39;ApiName&#39;: &#39;describe_transit_gateway_attachments&#39;, <br>&#39;ApiFilter&#39; : &#39;[{&quot;Name&quot;: &quot;transit-gateway-id&quot;,&quot;Values&quot;: [&quot;VARIABLE&quot;]}]&#39;, <br>&#39;ApiParam&#39;: &#39;TransitGatewayAttachments&#39;, <br>&#39;initialQuery&#39;: &#39;[&quot;describe_transit_gateways&quot;,&quot;TransitGateways&quot;, &quot;TransitGatewayId&quot;]&#39;<br>}</pre><h3>Outliers</h3><p>For most of our quota measurements, these two approaches work well. However, with over 2600 different quotas inside AWS, not all of them fit neatly into these two buckets. For example <em>Multicast Network Interfaces per transit gateway</em> requires 3 calls: Transit gateways -&gt; Multicast Domains → Domain attachments.</p><p>For others, there is custom code to iterate over. These require an extra if statement in the code to properly account for their usage.</p><h3>Action Format</h3><p>We can differentiate between the two types of query by looking at the ‘initialQuery’ parameter. If it is empty, we can do the Simple query, otherwise, do the double query (with a for loop that queries each initial result). For outliers, we can add specific code inside the if/else:</p><p>(this is simplified a bit from what actually runs):</p><pre>for i in table: #get quota sq = sqClient.get_service_quota(ServiceCode=i.get(&#39;ServiceCode&#39;),QuotaCode=i.get(&#39;QuotaCode&#39;)) quotaValue =sq[&#39;Quota&#39;][&#39;Value&#39;] #get usage <br> if i.get(&#39;initialQuery&#39;) = &#39;&#39;: <br>    res = aws_get_paginator(ec2Client, i.get(&#39;ApiName&#39;), i.get(&#39;ApiParam&#39;), Filters=filterList) <br>    count = len(res) <br>    percentage = count/quotaValue <br>    combinedData = {&#39;Quota Name&#39;: i.get(&#39;QuotaName&#39;), &#39;Limit&#39;:quotaValue, &#39;used&#39;: count, &#39;percentage&#39;:percentage} <br>    result.append( combinedData) print(combinedData)<br> else:<br>    res = aws_get_paginator(ec2Client, i.get(&#39;ApiName&#39;), i.get(&#39;ApiParam&#39;), Filters=filterList) <br>    for j in res:<br>       #build the filter query with some simple substitutions<br>       res2 = aws_get_paginator(ec2Client, i.get(&#39;ApiName&#39;), i.get(&#39;ApiParam&#39;), Filters=filterList) <br>       count = len(res2)<br>       percentage = count/quotaValue<br>       objectResult = {j[initialQueryFilter] : count}<br>       quotaName = f&quot;{i.get(&#39;QuotaName&#39;)} for {j[initialQueryFilter]}&quot;<br>       combinedData = {&#39;Quota Name&#39;: quotaName, &#39;Limit&#39;:quotaValue, &#39;used&#39;: count, &#39;percentage&#39;:percentage}<br>       result.append(combinedData)</pre><h3>Action Output</h3><p>Once all of the values have been collected, the percentage utilized is compared to the warning percentage input. If the utilization is over the requested percentage, the Service data will be added to the output of the Action. With this information, the SRE responsible can decide the correct Action to take — either prune away some usage, or request an increase from AWS.</p><p>For example, testing all VPC Service quotas with a earning of 50% utilization gives the following data:</p><pre>{&#39;Instances&#39;: <br>  [{&#39;Limit&#39;: 20.0, <br>    &#39;Quota Name&#39;: &#39;VPCs Per Region&#39;, <br>    &#39;percentage&#39;: 0.65, <br>    &#39;used&#39;: 13}, <br>   {&#39;Limit&#39;: 20.0, <br>      &#39;Quota Name&#39;: &#39;Internet gateways per Region&#39;, <br>      &#39;percentage&#39;: 0.6, <br>      &#39;used&#39;: 12}, <br>    {&#39;Limit&#39;: 5.0, <br>      &#39;Quota Name&#39;: &#39;NAT gateways per Availability Zone&#39;, <br>      &#39;percentage&#39;: 0.8, <br>      &#39;used&#39;: 4}, <br>    {&#39;Limit&#39;: 50.0, <br>      &#39;Quota Name&#39;: &#39;Routes per route table&#39;, <br>      &#39;percentage&#39;: 0.5, <br>      &#39;used&#39;: 25}, <br>    {&#39;Limit&#39;: 20.0, <br>      &#39;Quota Name&#39;: &#39;Rules per network ACL&#39;, <br>      &#39;percentage&#39;: 0.65, <br>      &#39;used&#39;: 13}]}</pre><h3>Availability Today</h3><p>As we publish this article, we have 2 Actions heading into unSkript:</p><ol><li>A general <em>AWS_ServiceQuota Compare</em> Action that has the basic framework described above. This will likely require customization for each Quota you wish to test against.</li><li><em>AWS VPC Service Quota Warning</em>. This Action takes all of the VPC service quotas (as of February 2023) and tests them against your infrastructure.</li></ol><p>Coming Soon:</p><p>We’re really excited to see how people use these Service Quota alerts in their infrastructure. If you have questions — feel free to reach out in our <a href="https://communityinviter.com/apps/cloud-ops-community/awesome-cloud-automation">Slack Community</a>. If you haven’t tried unSkript — try our <a href="https://github.com/unskript/Awesome-CloudOps-Automation">OSS Docker Container</a>, or use our <a href="https://us.app.unskript.io/">free trial online!</a></p><p><em>Originally published at </em><a href="https://unskript.com/aws-service-quotas-discovering-where-you-stand/"><em>https://unskript.com</em></a><em> on February 17, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f26a4e6332c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Service Quotas: What are they, and how can I increase them?]]></title>
            <link>https://dougsillars.medium.com/aws-service-quotas-what-are-they-and-how-can-i-increase-them-20f25c6db06c?source=rss-99312f6126fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/20f25c6db06c</guid>
            <dc:creator><![CDATA[Doug Sillars]]></dc:creator>
            <pubDate>Tue, 14 Feb 2023 00:00:08 GMT</pubDate>
            <atom:updated>2023-02-21T13:52:46.676Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TT_kSjzeaccRidW3.jpg" /></figure><p>Everywhere we go, there are limits — speed limits, weight limits, capacity limits. AWS is no different. For many of the services offered by AWS, there is a service quota limit — the maximum number of that feature each account holder is allowed to use.</p><h3>Can we determine the limits imposed by AWS?</h3><p>Yes, the AWS <em>service-quotas</em> API endpoint can tell us what quotas exist and their values?</p><h3>Can we ask for a limit increase?</h3><p>For most of the quotas, you can ask for your limit to be increased.</p><p>In this post, we’ll use Actions in unSkript to automate work around Service Quotas — determining limits, and asking for an increase to a quota. All of these Actions are soon to be a part of the unSkript <a href="https://github.com/unskript/Awesome-CloudOps-Automation">Awesome Runbooks GitHub repository.</a> They’ll also be included in all instances on unSkript.</p><h3>Probing the AWS Service Quota Surface</h3><p>The first step in understanding AWS Service Quotas is to look at the API. There are a few interesting endpoints, but in order to query a specific service or request a quota increase, we will need three items:</p><p>We probably have a good idea what AWS Region our stack is deployed to — that’s the easy part. We still need to understand and figure out the Service Code and the Quota Code for our service.</p><h3>Service Codes</h3><p>Service codes describe the top level services that AWS offers (think S3, EC2, etc.) To obtain the AWS Service Codes, we can utilize the <em>list-services</em> endpoint in our Action named <strong>AWS Get All Service Names v1</strong>:</p><pre>def aws_get_all_service_names(handle, region:str) -&gt; List: <br>  sqClient = handle.client(&#39;service-quotas&#39;,region_name=region) <br>  resPaginate = aws_get_paginator(sqClient,&#39;list_services&#39;,&#39;Services&#39;,PaginationConfig={ <br>        &#39;MaxItems&#39;: 1000, <br>        &#39;PageSize&#39;: 100 }) <br>  #res = sqClient.list_services(MaxResults = 100) <br>  return resPaginate</pre><p>This lists all of the AWS Services by name and their service code. At the time of this writing, there are 220 ( <strong>edit</strong> — it is now 221!) services in the output.</p><h3>Quota Codes</h3><p>Quota codes are available in the AWS Console interface, but it requires a lot of digging to get them (and sometimes it is easiest to find them in the url string). An easier way is via the API:</p><p>The <em>list_service_quotas</em> endpoint takes a Service Code (from the first list), and outputs all of the service quotas for that service. The <strong>AWS Get Service Quotas for a Service v1</strong> Action obtains the codes, given a Service Code</p><p>Setting the Service Code to “ec2”, and the Region to “us-west-2”, we get 129 different Quotas (and the quota code for each one of them).</p><pre>sqClient = handle.client(&#39;service-quotas&#39;,region_name=region) <br>resPaginate = aws_get_paginator(sqClient,&#39;list_service_quotas&#39;,&#39;Quotas&#39;, <br>ServiceCode=service_code, PaginationConfig={ <br>    &#39;MaxItems&#39;: 1000, <br>    &#39;PageSize&#39;: 100 }) <br>#res = sqClient.list_services(MaxResults = 100) <br>return resPaginate</pre><h3>A sample output</h3><p>Here is a sample of the EC2 output:</p><pre>{ &#39;ServiceCode&#39;: &#39;ec2&#39;, <br>  &#39;ServiceName&#39;: &#39;Amazon Elastic Compute Cloud (Amazon EC2)&#39;, <br>  &#39;QuotaArn&#39;: &#39;arn:aws:servicequotas:us-west-2:100498623390:ec2/L-70015FFA&#39;, <br>  &#39;QuotaCode&#39;: &#39;L-70015FFA&#39;, <br>  &#39;QuotaName&#39;: &#39;AMI sharing&#39;, <br>  &#39;Value&#39;: 1000.0, <br>  &#39;Unit&#39;: &#39;None&#39;,  <br>  &#39;Adjustable&#39;: True, <br>  &#39;GlobalQuota&#39;: False<br>}</pre><p>This says that the limit for the number of Amazon Machine Images (AMIs) that you can share is 1000.</p><h3>Requesting a Quota Increase</h3><p><strong>What if we wanted to share 1001 AMIs? </strong>We can request a quota increase via API. In the several attempts I have made, they were all grated automatically — but not immediately. Using the <em>request service quota increase</em> endpoint in the <strong>AWS Request Service Increase</strong> Action adds your request to the AWS queue for processing:</p><pre>def aws_get_service_quotas(handle, service_code:str, quota_code:str, new_quota:float,region:str) -&gt; Dict: <br>  sqClient = handle.client(&#39;service-quotas&#39;,region_name=region) <br>  res = sqClient.request_service_quota_increase( ServiceCode=service_code, QuotaCode=quota_code, DesiredValue=new_quota) <br>  #res = sqClient.list_services(MaxResults = 100) <br>  return res</pre><p>This Action has 3 inputs — the Service_code, the quota_code, and the integer value that you would like the quota changed to.</p><h3>Conclusion</h3><p>In this post, we built Actions using unSkript to learn what service quotas exist in your AWS Account, and how to update them. The Actions described in this post are built into unSkript’s automation engine, allowing you to build custom RunBooks around service quotas in your AWS environment.</p><p>Are you interested in learning more? Try out our Open Source Docker build. <a href="https://github.com/unskript/Awesome-CloudOps-Automation">Instructions can be found in the GitHub Readme file.</a> If you have questions, join our <a href="https://communityinviter.com/apps/cloud-ops-community/awesome-cloud-automation">Slack channel</a>, where the community will be happy to help you!</p><p><em>Originally published at </em><a href="https://unskript.com/aws-service-quotas-what-are-they-and-how-can-i-increase-them/"><em>https://unskript.com</em></a><em> on February 14, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20f25c6db06c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Security Checkup: Force AWS Load Balancers to redirect to HTTPS]]></title>
            <link>https://blogs.unskript.com/security-checkup-force-aws-load-balancers-to-redirect-to-https-3249016eb916?source=rss-99312f6126fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3249016eb916</guid>
            <dc:creator><![CDATA[Doug Sillars]]></dc:creator>
            <pubDate>Wed, 25 Jan 2023 00:00:19 GMT</pubDate>
            <atom:updated>2023-01-27T03:08:17.042Z</atom:updated>
            <content:encoded><![CDATA[<p>When on a hike — you always want to take the most secure path, and not risk taking an unsafe route. With so many features now in the Cloud, it can be tricky to ensure that all of the traffic in and out of your services is secured over HTTPS — both for the safety of your company, but also your customers.</p><p>In this health/security check, we’ll configure unSkript to run a prebuilt RunBook to ensure that all of our Application Load Balancers in AWS are enforcing HTTPS redirection.</p><p>The RunBooks we’ll be configuring is called “<strong><em>Enforce HTTP Redirection Across AWS ALB.</em></strong>” To access this xRunBook, follow the following steps (depending on the release being used):</p><ol><li><a href="https://github.com/unskript/Awesome-CloudOps-Automation">Docker (Open Source)</a>: in the Welcome.ipynb landing page, you’ll see this RunBook listed under AWS. Click the link to open.</li><li>SAAS (<a href="https://us.app.unskript.io/">Free Trial</a>): Under “xRunBooks” click the “unSkript xRunBooks” tab to see a list of all of the pre-built RunBooks. Search for the title. Click the 3 dot menu to import this into your library (You’ll need to give the RunBook a new name, and assign a proxy). Once it is saved in your library, open the runBook to the editor.</li></ol><p>This xRunBook has one input parameter — the AWS Region to use. The default setting is ‘us-west-2’, but this can be changed in the top menu “Parameters.” Once the input settings are set, there are 3 Actions that are run in this xRunBook:</p><ol><li><strong><em>List all AWS Application Load Balancers</em></strong>: This queries AWS for a full list of all the load balancers in the region.</li><li><strong>List all AWS Listeners that do not have HTTP Redirection</strong>: This Action takes all of the Load Balancers from step 1, and cycles through them all checking the Listeners attached to the load balancers. If the Listeners do not support HTTPS Redirect, they are written as output.</li><li><strong>Modify Load Balancer Listeners to Enforce HTTP Redirection</strong>: This Action iterates through the list created in step 2. If all of the Load balancers are already enforcing HTTP redirection, it does not run.</li></ol><p>In order for this xRunBook to run in your AWS environment, you must have <a href="https://docs.unskript.com/unskript-product-documentation/guides/connectors/aws#authentication">AWS credentials</a> set in your unSkript proxy. Set them up via the instructions in the link. Once they are created, Click the configuration button for each Action, and choose the AWS Credentials you would like to be used in this xRunBook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*Ndb3DCsBW_e7xgc5" /></figure><p>Once all three Actions have the proper Credentials — save the xRunBook, and you are ready to run.</p><p>To run Interactively, click “Run Action” for each step (in order). You’ll first get the list of Load Balancers:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*n0bd7iOOSCZG1BSn" /></figure><p>This list will then be iterated on for all of the listeners on each load balancer. If any listeners do not enforce a HTTP redirect, they will appear in the response:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*I9riU2aB0URo4fZu" /></figure><p>Finally, if there are any listeners that need to be updated, the last Action will update the listeners.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*7htg1cZalA56t6G-" /></figure><p>If you run the xRunBook a second time for the same region — all of the listeners will pass the 2nd step, and the array will be empty:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*O9graY5cnAEV8Y55" /></figure><h3>Summary</h3><p>In this post, we’ve walked through the steps to configure an unSkript RunBook that Enforces AWS Load Balancers to redirect HTTP to HTTPS. This pre-built RunBook is installed for free as a part of our open-source library of RunBooks and Actions, and as noted in this post, can be quickly configureed to run in your AWS environment. By regularly running this security check, you can ensure that all traffic passing through your load balancers at AWS is HTTPS, and that your customer’s data is secure.</p><p>Want to try it yourself? Check out our <a href="https://us.app.unskript.io/">Free Trial</a>, and give us a star on <a href="http://runbooks.sh/">GitHub</a>!</p><p><em>Originally published at </em><a href="https://unskript.com/security-checkup-force-aws-load-balancers-to-redirect-to-https/"><em>https://unskript.com</em></a><em> on January 25, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3249016eb916" width="1" height="1" alt=""><hr><p><a href="https://blogs.unskript.com/security-checkup-force-aws-load-balancers-to-redirect-to-https-3249016eb916">Security Checkup: Force AWS Load Balancers to redirect to HTTPS</a> was originally published in <a href="https://blogs.unskript.com/">unSkript</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Copying AWS Amazon Machine Images Across Regions with unSkript]]></title>
            <link>https://blogs.unskript.com/copying-aws-amazon-machine-images-across-regions-with-unskript-9f3c77f110a4?source=rss-99312f6126fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f3c77f110a4</guid>
            <dc:creator><![CDATA[Doug Sillars]]></dc:creator>
            <pubDate>Tue, 24 Jan 2023 00:00:01 GMT</pubDate>
            <atom:updated>2023-01-27T03:07:47.389Z</atom:updated>
            <content:encoded><![CDATA[<p>When you are building a distributed platform, You’ll need to regularly update the machines that you have deployed around the world. With Amazon Web Services (AWS), one way to do this is to deploy the updated machine in one region, and create an Amazon Machine Image (AMI) of that server. Then, by copying that AMI to different AWS regions, you can easily deploy an identical server anywhere around the world.</p><p>Copying AMIs across regions is possible to do via the AWS console UI, or using the AWS command line. At unSkript, we are working to remove the manual toil of running scripts against the command line, or performing multi-step manual processes in the UI. With hundreds of pre-built connectors and Actions to perform common tasks with the most popular cloud services — it is easy to get started with unSkript in just minutes. Try it today — either with our<a href="https://github.com/unskript/Awesome-CloudOps-Automation"> Open Source Docker image</a> that you can run on-premises, or with a<a href="https://us.app.unskript.io/"> free trial of our Cloud</a> offering.</p><p>In your install of unSkript, there will be a RunBook called “<a href="https://github.com/unskript/Awesome-CloudOps-Automation/blob/master/AWS/Copy_ami_to_all_given_AWS_regions.ipynb"><em>Copy AMI to All Given AWS Regions.</em></a>” This RunBook is pre-configured to perform the AMI copy with just the click of a button. When you open this RunBook (or import your copy into your work area), you’ll only have a few steps before you can begin copying your AMIs.</p><p>At the top of the page, there is a Parameters drop down, where the input parameters for the RunBook are entered:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*UQcdYM_R99f9s_WF" /></figure><p>In the screenshot above, we have an <em>ami_id</em> (with pixelated name) with a <em>source_region</em> of us-west-2. We are looking to copy this AMI to the <em>destination_regions</em> us-east1 and us-east-2. These can be edited with the Edit Value button. When you run this RunBook via the UI — you will be give the opportunity to insert different values.</p><h3>Configuring the Actions</h3><p>Each step of the RunBook is completed by an Action. We will need to quickly configure each Action with credentials that allow unSkript to connect to AWS. If you do not yet have <a href="https://docs.unskript.com/unskript-product-documentation/guides/connectors/aws#authentication">AWS Credentials</a> in unSkript, follow the link to set up your credentials. To Configure your action, click the Configurations button. On the right side, select the AWS credential you’d like the RunBook to connect with:</p><p>Repeat this for all AWS Actions in the RunBook:</p><ul><li>Get all AWS Regions</li><li>Get AMI Name</li><li>Copy AMI to Other Regions</li></ul><p>Once the credentials are set up, save your RunBook. It can now be run from this page in two ways: Run XRunBook button: or interactively — running one Action at a time. But it can now also be run via the RunBook listing page, or using our API.</p><p>Here is the interactive output of the final Action, where the AMI image was copied into us-east-1 and us-east-2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*xQC4hPp6DjmAmPe7" /></figure><p>In this post, we utilized unSkript to automate the copying of AMI’s across AWS regions. Rather than build a RunBook ourselves, we were able to utilize a pre-built RunBook, and simply configure the RuBook for our use case. With just a few steps, we were able to authenticate this RunBook to run in our AWS instance, and copy AMI images from one region to many other regions. By automating such repetitive tasks, unSkript alleviates DevOps toil of repetitive tasks, allowing the team to focus on more important projects.</p><p>Give us a <a href="https://us.app.unskript.io/xRunBooks">try today</a>, and if you like what you see, give us a <a href="https://github.com/unskript/Awesome-CloudOps-Automation">star on GitHub</a>! Questions? Join our <a href="https://communityinviter.com/apps/cloud-ops-community/awesome-cloud-automation">Slack Community</a> — we’d be happy to help.</p><p><em>Originally published at </em><a href="https://unskript.com/copying-aws-amazon-machine-images-across-regions-with-unskript/"><em>https://unskript.com</em></a><em> on January 24, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f3c77f110a4" width="1" height="1" alt=""><hr><p><a href="https://blogs.unskript.com/copying-aws-amazon-machine-images-across-regions-with-unskript-9f3c77f110a4">Copying AWS Amazon Machine Images Across Regions with unSkript</a> was originally published in <a href="https://blogs.unskript.com/">unSkript</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Healthcheck RunBook: Analysis of K8s Logs]]></title>
            <link>https://blogs.unskript.com/building-a-healthcheck-runbook-analysis-of-k8s-logs-d9c1ae47224b?source=rss-99312f6126fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9c1ae47224b</guid>
            <dc:creator><![CDATA[Doug Sillars]]></dc:creator>
            <pubDate>Thu, 19 Jan 2023 00:00:29 GMT</pubDate>
            <atom:updated>2023-02-06T17:45:01.885Z</atom:updated>
            <content:encoded><![CDATA[<p>There’s nothing worse than an outage. Every outage has a cost — both in revenue, sales, but also reputation and perceived reliability. No one wants their company to appear in the news as having a DevOps issue that cratered their service.</p><p>Building RunBooks to perform regular health checks on your system is an effective way to catch issues early — before they become catastrophic. If things have already started breaking the health check alert can point you in the direction of the root cause — reducing the Mean Time to Resolution (MTTR).</p><p>In this post, we’ll build a RunBook that checks our Kubernetes log records for alerts with a level of WARNING, and if there is one — sends a Slack message to the team.</p><p>Like many RunBooks, this project originated from an issue that originated on an Elasticsearch Pod. Here is what the logs were telling us:</p><pre>[2023-01-11T23:45:21,890][WARN ][r.suppressed ] [elastic-elasticsearch-master-0] \path: /audit-alias/_doc/1e84dc30-df60-46b6-8212-e1a51a5a0508, params: {refresh=true, index=audit-alias, id=1e84dc30-df60-46b6-8212-e1a51a5a0508} 2 org.elasticsearch.action.UnavailableShardsException: [audit-000157][0] primary shard is not active Timeout: [1m],</pre><p>The issue is that the primary shard was timing out.</p><p>The resolution was to restart the unresponsive Pod. Since the resolution to this issue is a simple restart, this is a prime example of a RunBook that can be automated ensuring service uptime, without impacting the DevOps team.</p><p>But, while we want to cure this <em>very specific</em> issue, it is likely that there are dozens (if not hundreds) of other warnings that might appear in the Kubernetes logs. Creating a general warning notebook that alerts the team of <strong><em>any</em></strong> warning in the logs seems like it might be a good idea. in this post, we’re going to focus on the general warning, and have the detailed automated fix in a following blog post.</p><p>Tl;dr: This exact RunBook will soon be available in our Open Source repository, so you can use it right ‘off the shelf.’ If you want to see the results of the RunBook, you can import this RunBook, and follow the configuration steps below.</p><p>In our General Warning Notebook, we will go through four steps:</p><ol><li>Get a list of all Kubernetes Pods running in an environment,</li><li>Grab the logs from all of these pods.</li><li>Parse the logs for Warning messages</li><li>If messages are found, send a Slack message to the team.</li></ol><p>We can automate this Notebook to run on a regular schedule to ensure that any K8s warning messages can be dealt with promptly.</p><h3>Building the RunBook.</h3><p>In unSkript, we’ll begin by creating a new RunBook. In the unSkript Free trial, this can be done by clicking the Create button on the If you are using our Docker Open Source, here’s <a href="https://tenant-staging.alpha.unskript.io/xRunBooks">xRunBooks page.</a> <a href="https://docs.unskript.com/unskript-product-documentation/guides/xrunbooks/create-a-xrunbook">how to create a new RunBook</a>:</p><p>We’ll want two input parameters in your RunBook:</p><ul><li>namespace: the K8s resources that we will be examine</li><li>hoursToExamine: the number of hours that we will examine in the logs.</li></ul><p>Here I am have set the default namespace to “logging”, and to examine the logs for the last 1 hour:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*XwBaPeYiPKKzkjv9" /></figure><p>Now we can add our Actions. Three of the Actions in this RunBook are already available in our Action library:</p><ol><li><strong>Kubectl list pods</strong>. In the right navigation — search for this Action, and then drag it into your RunBook Workspace. Click the configuration button.</li><li>If you have a Kubernetes connection created already, select the correct credential to connect to the namespace you desire. If you have not yet created a credential to connect to Kubernetes, <a href="https://docs.unskript.com/unskript-product-documentation/guides/connectors/kubernetes#authentication">here’s how</a>.</li><li>The required field is the namespace we’ll connect to. Since we are using the RunBook parameter to define the namespace, enter the parameter name (in the screenshot above it would be ‘namespace’)</li><li>Click the “Output: tab, name the output “podList” and click Apply changes. This will assign a variable name to the list of pods that we can use in the next Action.</li><li>You can test this configuration by clicking the “Run Action” button. You should obtain a list of the K8s pods in the namespace.</li><li><strong>Kubectl get logs</strong>. Close the configuration and search for the second Action.</li><li>Add the same Credential as above.</li><li>There are two required parameters, “Pod Name” and “Namespace.”</li><li>For “Namespace”, use the same parameter name used in Step 1.</li><li>For “Pod Name”, we have multiple pods that we would like to iterate over. In order to do this, click the “Iterator” tab. We’ll want to iterate over the “podList” we created in Step 1, and then place those values into <em>pod_name</em>. Click Apply Changes for these to take effect.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/764/0*cNQJ7ta82hoJpYuC" /></figure><ol><li>In the Output tab, name the output variable. In this example, we used “allTheLogs.”</li><li>You can now test this Action by clicking <strong>Run Action.</strong> Depending on how many Pods there are in your namespace, this might take a while as the iteration is serial. All of the logs will be saved in a Dict.</li><li>Now we will create a custom Action to parse the logs.</li><li>In the top menu click “Add” and Choose Action. You can edit the name — we chose <strong>parse dict of logs</strong> as our name.</li><li>The code looks like this:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oBz5jqNNvkiGtlNw9uLpTQ.jpeg" /></figure><ol><li>We loop through all of the logs, and do a regular expression search for ‘[WARN’, and create a list of the location of this string in the log.</li><li>Next we loop through all of the places there is a warning in the log, and extract the date and time of the warning. If it falls into the range of the ‘hoursToExamine’ that is set by the RunBook, we have found a new warning.</li><li>We can suppress warnings that have been examined as not important in the stringsToIgnore list — because we do not want alert fatigue to set in, and cry wolf for issues that will not affect the system.</li><li>If our WARNING log entry passes all of these criteria, an entry will be written into warning_text_all with the date, Pod name, and the warning message.</li><li>We also have the ability to check for specific issues in this code. If we see the “primary shard is not active” text, we can call another RunBook to resolve this issue. We’ll cover this in a later post.</li></ol><p><strong>4. Post Message to Slack</strong> Finally, if there are warnings, we want to alert the team. That’s really why the RunBook is here, right?</p><ol><li>Search the Action list, and drag the “Post Message to Slack” Action into your RunBook. In the Configurations, add your Slack Credential (or <a href="https://docs.unskript.com/unskript-product-documentation/guides/connectors/slack#authenticate">create a new Slack Connection</a>).</li><li>There are 2 input parameters:</li><li>Slack Channel</li><li>Message. Here we just print the “warning_text_all” Dict that was created in Step 3.</li><li>Start Conditions. We only want to send a Slack message when there is a warning — alert fatigue and all of that. So in the <em>Start Condition</em> tab of the Action, we can tell this step to only run when: <em>len(warning_text_all) &gt;0</em>. Now, the Slack message will only be sent when there are warnings in the logs</li></ol><p>We can now save this RunBook.</p><p>Philosophers have debated for centuries “If a tree falls in the woods, but no one is there to hear it, does it make a sound?” There is no similar corollary in DevOps. If your systems are reporting errors in their logs, but no one is there to see them — the system will still break. In this post, we’ve built a healthcheck for K8s pods by scanning the logs on regular intervals and surfacing the WARNING errors for the DevOps and SRE team — making it easier and more likely that the messages will be seen and acted upon — and preventing catastrophic errors from going unnoticed.</p><p>Interested in giving health checks with unSkript a try? Check out hundreds of open source Actions and RunBooks in our <a href="https://github.com/unskript/Awesome-CloudOps-Automation">GitHub repo</a> (and instructions for our Docker build), and try out our free <a href="https://us.app.unskript.io/">Sandbox</a>, where you can build and deploy RunBooks for free. We also have a growing <a href="https://communityinviter.com/apps/cloud-ops-community/awesome-cloud-automation">Cloud Automation Slack channe</a> l where we discuss RunBook automations. We look forward to working with you as you begin automating your DevOps processes!</p><p><em>Originally published at </em><a href="https://unskript.com/runbook-analysis-of-k8s-logs/"><em>https://unskript.com</em></a><em> on January 19, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9c1ae47224b" width="1" height="1" alt=""><hr><p><a href="https://blogs.unskript.com/building-a-healthcheck-runbook-analysis-of-k8s-logs-d9c1ae47224b">Building a Healthcheck RunBook: Analysis of K8s Logs</a> was originally published in <a href="https://blogs.unskript.com/">unSkript</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extending unSkript Actions: Quick Customizations of ‘Off the Shelf’ Code]]></title>
            <link>https://dougsillars.medium.com/extending-unskript-actions-quick-customizations-of-off-the-shelf-code-a7a09f0c7270?source=rss-99312f6126fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a7a09f0c7270</guid>
            <dc:creator><![CDATA[Doug Sillars]]></dc:creator>
            <pubDate>Thu, 05 Jan 2023 00:00:28 GMT</pubDate>
            <atom:updated>2023-01-27T03:05:48.786Z</atom:updated>
            <content:encoded><![CDATA[<p>unSkript has hundreds of built-in <a href="https://docs.unskript.com/unskript-product-documentation/lists/action_list">Actions</a> that allow you to quickly build integrated Runbooks with popular Cloud providers, databases, and more. But sometimes, the supplied Actions are not <em>exactly</em> what you are looking for. Luckily, since each Action is written in Python, it is easy to extend and customize any existing Action to exactly suit your needs. In this post, we’ll walk through an example — with a couple of different approaches to modify the Action.</p><h3>Public EC2 instances</h3><p>AWS EC2 virtual machines can be used for a variety of purposes inside an organization. There may be some EC2 instances that are public (hosting your website, for example), but others may be running business critical functions that should be firewalled away from the public.</p><p>Accidentally misconfiguring a private EC2 instance as public facing exposes your company to hacking and potential security breaches, so from a security perspective it is imperative to constantly monitor and ensure that your code is not exposed on the public internet. The unSkript Action “ <a href="https://github.com/unskript/Awesome-CloudOps-Automation/tree/master/AWS/legos/aws_get_public_ec2_instances/README.md">List Public EC2 Instances</a> “ can help you identify any public EC2 instances.</p><p>The Action is easy to configure — requiring just <a href="https://docs.unskript.com/unskript-product-documentation/guides/connectors/aws#authentication">AWS Credentials</a> and an AWS region where your EC2 instances are running. Running this Action gives a result with the public DNS and IP of all the public EC2 instances in that region:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/784/0*JZmhgzJ6pEYT01vZ" /></figure><p>This is great. With a little work, you may discover that some of these need to be made private, and you can update the Security Group as needed. But, there may be a few instances that need to remain public (for your website, or a specific SAAS offering). How do you identify and remove those from the report to prevent false positives?</p><h3>Let’s look at the code</h3><p>Here is the code in the Action that gets all of the EC2 instances, and decides whether they are public or not:</p><pre>ec2Client = handle.client(&#39;ec2&#39;, region_name=region) res = aws_get_paginator(ec2Client, &quot;describe_instances&quot;, &quot;Reservations&quot;) result={} # Iterate through the list of instances for reservation in res: for instance in reservation[&#39;Instances&#39;]: #print(&quot;instance&quot;,instance) instance_id = instance[&#39;InstanceId&#39;] public_DNS = instance[&#39;PublicDnsName&#39;] if len(public_DNS)&gt;0 and instance_id != &quot;i-0684a4244445eb47c&quot;: public_ip = instance[&#39;PublicIpAddress&#39;] result[instance_id] = {&quot;public DNS&quot;: public_DNS,&quot;public IP&quot;:public_ip} return(result)</pre><p>The first 2 lines define the query to AWS, specifying that the query is related to EC2 and identifying the region. We’ll iterate through all the of the “instances” in the response to determine which of the instances are public. These will be placed into the result JSON which is returned by the Action.</p><p>To identify a public EC2 instance, we look for the presence of the parameter <em>instance[‘PublicDnsName’]</em>. If there is no PublicDNS Name, we’re good — the instance is private. If the length of the PublicDNSName is &gt;0, then the instance is public, and we can append the result JSON Dictionary with the information about the instance.</p><p>So how could we extend this? If we are aware of public instances (that are <em>supposed to be public</em>), we wouldn’t want this Action reporting those values. How might we hide these from the results?</p><h3>Hardcoding</h3><p>What if there are only one or 2 EC2 instances that should be public? You might decide to just hardcode these out of your listing:</p><pre>if len(public_DNS)&gt;0 and instance_id != &quot;i-0684a4244445eb47c&quot;: public_ip = instance[&#39;PublicIpAddress&#39;] result[instance_id] = {&quot;public DNS&quot;: public_DNS,&quot;public IP&quot;:public_ip}</pre><p>In this example, we’ve explicitly added one EC2 instance to ignore. Of there is more than one, we could build a List of the instance_ids to ignore:</p><pre>publicList = [&quot;i-0684a4244445eb47c&quot;,&#39;i-0b21f192adb417251&#39;] &lt;snip&gt; if len(public_DNS)&gt;0 and instance_id not in publicList: public_ip = instance[&#39;PublicIpAddress&#39;] result[instance_id] = {&quot;public DNS&quot;: public_DNS,&quot;public IP&quot;:public_ip}</pre><p>So, with just a few minor edits to the pre-built Action, we can refine the list by exempting known public EC2 instances from the report.</p><p>But, hard coding values has its own disadvantages — changes require dipping into the code whenever a new public instance needs to be added. What if we could make the list of public instances to ignore a parameter to the xRunBook?</p><h3>Soft-coding</h3><p>With a small configuration change, we could define a xRunBook or Action input parameter to provide the <em>publicList</em> of instances for our Action. By specifying the list as an input, we can configure this list at runtime (or if there are no changes, we can rely on the default value of the parameter).</p><p>By Clicking <strong><em>Parameters</em></strong> at the top of our xRunBook, we can add a parameter (Click <strong>+ Add Parameter</strong>) called publicList:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*PXhVrcm9I1ZntKxI" /></figure><p>Clicking the edit button on <em>publicList</em> allows a bit better visibility:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/945/0*7nMQNwwHiJ_sXQiT" /></figure><p>We’ve now built a default list of public EC2 instances to ignore, but an updated list can be easily provided at runtime (or even programmatically). We no longer need to define the publicList in the code, so our changes now appear as:</p><pre>#publicLIst is now a parameter, so this line is no longer required #publicList = [&quot;i-0684a4244445eb47c&quot;,&#39;i-0b21f192adb417251&#39;] &lt;snip&gt; if len(public_DNS)&gt;0 and instance_id not in publicList: public_ip = instance[&#39;PublicIpAddress&#39;] result[instance_id] = {&quot;public DNS&quot;: public_DNS,&quot;public IP&quot;:public_ip}</pre><h3>Filter by longevity</h3><p>Perhaps we are only concerned about <strong>new</strong> EC2 instances. We can assume that the legacy public instances are ok, and we just want to identify any that have been recently deployed and set to public.</p><p>The API response from AWS for each instance includes the LaunchTime timestamp for each EC2 instance. We can filter the response to show only NEW public EC2 instances — in the example below — in the last 24 hours:</p><pre>yesterday = datetime.now(pytz.utc) - timedelta(hours=24) &lt;snip&gt; if len(public_DNS)&gt;0 and instance[&#39;LaunchTime&#39;] &gt; yesterday: public_ip = instance[&#39;PublicIpAddress&#39;] result[instance_id] = {&quot;public DNS&quot;: public_DNS,&quot;public IP&quot;:public_ip}</pre><p>All of the public EC2 instances in the region queried are over a day old, so the result is <em>{}</em>.</p><h3>Prebuilt, but modular</h3><p>An advantage of using unSkript is that you can begin building RunBooks immediately by utilizing our library of pre-built Actions. But, if the available Action does not 100% fit your needs, it can be easily modified with Python to exactly match the outcome that you require.</p><p>The ability to quickly build, modify and configure with “off the shelf” Actions is one of the reasons unSkript’s users find such value in our xRunBook engine. Want to give it a spin? There’s a Docker install ( <a href="https://github.com/unskript/Awesome-CloudOps-Automation">instructions on GitHub</a>), or give the <a href="https://us.app.unskript.io/">free trial of our SAAS product</a> a spin. We also love contributions, so if you have modified an Action (or created a new one!) we’d love a <a href="https://docs.unskript.com/unskript-product-documentation/guides/contribute-to-open-source">Pull request</a>. If you have any questions — join the <a href="https://communityinviter.com/apps/cloud-ops-community/awesome-cloud-automation">Slack Community</a> and we’ll be happy to help.</p><p><em>Originally published at </em><a href="https://unskript.com/extending-unskript-actions-quick-customizations-of-off-the-shelf-code/"><em>https://unskript.com</em></a><em> on January 5, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a7a09f0c7270" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Will AI replace us? Using ChatGPT to create Python Actions for unSkript]]></title>
            <link>https://blogs.unskript.com/will-ai-replace-us-using-chatgpt-to-create-python-actions-for-unskript-f4448c9473?source=rss-99312f6126fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4448c9473</guid>
            <dc:creator><![CDATA[Doug Sillars]]></dc:creator>
            <pubDate>Tue, 20 Dec 2022 00:00:21 GMT</pubDate>
            <atom:updated>2023-01-27T03:05:09.138Z</atom:updated>
            <content:encoded><![CDATA[<p>Over the last few weeks, ChatGPT has been the buzz of the development world. One of the biggest questions that has been asked is “Is the AI coming to replace developers?” Will a fleet of Daleks come after us shouting “exterminate?” Or will AI code generators just become another tool in our arsenal? In this post, we’ll look at the code generated by ChatGPT, and how good (or not good) it actually is.</p><p>If you have not yet tried ChatGPT, you can sign up at OpenAI for a free account, and then head to <a href="https://chat.openai.com/chat">https://chat.openai.com/chat </a>and start asking questions. The AI answers in a conversational way, and remembers previous answers, allowing you to build on top of previous answers and refine the result. If you plan to use ChatGPT to generate code, expect to use this feature a lot.</p><p>If you ask Chat GPT to create code for you, it will, and it will even add comments, and describe what the code is doing. At unSkript, we are building a CloudOps system with hundreds of Actions that can be put together in unique ways — connecting your services with observability and automated remediation. As a result, we are releasing dozens of new <a href="https://docs.unskript.com/unskript-product-documentation/lists/action_list">Actions</a> (microservices that complete a distinct function) into our Open Source Repository.</p><p>Since unSkript’s Actions are written in Python (and not a domain specific language), I thought it would be neat to see if ChatGPT might be able to help us accelerate the creation of these Actions.</p><h3>Warming up</h3><p>Like any new tool, you have to understand what makes ChatGPT ‘ticks’ in order to make it work for you. Let’s begin by trying to get GPT to copy some Actions that we have recently <a href="https://unskript.com/managing-your-cloud-costs-with-cloudops-automations-part-1/">blogged about</a> — analyzing and adding tags to AWS EC2 resources.</p><p>Lets start with asking to check an EC2 instance for a specific tag:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>The result is nearly exactly the same code as what was used in our blog post (and our published <a href="https://github.com/unskript/Awesome-CloudOps-Automation/blob/master/AWS/legos/aws_filter_untagged_ec2_instances/aws_filter_untagged_ec2_instances.py">Action</a>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>However, the code only works for one EC2 instance, and our Action needs to look at all of the EC2 instances in our account. So we can ask for it to be extended, and chatGPT comes up with an acceptable response to get every EC2 instance, and see if there is a “CostCenter” Tag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>I find the variable naming system here a bit counterintuitive — naming the list of reservations ‘ <em>instances</em>’ and then naming each instances ‘ <em>reservation</em> ‘, but otherwise this is lock step with the code that humans used to iterate through all of our EC2 instances and then determine the presence or absence of a tag.</p><h3>Tagging the Instances</h3><p>We could take the results from this Action, and then build another Action to add the CostCenter tag to those instances that do not have the tag. Let’s ask the bot to help:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>The bot has nailed it again! This can be copied right into the unSkript interface, and it’ll work. Now, let’s ask GPT to abstract this a bit, and make the key:value pair variables, rather than hard coded. This again works like a charm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><h3>Pushing our GPT queries into new Directions</h3><p>By using Chat GPT to duplicate Actions that already exist, we are able to better understand how to generate results that might work when we branch into new Actions that have not yet been written. Let’s keep our queries to AWS and EC2 CloudOps, but build an Action to find out the age of all of our EC2 instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>The Chatbot’s code is similar to the code it used in the earlier example (with the same funny variable naming schema). And, like a good computer, it does what I asked it to do -&gt; it will print a line for each instance telling me the age. This is great, but not terribly useful for further usage. Perhaps you’d like to restart EC2 instances that have been running for &gt;180 days (the old “turn it off and turn it back on” approach), so having this list in a way that can be manipulated would be useful. So I defined a JSON format that I would like: key is instanceID, and the value is the age. I then asked Chat GPT to return the results in that way:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>Copying this code into unSkript, this works a charm.</p><h3>Monitoring CPU usage</h3><p>Another issue that can arise with EC2 instances is that the CPU is too high. Can ChatGPT build an Action to list the CPU usage of each EC2 instance? This will use two calls to AWS — one call to EC2 to get the list of instances, and then a 2nd round of calls to CloudWatch to get the CPU utilization.</p><p>The first time I asked Chat GPT to generate this code — it did so flawlessly. But, when getting screenshots for this post, it failed. It attempted to make the 2nd set of calls to the EC2 endpoint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>In the 2 red boxes, both calls are being made to the EWC2 endpoint. This is easily corrected with a little prodding. Now there are 2 calls, one to EC2 and the other to cloudwatch:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>Once corrected, this runs. However, not every EC2 instance responds with a CPU usage, so a short error check (is the array’s length &gt;0) to populate the data prevents the Action from breaking in practice:</p><blockquote><em># Calculate the average CPU usage for the past 24 hours #error check for the presence of CPU usage data if len(response[‘Datapoints’])&gt;0: cpu_utilization_values = [datapoint[‘Average’] for datapoint in response[‘Datapoints’]] avg_cpu_utilization = sum(cpu_utilization_values) / len(cpu_utilization_values) results[instance_id] = avg_cpu_utilization else: results[instance_id] = “error”</em></blockquote><p>The response from AWS has 24 entries, and here we have averaged them all to get the full 24 hour average.</p><h3>Trust, but verify</h3><p><strong>Note:</strong> in some iterations, the bot did not do the average calculation and just assigned [datapoint[‘Average’][0] as the average (the first entry in the array — not the true average). So, it is very important to check all the inputs and outputs used the the bot, and ensure that it is using them correctly.</p><h3>One last example: Bot goes a bit off the rails</h3><p>This last example should have been quite similar to the previous one — checking the Network data in and out of each EC2 instance over the last hour:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>I expected the code to first query EC2 for the list of instances, and then hit up Cloudwatch for the data. But we got a bit of a mashup between a SQL query and Python in the result. Instead of a for loop over each instance, we got:</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /></figure><p>Is it a SQL query? Or is it Python? Needless to say, this does not work.</p><blockquote><em>However, the Cloudwatch query to get 2 the metrics (bytes in and out of each instance) does work, and the code correctly outputs the data as dict. By reusing the for loop that the BOT created in previous queries, and switching in the new query, I was able to get the code to run. However, in error checking, I found that sometimes CloudWatch returns a null value tor a result. Adding a little error correction at the end fixes this. Also — CloudWatch reports the values in Bytes, so we convert to MB for easier comparisons. if len(metrics[‘MetricDataResults’][0][‘Values’])&gt;0: NetworkInMB = round(float(metrics[‘MetricDataResults’][0][‘Values’][0])/1024/1024,2) else: NetworkInMB = “error” if len(metrics[‘MetricDataResults’][1][‘Values’])&gt;0: NetworkOutMB = round(float(metrics[‘MetricDataResults’][1][‘Values’][0])/1024/1024,2) else: NetworkOutMB = “error” metricsIwant = {metrics[‘MetricDataResults’][0][‘Label’] : NetworkInMB, metrics[‘MetricDataResults’][1][‘Label’] : NetworkOutMB} result[instance_id] = metricsIwant</em></blockquote><h3>Conclusion</h3><p>Are the bots coming for our jobs? In these few examples, ChatBot generally did ok. There were certainly bugs in the code that was generated, and a solid code review of what the bot has generated <em>must</em> be undertaken to ensure that it is providing what was asked for.</p><p>That said, generating 90% of the code correctly allows us to spend that extra time error checking and verifying (that we should be doing anyway).</p><p>Using ChatGPT allowed me to create these Python unSkript Actions in a fraction of the time that it would have taken me to do them solo. By generating much of the boilerplate code, I could take the extra time to ensure that the results made sense.</p><p>Want to try to build your own CloudOps Actions with unSkript? Sign up for our <a href="https://us.app.unskript.io/xRunBooks">free trial</a>. And look for the Actions built in this post using ChatGPT to appear in our <a href="https://github.com/unskript/Awesome-CloudOps-Automation">Awesome-CloudOps-Automation</a> Github repository in the very near future!</p><p><em>Originally published at </em><a href="https://unskript.com/will-ai-replace-us-using-chatgpt-to-create-python-actions-for-unskript/"><em>https://unskript.com</em></a><em> on December 20, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4448c9473" width="1" height="1" alt=""><hr><p><a href="https://blogs.unskript.com/will-ai-replace-us-using-chatgpt-to-create-python-actions-for-unskript-f4448c9473">Will AI replace us? Using ChatGPT to create Python Actions for unSkript</a> was originally published in <a href="https://blogs.unskript.com/">unSkript</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing your Cloud Costs with CloudOps Automation Part 1: Identifying Your Resources with Tags]]></title>
            <link>https://blogs.unskript.com/managing-your-cloud-costs-with-cloudops-automation-part-1-identifying-your-resources-with-tags-d7428b224bdd?source=rss-99312f6126fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7428b224bdd</guid>
            <dc:creator><![CDATA[Doug Sillars]]></dc:creator>
            <pubDate>Thu, 15 Dec 2022 00:00:25 GMT</pubDate>
            <atom:updated>2022-12-16T01:38:31.705Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*5YC5OJdVwldD5PibtD3nxw.jpeg" /></figure><p>Moving systems to the cloud makes a lot of sense operationally — letting the experts take care of the infrastructure, and let us build what we need to make our company successful.</p><p>But this comes at a substantial downside — your monthly cloud bill. Cloud providers have made it insanely easy to spin up new servers and features, but without careful auditing — it is *very* easy to leave money on the table due to unused or improperly sized resources remaining active on our cloud provider. In this series of posts, we’ll use unSkript to uncover unused assets in your cloud account, and then either alert the team of their existence, or remove them automatically.</p><p>This of course leads to a catch 22 — how do you know what is safe to remove — and what will bring down production? In order to better identify our cloud resources, we need a good tagging strategy.</p><p>So, to kick off our cost savings series of posts, we’ll begin with a discussion on tagging your cloud resources.</p><h3>Why Tag your resources?</h3><p>Tags are key:value pairs that describe your cloud function. With AWS, you can use any value for your key — giving the ultimate in customization. AWS has a number of <a href="https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html#tag-best-practices">best practices</a> for tagging your resources.</p><p>Tagging allows us to easily identify our cloud components and quickly determine what the components do. AWS recommends “overtagging” vs “undertagging.” In many ways, this is the CloudOps analogy to commenting code. With a ‘well-tagged” set of resources, auditing each instance becomes easier.</p><p><strong>Perhaps most importantly — it becomes easy to find resources that are no longer needed, allowing for them to be turned off keeping your cloud bill in check.</strong></p><h3>Tag Strategy</h3><p>There is no definitive set of tags that should be used, but here are some that are often discussed:</p><ul><li><strong>Environments:</strong> If your different environments are all in the same Cloud, labeling each object with an Environment key, and values like development, staging, production help you understand where in the deployment process your instances lie.</li><li><strong>Department: </strong>Tagging the department that owns/controls the resource has a number of important features:</li></ul><ol><li>The team can track their cloud installs.</li><li>If there is a problem with the instance, the correct team can be easily identified and notified that there is an issue.</li></ol><ul><li><strong>Cost center: </strong>Identify teams with higher spends. More easily break down budgeting for cloud billing.</li></ul><h3>Building your tagging strategy.</h3><p>If you have not yet built out your strategy, you probably have dozens (hundreds) of untagged cloud objects. Since there is no way for one person or team to know what each instance is, or even if it is still in use, we need to add tags.</p><p>So the first step is to identify each object, and contact the owners to add tags to the instances.</p><p>Of course, it would be best to give your team an automated way to add tags to their instances, so that they do not lose a lot of bandwidth complying with the new requirements (with the added benefit that an easy onboarding will make your new tagging policy go faster with less friction. Here’s how we have done this at unSkript (using unSkript xRunBooks and Actions, or course).</p><h3>Step 1 Find resources with zero tags</h3><p>unSkript has a built in action called “ This Action calls all EC2 instances that have no tags attached to them, We can search for this Action and drag it into our workflow. (In our <strong>AWS Get Untagged Resources.” </strong><a href="https://us.app.unskript.io/">Free Sandbox</a>, create a new xRunBook, and then search for the action)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*bHlvP7-giiExvBNM.gif" /></figure><p>Connect your AWS Credentials (learn how to create a <a href="https://docs.unskript.com/unskript-product-documentation/guides/connectors/aws#authentication">connection to AWS</a>), and add your Region (you can either change the value in the configurations to the right, OR change the parameters in the top menu — this refers to the variable <em>Region</em>). When run, this Action gives a list if instanceIds that have no tags. We’d like a bit more information, so we’ll edit the xRunBook to look like this:</p><pre>def aws_get_untagged_resources(handle, region: str) -&gt; List: print(&quot;region&quot;,region) <br>  ec2Client = handle.client(&#39;ec2&#39;, region_name=region) <br>  #res = aws_get_paginator(ec2Client, &quot;describe_instances&quot;, &quot;Reservations&quot;) <br>  res = aws_get_paginator(ec2Client, &quot;describe_instances&quot;, &quot;Reservations&quot;) <br>  result = [] for reservation in res: for instance in reservation[&#39;Instances&#39;]: <br>    try: #has tags <br>        tagged_instance = instance[&#39;Tags&#39;] <br>    except Exception as e: <br>        #no tags <br>        result.append({&quot;instance&quot;:instance[&#39;InstanceId&#39;],&quot;type&quot;:instance[&#39;InstanceType&#39;],&quot;imageId&quot;:instance[&#39;ImageId&#39;], &quot;launched&quot;:instance[&#39;LaunchTime&#39;] }) <br>  <br>  return result<br></pre><p>We make these changes to give a bit more information about each instance that is untagged. For example:</p><p>[{‘imageId’: ‘ami-094125af156557ca2’,‘instance’: ‘i-049b54f373769f51b’,</p><p>‘launched’: datetime.datetime(2022, 12, 14, 17, 48, 49, tzinfo=tzlocal()),</p><p>‘type’: ‘m1.small’},</p><p>Now we can reach out to the rest of the team to see if anyone knows about this m1.small instance launched on 12/14/22 from a specific AMI.</p><h3>Step 2: Add tags to found instances:</h3><p>We now have a list of all of the instanceIds that have no tags. Now we can use a new action that attaches tags to an EC2 instance to begin the process of bringing the instance into tagging compliance.</p><pre>This action has 3 inputs:instanceId, Tag_Key, and Tag_Value. def aws_tag_resources(handle, instanceId: str, tag_key: str, tag_value: str, region: str) -&gt; Dict: ec2Client = handle.client(&#39;ec2&#39;, region_name=region) result = {} try: response = ec2Client.create_tags( Resources=[ instanceId ], Tags=[ { &#39;Key&#39;: tag_key, &#39;Value&#39;: tag_value }, ] ) result = response except Exception as error: result[&quot;error&quot;] = error return result</pre><p>Running this Action adds the key:value tag into the EC2 instance.</p><h3>Step 3: Compliance check</h3><p>Finally, we’ll build one last Action that checks all tag Keys against the required list of keys, and returns those instances that are mossing a required tag:</p><pre>def aws_get_resources_out_of_compliance(handle, region: str, requiredTags: list) -&gt; List: ec2Client = handle.client(&#39;ec2&#39;, region_name=region) #res = aws_get_paginator(ec2Client, &quot;describe_instances&quot;, &quot;Reservations&quot;) res = aws_get_paginator(ec2Client, &quot;describe_instances&quot;, &quot;Reservations&quot;) result = [] for reservation in res: for instance in reservation[&#39;Instances&#39;]: try: #has tags allTags = True keyList = [] tagged_instance = instance[&#39;Tags&#39;] #print(tagged_instance) #get all the keys for the instance for kv in tagged_instance: key = kv[&quot;Key&quot;] keyList.append(key) #see if the required tags are represented in the keylist #if they are not - the instance is not in compliance for required in requiredTags: if required not in keyList: allTags = False if not allTags: # instance is not in compliance result.append({&quot;instance&quot;:instance[&#39;InstanceId&#39;],&quot;type&quot;:instance[&#39;InstanceType&#39;],&quot;imageId&quot;:instance[&#39;ImageId&#39;], &quot;launched&quot;:instance[&#39;LaunchTime&#39;], &quot;tags&quot;: tagged_instance}) except Exception as e: #no tags result.append({&quot;instance&quot;:instance[&#39;InstanceId&#39;],&quot;type&quot;:instance[&#39;InstanceType&#39;],&quot;imageId&quot;:instance[&#39;ImageId&#39;], &quot;launched&quot;:instance[&#39;LaunchTime&#39;], &quot;tags&quot;: []}) return result</pre><p>This Action reads in a list of required keys, and if an instance does not have all of them — it is returned in an out of compliance list.</p><h3>Conclusion</h3><p>It has been shown that tagging cloud instances makes troubleshooting faster. It also helps you identify cloud objects that are no longer in use — helping you to reduce your cloud bill. For these reasons it makes sense to create a tagging requirement for all instances.</p><p>In this post, we have created a series of Actions that will help you simplify the transition process of bringing all of your existing cloud objects into tagging compliance.</p><p>Feel free to try these Actions in our <a href="https://us.app.unskript.io/">Free Sandbox</a>, or using our <a href="https://github.com/unskript/Awesome-CloudOps-Automation">Docker install</a>. The actions used in this post will soon be available on Github in the xRunBook <a href="https://github.com/unskript/Awesome-CloudOps-Automation/AWS/AWS_Add_Mandatory_tags_to%20EC2.ipynb">Add Mandatory Tags to EC2. </a>Please reach out if you’d like a copy earlier!</p><p><em>Originally published at </em><a href="https://unskript.com/managing-your-cloud-costs-with-cloudops-automations-part-1/"><em>https://unskript.com</em></a><em> on December 15, 2022.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7428b224bdd" width="1" height="1" alt=""><hr><p><a href="https://blogs.unskript.com/managing-your-cloud-costs-with-cloudops-automation-part-1-identifying-your-resources-with-tags-d7428b224bdd">Managing your Cloud Costs with CloudOps Automation Part 1: Identifying Your Resources with Tags</a> was originally published in <a href="https://blogs.unskript.com/">unSkript</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Cloud Ops Auto Remediation: A Holiday Allegory]]></title>
            <link>https://blogs.unskript.com/a-cloud-ops-auto-remediation-a-holiday-allegory-a0b765c905a?source=rss-99312f6126fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0b765c905a</guid>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[christmas-music]]></category>
            <category><![CDATA[runbooks]]></category>
            <category><![CDATA[spotify]]></category>
            <category><![CDATA[remediation]]></category>
            <dc:creator><![CDATA[Doug Sillars]]></dc:creator>
            <pubDate>Mon, 05 Dec 2022 17:23:03 GMT</pubDate>
            <atom:updated>2022-12-05T17:23:03.822Z</atom:updated>
            <content:encoded><![CDATA[<p>Auto remediations <strong>are tools that respond to events with automations able to fix, or remediate, the underlying condition.</strong> Building a demo that features auto remediation fix is hard, because generally modern infrastructure is resilient so keeping it in an error state is difficult. In order to feature an auto-remediation example, we’re going to get a little creative.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FJ7IGm5Skfq0dPn3TrWlDg.jpeg" /></figure><h3>A Holiday Auto Remediation</h3><p>I am writing this post in the first week of December, and let’s face it — holiday music is pretty inescapable this time of year. To describe the auto remediation that we will fix, let’s turn to one of the greatest fiction writers of our time:</p><figure><img alt="Stephen King tweets that he dislikes “Holly Jolly Christmas.”" src="https://cdn-images-1.medium.com/max/1024/1*3_lBdiVbEMhhGkSq2YD1aA.jpeg" /></figure><p>As Mr. King has clearly presented — everyone has a least favorite holiday song, and the playing of this song can . During the holiday season, it is pretty common to use playlists generated by other users on Spotify. Wouldn’t it be great if we could auto remediate the playing of our disliked holiday songs automatically — without any intervention?</p><p>This is a great example of building auto remediation — an xRunBook in unSkript that identifies the song playing, and if there is an “error state” (a song on the blocklist), the RunBook will correct this issue without human intervention.</p><h3>Auto Remediation in Spotify</h3><p>In this post, we will build an auto remediation RunBook for your Spotify account.</p><ol><li>We will create a Spotify app that connects with unSkript.</li><li>Curate a block list of songs.</li><li>We will build a xRunBook that checks to see if Spotify is playing.</li><li>If Spotify is playing a song on the block list, unSkript will automatically remediate the issue by skipping to the next track.</li><li>We can then place this xRunBook on a schedule to run every minute- ensuring that we’ll only hear a few seconds of our least favourite songs (at least when listening on *our* Spotify account). Note: This last step is only possible in the <a href="https://github.com/unskript/Awesome-CloudOps-Automation">Open Source Docker build</a>, or in a SAAS install of unSkript. This won’t work in the sandbox :(</li></ol><p>Let’s get started:</p><h3>Build a Spotify app</h3><p>In order to interface with Spotify, we <a href="https://developer.spotify.com/dashboard/applications">create an app</a> at Spotify.</p><p>When you create an app, you’ll need to submit a redirect url. I used <a href="https://unskript.com/">unskript.com</a> in my example. Once you generate the app, you’ll get a clientId and clientSecret that you will need later to interface with your xRunBook. You can also add your account email as an authorized user of the application:</p><figure><img alt="Screenshot of the Spotify app" src="https://cdn-images-1.medium.com/max/1000/1*5AIO8ckjaDV3amJB0v9_vA.jpeg" /></figure><p>The name and description of my Spotify application gives away *my* reasoning for this app.</p><h3>Building the xRunBook</h3><p>NOTE: For full automation, install <a href="https://github.com/unskript/Awesome-CloudOps-Automation">unSkript locally using Docker</a>. If you just want to follow along the tutorial, you can use our <a href="https://us.app.unskript.io/">free Sandbox</a> to run the xRunBook manually. (If you are using the Sandbox, complete the tutorial.)</p><p>Now we are ready to create our xRunBook.</p><ul><li>In Sandbox, Click xRunBook, and then “+Create”, and connect your RunBook to the proxy you created in the tutorial.</li><li>In Docker, there are instructions to create a new xRunBook in the README file.</li></ul><p>xRunBooks are based on Jupyter Notebooks. Each action is an independent Python application. When the RunBook is executed, each Action is run in order. I have pasted the code for each action below. You’ll need to create a new Action for each code snippet. Do this by Clicking the + Add button at the top, and choosing “Action.”</p><p><strong>Action 1: Install Spotipy</strong></p><p>We’re going to use a Python library to interact with Spotify. In your first action:</p><pre>!pip install spotipy - quiet</pre><p><strong>Action 2: Add our ClientIds.</strong></p><p>In the OSS, and Sandbox, there is no built in Secret vault. so we’ll put them here. Make sure the redirect url matches what you placed in your Spotify application/</p><pre>client_id = &quot;&lt;client ID from Spotify&gt;&quot;<br>client_secret=&quot;&lt;secret from Spotify&quot;<br>client_redirect=&quot;https://unskript.com&quot;</pre><p><strong>Action 3: Connect to Redis</strong></p><p>Note: not needed for Docker, and will not work for Sandbox, but this will work in unSkript SAAS:</p><pre>import redis<br>redis = redis.Redis(host=&#39;&lt;redis-host&gt;&#39;, port=6379, db=0)<br>redis.set(&#39;foo&#39;, &#39;bar&#39;)<br>True<br>redis.get(&#39;foo&#39;)<br>b&#39;bar&#39;<br>print(redis)</pre><p>Spotipy stores the authentication in a local cache — which is fine in the unSkript Docker instance.</p><p>The Sandbox does not have a local cache, nor a Redis instance, so this xRunBook cannot be run on a schedule as a result.</p><p>In our SAAS version, a Redis database can be attached to the xRunBook to ensure that the credentials are stored locally, and can be reused.</p><p><strong>Action 4: Find SongIDs</strong></p><p>Let’s do some searches in the Spotify database to extract the songIds we want to add to our blocklist. Here we are searching for songs sung by Mariah Carey:</p><pre>import spotipy<br>from spotipy.oauth2 import SpotifyClientCredentials<br><br>scope = &quot;user-library-read user-modify-playback-state user-read-playback-state&quot;<br><br>sp = spotipy.Spotify(auth_manager=SpotifyClientCredentials(client_id=client_id,<br>                                               client_secret=client_secret))<br><br>results = sp.search(q=&#39;mariah carey&#39;, limit=5)<br>#print(results)<br>for idx, track in enumerate(results[&#39;tracks&#39;][&#39;items&#39;]):<br>    print(idx, track[&#39;artists&#39;][0][&#39;name&#39;], &quot; &quot;, track[&#39;name&#39;], &quot; &quot; ,track[&#39;id&#39;])</pre><p>The results for this Action are:</p><pre>0 Mariah Carey   All I Want for Christmas Is You   0bYg9bo50gSsH3LtXe2SQn<br>1 Mariah Carey   Fantasy   6xkryXuiZU360Lngd4sx13<br>2 Mariah Carey   Christmas (Baby Please Come Home)   3PIDciSFdrQxSQSihim3hN<br>3 Mariah Carey   We Belong Together   3LmvfNUQtglbTrydsdIqFU<br>4 Mariah Carey   Fantasy (feat. O.D.B.)   2itAOPLerxnnc8KXHMqPWu</pre><p>We want to (ok, I want to) block the song with ID: 0bYg9bo50gSsH3LtXe2SQn.</p><p><strong>Action 5: Build a block list</strong></p><p>This Action defines the array of songs we want to block.</p><pre>songList = [&quot;0bYg9bo50gSsH3LtXe2SQn&quot;, <br>            &quot;4iHNK0tOyZPYnBU7nGAgpQ&quot;,<br>            &quot;0SorhWEyl6wkQ6vYAQt2D0&quot;]</pre><p><strong>Action 6: Authenticate the user</strong></p><p>This requests access for a user at Spotify. We need to read the playback state (is Spotify playing?), and we need permission to modify the state (skip the song!).</p><p>We have commented out the Redis cache_handler. If you are using the SAAS version of unSkript — remove the comment.</p><pre>import spotipy<br>from spotipy.oauth2 import SpotifyOAuth<br>import json<br><br><br>scope = &quot;user-library-read user-modify-playback-state user-read-playback-state user-read-recently-played&quot;<br><br><br><br><br>spUser = spotipy.Spotify(auth_manager=SpotifyOAuth(client_id=client_id,<br>                                               client_secret=client_secret,<br>                                               redirect_uri=client_redirect,<br>                                              # cache_handler=spotipy.cache_handler.RedisCacheHandler(redis),<br>                                               scope=scope,<br>                                               open_browser=False))</pre><p><strong>Action 7: Skip the track</strong></p><p>This step will be interactive. When this action is run, you’ll be asked to visit a url (that does a redirect) and then paste in the redirected url. This url has your authentication token in it. Once this is done, a token is stored locally that is valid for one hour. Every time the xRunBook is run, the token is re-authenticated for another hour.</p><pre>#get current track<br>currentTrack = spUser.current_user_playing_track()<br><br>## only test the playback if there is currently a song playing<br>if currentTrack is not None:<br>    #<br>    track = currentTrack[&quot;item&quot;][&quot;uri&quot;]<br>    print(track)<br>    #remove &#39;spotify:track:&#39; from front of string to get the ID<br>    track = track[14:]<br>    print(track)<br><br>    # all i want for christmas is you. spotify:track:0bYg9bo50gSsH3LtXe2SQn<br>    songs_i_hate = songList<br><br>    for song in songs_i_hate:<br>        print(&quot;song&quot;, song)<br>        if track == song:<br>          print(&quot;ahhh save us&quot;)<br>          spUser.next_track()<br>          break<br>        else:<br>          print(&quot;its all good&quot;)<br>else:<br>    print(&quot;the music is off&quot;)</pre><p>This completes the xRunBook creation. Save the RunBook (by closing it, and then selecting Save)</p><p><strong>Scheduling the RunBook</strong></p><p>In the SAAS (and Sandbox), it is possible to schedule your xRunbooks. By scheduling this xRunBook to run every minute — you can ensuyre that you’ll never have to listen to more than 59 seconds of the songs you dislike.</p><h3>A Holiday Allegory</h3><p>An Allegory is a metaphor that symbolizes an idea or message. Many stories told at Christmas time are allegories (like Dicken’s a Christmas Carol). In this post, we have used Spotify playlists as an allegory to a Cloud System in distress. By auto-skipping songs, our unSkript RunBook is automatically solving a situation without involving a human (potentially paging them out of a “long winder’s nap.”)</p><p>By building a “Skip the horrible track” auto remediation, we show the power of unSkript, and also potentially save the family Christmas by avoiding arguments over the Christmas playlist.</p><p>Interested in learning more about how unSkript can help you build internal auto remediation tooling for your team? Check out our <a href="https://us.app.unskript.io/signup">free trial</a>, star our <a href="https://github.com/unskript/Awesome-CloudOps-Automation">GitHub repository</a> of xRunBooks and Actions, or join our <a href="https://communityinviter.com/apps/cloud-ops-community/awesome-cloud-automation">Slack Community</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0b765c905a" width="1" height="1" alt=""><hr><p><a href="https://blogs.unskript.com/a-cloud-ops-auto-remediation-a-holiday-allegory-a0b765c905a">A Cloud Ops Auto Remediation: A Holiday Allegory</a> was originally published in <a href="https://blogs.unskript.com/">unSkript</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automating the AWS Identity Lifecycle with unSkript (Part 3)]]></title>
            <link>https://blogs.unskript.com/automating-the-aws-identity-lifecycle-with-unskript-part-3-4b66b410774b?source=rss-99312f6126fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b66b410774b</guid>
            <dc:creator><![CDATA[Doug Sillars]]></dc:creator>
            <pubDate>Thu, 01 Dec 2022 02:14:13 GMT</pubDate>
            <atom:updated>2022-12-01T18:43:26.304Z</atom:updated>
            <content:encoded><![CDATA[<p>This week, AWS is celebrating all that is AWS at their re:Invent conference in Las Vegas. Here at unSkript, we are celebrating all that is AWS by highlighting how to automate common AWS tasks with our xRunBooks. In our first two posts in this series (<a href="https://blogs.unskript.com/automate-the-aws-identity-lifecycle-with-unskript-part-1-104edd523c4f">Part 1</a> and <a href="https://blogs.unskript.com/automating-the-aws-identity-lifecycle-with-unskript-part-2-7575edb6ee1b">Part 2</a>) , we built a xRunBook that creates a IAM user, and applied a Managed access policy to the user. In this post, we are going to do the opposite — removing a user from the AWS environment.</p><p>There comes a time when access for a certain identity or user must be removed from your AWS environment. In this post, we’ll create an automated workflow that does just that.</p><p>When creating this article, there was no pre-built workflow to delete an IAM user in the <a href="https://github.com/unskript/Awesome-CloudOps-Automation">open source unSkript xRunBook Library</a>, so we will have to modify an existing workflow to delete the user. (Once this post is completed, the xRunBook will be added to our Open Source library of RunBooks.</p><p>In this case, we’ll use “Create IAM User workflow” from <a href="https://blogs.unskript.com/automating-the-aws-identity-lifecycle-with-unskript-part-2-7575edb6ee1b">our last post</a> in this series. By changing the order of the actions in the workflow, and a few small code edits, we’ll change this workflow from one that c<em>reates</em> new users to one that <em>deletes</em> existing users.</p><h3>Setup</h3><p>If you have not yet created AWS Credentials, <a href="https://docs.unskript.com/unskript-product-documentation/guides/connectors/aws#creating-aws-access-keys">here are the instructions.</a></p><p>The existing order of the Actions in the xRunBook we created in Part 2 is:</p><ol><li>unSkript Internal</li><li>Create IAM user: Create the user</li><li>Create logon profile: add a password</li><li>Add policies: Assign a permission policy</li><li>Get STS identity: get Assigner’s name</li><li>Send Slack message: Posts results in Slack</li></ol><h3>Changes Required</h3><p>Clearly, steps 2–4 are creation steps and they will all be changed to deletion/removal steps. They also must be reordered, as permission policies and passwords must be removed from an identity before it can be deleted.</p><p>Luckily, reordering Actions in unSkript is a Drag-and-drop affair. Click and drag Actions 2–4 (and the corresponding notes) to reorder the Actions as follows:</p><ol><li>unSkript Internal</li><li>Create logon profile: add a password</li><li>Add policies: Assign a permission policy</li><li>Create IAM user: Create the user</li><li>Get STS identity: get Assigner’s name</li><li>Send Slack message: Posts results in Slack</li></ol><h3>Editing the Actions</h3><p>Now we can begin the process of editing the Actions from Creation steps to deletion steps</p><p><strong>Create Login Profile -&gt; Delete Login Profile</strong></p><p>In order to delete an IAM profile, the profile cannot have a password login. Lucki;y, with just a few small changes, we can update this Action to delete the Login Profile.</p><p>Here are lines 34–37:</p><blockquote>response = ec2Client.create_login_profile(</blockquote><blockquote>UserName=UserName,</blockquote><blockquote>Password=Password,</blockquote><blockquote>PasswordResetRequired=True)</blockquote><p>Change <em>ec2Client.</em><strong><em>create</em></strong><em>_login_profile</em> to <em>ec2Client.</em><strong><em>delete</em></strong><em>_login_profile</em>, and remove the two password parameters:</p><blockquote>response = ec2Client.delete_login_profile(</blockquote><blockquote>UserName=UserName)</blockquote><p>Remove lines 58–62 (these may be different depending on your previous edit)</p><blockquote>task.configure(conditionsJson=’’’{</blockquote><blockquote>“condition_enabled”: true,</blockquote><blockquote>“condition_cfg”: “‘User’ in UserInfo”,</blockquote><blockquote>“condition_result”: true</blockquote><blockquote>}’’’)</blockquote><p>The next step in cleaning up this Action is to update the classes and naming to remove evidence of creation, and leave only mentions of deletion.</p><p><strong>Add policies to IAM user -&gt; Remove policies to IAM user</strong></p><p>This is the most complicated step. In order to remove the Policies for the IAM user, we must first identify what policies have been applied. There is an Action called “AWS List Attached User Policies” that we can add to the xRunBook. Search for this Action in the Action search, and drag the Action above the <em>Add Policies to IAM User</em> Action.</p><ul><li><strong>AWS List Attached User Policies</strong></li></ul><p>To configure this new Action to deliver the existing policies for the given user, add your AWS Credentials and user_name as the User Name. Under output, name the output <em>policies</em>. This will output an array of Policies associated with the user.</p><figure><img alt="Screen shot of a successful Action ru n. The 2 Policies are noted in the results window." src="https://cdn-images-1.medium.com/max/1024/1*IQfGjaFkxjDLzhGKjZh2MQ.jpeg" /><figcaption>This user is an Admin!</figcaption></figure><p>Now, back to the <em>Add Policies to user</em> Action. It is built to handle just one policy at a time, so we must extend it to handle an array of policies, and remove them.</p><p>Change the definition<em> aws_attach_iam_policy</em> to</p><blockquote>def aws_detach_iam_policy(handle, user_name: str, policy_name) -&gt; Dict:</blockquote><blockquote>“””aws_attache_iam_policy used to provide user permissions.</blockquote><blockquote>:type handle: object</blockquote><blockquote>:param handle: Object returned from task.validate(…).</blockquote><blockquote>:type user_name: string</blockquote><blockquote>:param user_name: Dictionary of credentials info.</blockquote><blockquote>:type policy_name: string</blockquote><blockquote>:param policy_name: Policy name to apply the permissions to the user.</blockquote><blockquote>:rtype: Dict with User policy information.</blockquote><blockquote>“””</blockquote><blockquote>for policy in policy_name:</blockquote><blockquote>result = {}</blockquote><blockquote>iamResource = handle.resource(‘iam’)</blockquote><blockquote>try:</blockquote><blockquote>user = iamResource.User(user_name)</blockquote><blockquote>response = user.detach_policy(</blockquote><blockquote>PolicyArn=’arn:aws:iam::aws:policy/’+policy</blockquote><blockquote>)</blockquote><blockquote>result = response</blockquote><blockquote>except ClientError as error:</blockquote><blockquote>result = error.response</blockquote><blockquote>return result</blockquote><p>And the last line change to:</p><blockquote>task.execute(aws_detach_iam_policy, lego_printer=unskript_default_printer, hdl=hdl, args=args)</blockquote><p>What we have done is extend the Class to handle an array of Policies (versus just a string containing one policy, and added a loop to iterate through the policies in order to remove them (detach_policy).</p><p>Finally change the configuration of this Action so that the Policy_Name is <em>policies</em> (the output list from the action we just added).</p><figure><img alt="successful removal of all policies" src="https://cdn-images-1.medium.com/max/1024/1*W8s5cl6oIRZshEdqxN1BmQ.jpeg" /></figure><p>For testing purposes, if you rerun the <em>List attached Policies </em>Action, the result should be an empty array: <em>[].</em></p><p><strong>Create IAM user -&gt; Delete IAM user</strong></p><p>Lines 36–42:</p><blockquote>response = ec2Client.create_user(</blockquote><blockquote>UserName=user_name,</blockquote><blockquote>Tags=[</blockquote><blockquote>{</blockquote><blockquote>‘Key’: tag_key,</blockquote><blockquote>‘Value’: tag_value</blockquote><blockquote>}])</blockquote><p>Change create_user to delete_user, and remove the Tags.</p><blockquote>response = ec2Client.delete_user(</blockquote><blockquote>UserName=user_name)</blockquote><p><strong>Slack Message</strong></p><p>Finally, we need to change the Slack message:</p><p>f’IAM user {user_name} deleted by {caller[“Arn”]}’</p><figure><img alt="Slack message showing user has been deleted." src="https://cdn-images-1.medium.com/max/1024/1*kdrCvZW401X3w9ll7gFVqw.jpeg" /><figcaption>Slack message indcicating deletion of a user</figcaption></figure><h3>Final xRunBook Cleanup</h3><p>With the changes above, your xRunBook will now delete the supplied user from the AWS environment. But, we can clean it up a little bit — removing references to Creation, and also removing a few superfulous variables that are still hanging around.</p><p><strong>Parameters</strong></p><p>We should delete the tag_key and tag_value input parameters, as they are no longer referenced in the xRunBook. You can do this by clicking “Parameters” in the top navigation bar, and clicking the trash bin next to these two items.</p><p>Actions that have input parameters that are no longer used: tag_key, tag_value, password. You can delete unused Action parameters by clicking the 3 dot menu in the Action and editing the Inputs.</p><h3><strong>Fast Iteration: Easy Automations</strong></h3><p>In this post, we took an existing xRunBook that <em>creates</em> IAM users and quickly iterated on a few of the Actions to invert the xRunBook to <em>delete</em> IAM users. Since RunBooks are based on Jupyter Notebooks, reordering Actions is easy (drag and drop) and by simply calling different calls in the Python libraries we were able to design an entire workflow quickly.</p><h3>Conclusion</h3><p>In this series of posts, we have created a simple AWS IAM lifecycle toolchain. If your IAM is more complicated, you can use these xRunBooks as a stepping stone — adding additional Actions or xRunBooks to completely automate your AWS IAM lifecycle.</p><p>unSkript can help you automate many of your internal tools and processes. Interested in learning more? Check out our <a href="https://docs.unskript.com/unskript-product-documentation/">Docs</a>, <a href="https://github.com/unskript/Awesome-CloudOps-Automation">GitHub</a>, or reach out in our <a href="https://communityinviter.com/apps/cloud-ops-community/awesome-cloud-automation">Slack Community</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b66b410774b" width="1" height="1" alt=""><hr><p><a href="https://blogs.unskript.com/automating-the-aws-identity-lifecycle-with-unskript-part-3-4b66b410774b">Automating the AWS Identity Lifecycle with unSkript (Part 3)</a> was originally published in <a href="https://blogs.unskript.com/">unSkript</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>