<?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"><channel><title><![CDATA[Anuj Dube]]></title><description><![CDATA[👋 Hi! I'm a Software Developer who writes about Ansible, PowerShell, AWS, Azure, Docker, Kubernetes, Golang, Web development, and all the latest projects I'm c]]></description><link>https://anujdube.com</link><generator>RSS for Node</generator><lastBuildDate>Sat, 16 May 2026 02:32:42 GMT</lastBuildDate><atom:link href="https://anujdube.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Learning AWS Lambda, API Gateway, and S3 by Building Your Own QR Code Generation API]]></title><description><![CDATA[In this tutorial, we will develop a custom QR code generator API and then integrate it into a basic website.

We'll build the API using Node.js and deploy it on AWS Lambda. The API endpoints will be established through API Gateway, and the generated ...]]></description><link>https://anujdube.com/learning-aws-lambda-api-gateway-and-s3-by-building-your-own-qr-code-generation-api</link><guid isPermaLink="true">https://anujdube.com/learning-aws-lambda-api-gateway-and-s3-by-building-your-own-qr-code-generation-api</guid><category><![CDATA[AWS]]></category><category><![CDATA[APIs]]></category><category><![CDATA[aws lambda]]></category><category><![CDATA[S3]]></category><category><![CDATA[API Gateway]]></category><dc:creator><![CDATA[Anuj Dube]]></dc:creator><pubDate>Tue, 31 Oct 2023 17:39:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1698778172475/e5005b09-87ae-421d-8a40-a5127ecf60c5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this tutorial, we will develop a custom QR code generator API and then integrate it into a basic website.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698772065283/45772850-c1c9-49e8-8931-36bb49b459b6.gif" alt class="image--center mx-auto" /></p>
<p>We'll build the API using Node.js and deploy it on AWS Lambda. The API endpoints will be established through API Gateway, and the generated QR codes will be stored in Amazon S3. The only requirement is having an AWS account. If you're within the free tier, following this tutorial should incur no costs, as we'll stay within the free tier limits. However, it's important to delete all AWS resources once you're done practicing to prevent any unexpected charges.</p>
<hr />
<p>AWS Lambda is a serverless compute service provided by AWS (Amazon Web Services) that allows developers to run code in response to events without having to manage servers or runtime environments. Lambda Supports lots of Runtime environments like Node.js, Python, Go, Ruby, Java, .NET etc. It supports custom runtime environments also. You only pay for the compute time you consume - there is no charge when your code is not running.</p>
<p>Under Free Tier AWS Gives 1,000,000 free requests per month which is 3.2 million seconds of free compute time per month for 12 months.</p>
<h2 id="heading-step-1-creating-s3-bucket">Step 1: Creating S3 Bucket</h2>
<p>We will be creating an S3 bucket. and making content inside it publically accessible so we can access our generated QR codes.</p>
<p>Login into AWS and search s3 in the search bar then click on the first result as shown in the image.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698763680300/e8e2590c-f706-4538-b4fa-bd5aa4515933.png" alt class="image--center mx-auto" /></p>
<p>Click on Create Bucket</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698763737106/064dbfb5-d0ab-4efe-9819-41981628d8f3.png" alt class="image--center mx-auto" /></p>
<p>Now Enter the Bucket name it must be unique. Keep all options as default. and then click on the "create bucket" button at the bottom.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698763810857/1b7ee744-070a-4aa7-98e2-07d6c6c5479c.png" alt class="image--center mx-auto" /></p>
<p>Now After Your bucket is created click on the "Permissions" tab. Click on the Edit button on "Block public access".</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698763916446/f5830657-5850-4454-adb3-6f17abb1fc5b.png" alt class="image--center mx-auto" /></p>
<p>uncheck all options and click on "Save Changes". You will be asked to confirm. type confirm.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698764009642/5e5c23d4-fb46-4561-9279-2608b82836ef.png" alt class="image--center mx-auto" /></p>
<p>Now Move down and click on Edit button in "Bucket policy".</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698764101055/df84c6d8-ae53-459a-9751-8fddf964f649.png" alt class="image--center mx-auto" /></p>
<p>Update Bucket Policy like below. Keep in mind to add Your Bucket ARN. You can take it just from above.</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"Version"</span>: <span class="hljs-string">"2012-10-17"</span>,
  <span class="hljs-attr">"Statement"</span>: [
    {
      <span class="hljs-attr">"Effect"</span>: <span class="hljs-string">"Allow"</span>,
      <span class="hljs-attr">"Principal"</span>: <span class="hljs-string">"*"</span>,
      <span class="hljs-attr">"Action"</span>: <span class="hljs-string">"s3:GetObject"</span>,
      <span class="hljs-attr">"Resource"</span>: <span class="hljs-string">"&lt;Your ARN&gt;/*"</span>
    }
  ]
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698764209695/67840c69-423a-47ec-9af0-39220570e45c.png" alt class="image--center mx-auto" /></p>
<p>Now Click on "Save Changes"<br />Now Our S3 Bucket is ready. All files put inside this bucket now will be publically accessible.</p>
<h2 id="heading-step-2-creating-a-lambda-function">Step 2: Creating a Lambda Function</h2>
<p>Search lambda in the search bar then click on the first result as shown in the image.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698761537367/3ecdfe6f-6cbb-443e-a695-51cc48aea5ae.png" alt class="image--center mx-auto" /></p>
<p>Now Click on Create Function</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698761675684/7b494b79-007a-4d48-87e4-b487a7d0341f.png" alt class="image--center mx-auto" /></p>
<p>Then Select the First Option "Author from scratch" and then Enter the Function name. Also, Runtime should be selected as Node.js. Keep Everything default. and Just click on the "Create Function" button.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698761717180/5085b7f3-a18b-4ddb-a67f-1f4c2c555199.png" alt class="image--center mx-auto" /></p>
<p>You Will come across a window like below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698761898791/757eed7c-f190-4901-a451-de7295e6c17c.png" alt class="image--center mx-auto" /></p>
<p>You can explore this window to learn more.</p>
<p>Go to link <a target="_blank" href="https://github.com/Anujsd/lambda-qr-code">https://github.com/Anujsd/lambda-qr-code</a><br />And Clone this Repo in your PC.<br />Open that in your Favourite IDE I will be using vs code.<br />Open index.mjs go to line number 9 and update the bucket name with your bucket name we just created.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698764856868/e2b06c90-4c92-4da3-8242-83fc330a5750.png" alt class="image--center mx-auto" /></p>
<p>Now Run the Command "npm install" to install node dependencies</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698764992349/e3a89018-6858-438d-b482-e1ccef23aeb2.png" alt class="image--center mx-auto" /></p>
<p>Now We are going to create a ZIP of this whole "lambda-qr-code" folder.<br />For Windows open it in File Explorer select all, right-click and click on compress to zip.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698765100952/0a6f3425-a3e4-4f2c-bcc3-181c6c29452e.png" alt class="image--center mx-auto" /></p>
<p>name zip file "lambda-qr-code".<br />For the Sake of this tutorial, we will be uploading code using zip.<br />This ZIP file contains all code and node modules required for the lambda function. As we are using custom packages we need to upload node modules in zip format. otherwise, we could have directly written code on the web interface.</p>
<p>Now to upload this ZIP go to lambda in AWS in the "code" section and click on "upload from".</p>
<p>select option ".zip file" and upload that zip file.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698762353241/9ef66b8c-0155-46ab-94f6-de36c4228bc6.png" alt class="image--center mx-auto" /></p>
<p>After Uploading the File You will see an interface like below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698762433474/a15b7b31-19ec-4088-83a6-f3b67fada244.png" alt class="image--center mx-auto" /></p>
<p>The code won't be visible in the web interface because the file is too large; however, it's quite straightforward, and you can view it below.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> AWS <span class="hljs-keyword">from</span> <span class="hljs-string">'aws-sdk'</span>;
<span class="hljs-keyword">import</span> QRCode <span class="hljs-keyword">from</span> <span class="hljs-string">'qrcode'</span>;

<span class="hljs-comment">// Configure AWS SDK</span>
AWS.config.update({ <span class="hljs-attr">region</span>: <span class="hljs-string">'us-east-1'</span> });
<span class="hljs-keyword">const</span> s3 = <span class="hljs-keyword">new</span> AWS.S3();

<span class="hljs-comment">// Define S3 bucket and key</span>
<span class="hljs-keyword">const</span> bucketName = <span class="hljs-string">'&lt;s3 bucket name&gt;'</span>;
<span class="hljs-keyword">const</span> key = <span class="hljs-string">`qr-codes/<span class="hljs-subst">${<span class="hljs-built_in">Date</span>.now()}</span>.png`</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> handler = <span class="hljs-keyword">async</span> (event) =&gt; {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">JSON</span>.stringify(event));

  <span class="hljs-comment">// Process POST request</span>
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">let</span> requestBody;
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> event.body === <span class="hljs-string">'string'</span>) {
      requestBody = <span class="hljs-built_in">JSON</span>.parse(event.body);
    } <span class="hljs-keyword">else</span> {
      requestBody = event.body; <span class="hljs-comment">// Assuming it's already parsed</span>
    }

    <span class="hljs-keyword">const</span> { url } = requestBody;

    <span class="hljs-keyword">if</span> (!url) {
      <span class="hljs-keyword">return</span> {
        <span class="hljs-attr">statusCode</span>: <span class="hljs-number">400</span>,
        <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({ <span class="hljs-attr">message</span>: <span class="hljs-string">'URL is required'</span>, <span class="hljs-attr">body</span>: requestBody }),
      };
    }

    <span class="hljs-comment">// Generate QR code</span>
    <span class="hljs-keyword">const</span> qrCodeBuffer = <span class="hljs-keyword">await</span> QRCode.toBuffer(url);

    <span class="hljs-comment">// Upload QR code to S3</span>
    <span class="hljs-keyword">await</span> s3
      .putObject({
        <span class="hljs-attr">Bucket</span>: bucketName,
        <span class="hljs-attr">Key</span>: key,
        <span class="hljs-attr">Body</span>: qrCodeBuffer,
        <span class="hljs-attr">ContentType</span>: <span class="hljs-string">'image/png'</span>,
      })
      .promise();

    <span class="hljs-comment">// Construct the public URL of the QR code</span>
    <span class="hljs-keyword">const</span> publicUrl = <span class="hljs-string">`https://<span class="hljs-subst">${bucketName}</span>.s3.amazonaws.com/<span class="hljs-subst">${key}</span>`</span>;

    <span class="hljs-comment">// Return response with CORS headers</span>
    <span class="hljs-keyword">return</span> {
      <span class="hljs-attr">statusCode</span>: <span class="hljs-number">200</span>,
      <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({ <span class="hljs-attr">qrCodeUrl</span>: publicUrl }),
    };
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error generating QR code:'</span>, error);
    <span class="hljs-keyword">return</span> {
      <span class="hljs-attr">statusCode</span>: <span class="hljs-number">500</span>,
      <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify({ <span class="hljs-attr">message</span>: <span class="hljs-string">'Internal Server Error'</span> }),
    };
  }
};
</code></pre>
<p>Now We will be giving our lambda function permission to add generated QR in s3.</p>
<p>for that go to the "Configuration" Tab then "Permissions" and click on the "Role name" link. It will be opened in a new tab.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698768689900/269788a5-d16b-47c5-9bf4-b94c18768ebf.png" alt class="image--center mx-auto" /></p>
<p>Now in a newly opened window. click on "Add permissions" and then "Attach policies".</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698768783421/9e0f926e-7426-49c9-8861-8c952b844ae9.png" alt class="image--center mx-auto" /></p>
<p>a new window will be opened. Search "s3" in that and select "<a target="_blank" href="https://us-east-1.console.aws.amazon.com/iamv2/home#/policies/details/arn%3Aaws%3Aiam%3A%3Aaws%3Apolicy%2FAmazonS3FullAccess">AmazonS3FullAccess</a>" policy. and click on the "add permissions" button at the bottom.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698768860667/d497edc2-7464-4191-be03-20f23466b6ac.png" alt class="image--center mx-auto" /></p>
<p>Now go to lambda Function.</p>
<p>We will be testing If it's working or not.<br />Click on the "Test" Section. Select options like below and add below JSON which is our test payload.</p>
<pre><code class="lang-json">{
  <span class="hljs-attr">"body"</span>: {
    <span class="hljs-attr">"url"</span>: <span class="hljs-string">"https://anujdube.com/"</span>
  }
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698762937086/bb144d31-8d48-476b-8534-94f01155994d.png" alt class="image--center mx-auto" /></p>
<p>Click on "Save" and then click on the "Test" button.<br />After Successful execution, you will see the output like below. To see detailed logs you can click on the "logs" link.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698769022990/44e65374-3713-4f65-bb64-2d213a0326cb.png" alt class="image--center mx-auto" /></p>
<p>Now Our lambda function is ready we are going to add an API gateway to this lambda function.</p>
<h2 id="heading-step-3-attaching-api-gateway-to-lambda-function">Step 3: Attaching API gateway to lambda function</h2>
<p>Search API Gateway in the search bar then click on the first result as shown in the image.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698769249545/a0d7ac82-fb1c-4d9a-b46b-4e11375b8b83.png" alt class="image--center mx-auto" /></p>
<p>after opening it. Click on the "build" option in HTTP API.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698769299119/af25091f-5670-4e66-9bc6-1861742f6c3f.png" alt class="image--center mx-auto" /></p>
<p>In "Intergrations" select our lambda function as shown below. and add name to API.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698769372592/58afa018-d823-4491-a6cd-68587c8710ba.png" alt class="image--center mx-auto" /></p>
<p>click on next. in routes. add a POST route like below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698769431464/b2a53d9b-b43e-4572-a956-5bddb08c6113.png" alt class="image--center mx-auto" /></p>
<p>Now Click on next. keep everything default. and click on the "Create" button.</p>
<p>You will see your API created like below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698769612496/eccdcf50-8554-428c-ad27-bf87796913ac.png" alt class="image--center mx-auto" /></p>
<p>Now open your API. On the left-hand side click on the section after "VPC links".</p>
<p>and in there you can see the invoke URL. this is your API URL.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698769662116/73aff34b-1662-4126-856f-b5c8ae47cbea.png" alt class="image--center mx-auto" /></p>
<p>You can use this URL and do a POST request using POSTMAN. It will be successful.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698769788090/dbff412b-8205-4770-b4c3-70e2f3b9aeee.png" alt class="image--center mx-auto" /></p>
<p>But if you try to use this URL in any application you might get CORS errors like below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698769949072/4ee473e6-3de6-4ce0-806d-3427fd2e7cc3.png" alt class="image--center mx-auto" /></p>
<p>To resolve these errors click on CORS on the left-hand side. and click on "configure"</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698769981198/8bdf30c0-1140-4cdd-9f93-894e555ccaf5.png" alt class="image--center mx-auto" /></p>
<p>Add values as below and click on "Save"</p>
<p><strong>Access-Control-Allow-Origin</strong> : <em>*</em></p>
<p><strong>Access-Control-Allow-Headers</strong> : <em>Content-Type, x-requested-with</em></p>
<p><strong>Access-Control-Allow-Methods</strong> : <em>OPTIONS, POST</em></p>
<p>At the moment, we are permitting access from all origins. However, for enhanced security in a production environment, it's advisable to restrict access to just your domain name.</p>
<p>Click on the "save" button.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698770293550/641a1dcc-9022-40d9-81ca-be414d80014e.png" alt class="image--center mx-auto" /></p>
<p>Now You will not face any CORS Errors While using your API in any app.</p>
<h2 id="heading-step-4-integrating-the-created-api-into-a-website">Step 4: Integrating the Created API into a Website</h2>
<p>Now we will be trying to use the created API in a simple app.</p>
<p>Click on the below link and clone the repo<br /><a target="_blank" href="https://github.com/Anujsd/qr-code-front-end">https://github.com/Anujsd/qr-code-front-end</a><br />it just has 3 files.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698770519594/924b8bd2-b94f-4f34-b847-44709c9da54e.png" alt class="image--center mx-auto" /></p>
<p>open script.js</p>
<p>and on line number 1. update your API endpoint</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698770577898/c1ee76ac-c1f4-439f-b398-03b05db39ca8.png" alt class="image--center mx-auto" /></p>
<p>now if you open index.html</p>
<p>you will see UI like below</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698770628869/1bbb0ec2-3b00-42c3-a8e6-f95fb0d9ef71.png" alt class="image--center mx-auto" /></p>
<p>enter any link to shorten and you will see a QR code generated for that link<br />you can test if the QR code is correct or not.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1698770703619/71d4fe76-6b9a-4c74-9a57-d06b6d17ac07.png" alt class="image--center mx-auto" /></p>
<p>Now You can host this website online if needed.</p>
<hr />
<p>In this way, We developed our custom QR Code generation API utilizing AWS Lambda. If you encounter any issues or spot any errors in the article, please don't hesitate to contact me.</p>
]]></content:encoded></item><item><title><![CDATA[Ansible Overview]]></title><description><![CDATA[In the Field of IT, Automation and Configuration management have become indispensable. As systems grow in complexity, the need to manage and provision them in a reproducible and scalable manner is crucial. Here Ansible can help it's a simple, agentle...]]></description><link>https://anujdube.com/ansible-overview</link><guid isPermaLink="true">https://anujdube.com/ansible-overview</guid><category><![CDATA[automation]]></category><category><![CDATA[ansible]]></category><category><![CDATA[puppet]]></category><category><![CDATA[chef]]></category><dc:creator><![CDATA[Anuj Dube]]></dc:creator><pubDate>Sun, 22 Oct 2023 17:21:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1697994890226/d8253972-4f93-4a62-a63e-94ba6f9dc4fd.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In the Field of IT, Automation and Configuration management have become indispensable. As systems grow in complexity, the need to manage and provision them in a reproducible and scalable manner is crucial. Here Ansible can help it's a simple, agentless IT automation tool that has become a go-to solution for many administrators and developers.</p>
<hr />
<h2 id="heading-what-is-ansible">What Is Ansible?</h2>
<p>Ansible is an open-source automation tool that helps in software provisioning, configuration management, and application deployment. Developed in Python, it uses a YAML to describe system configurations, making it readable and easy to implement. With its agentless architecture, all you need is SSH access and Python installed on the target nodes. In the case of Windows, It can use Winrm to connect to the Windows host and execute automations. Not only servers you can manage network devices like routers, switches etc with Ansible.</p>
<h2 id="heading-ansible-architecture">Ansible Architecture</h2>
<p><img src="https://pbs.twimg.com/media/F88nPJBXAAAXeqm?format=jpg&amp;name=900x900" alt="Ansible Architecture Central node pushing configuration to managed nodes." /></p>
<p>Ansible's design is straightforward and Easy to understand:</p>
<ol>
<li><p><strong>Control Node:</strong> This is the machine where Ansible is installed and from which all tasks and playbooks are run.</p>
</li>
<li><p><strong>Managed Nodes:</strong> These are the systems that are managed by the control node. No agents are installed on these systems.</p>
</li>
<li><p><strong>Inventory:</strong> A file that lists all managed nodes.</p>
</li>
<li><p><strong>Playbooks:</strong> Written in YAML, these define the desired states of systems, describing tasks to be executed on managed nodes.</p>
</li>
<li><p><strong>Modules:</strong> These are units of code Ansible executes. With over a thousand modules, Ansible can manage almost any IT component.</p>
</li>
</ol>
<p>Ansible communicates with its managed nodes using SSH. but, for Windows nodes, it utilizes WinRM.</p>
<p>One of the standout features of Ansible is its agentless nature. This means there's no need to install any additional software on the managed nodes. Instead, Ansible is only installed on the control node. The configurations/Automation Steps are stored in files called playbooks written in YAML, while the list of nodes it manages is documented in an inventory file, typically in INI format. To ensure security, the credentials used to connect to the managed nodes are stored securely in the Ansible Vault, where they are encrypted.</p>
<p>When it's time to execute tasks on the managed nodes, Ansible converts these tasks from the playbooks into small Python scripts called modules. These modules are then dispatched to the managed nodes for execution. This process showcases Ansible's "push" mechanism, where configurations are actively sent to the managed nodes.</p>
<p>For IT devices like networking equipment that have limited computing power and constraints, Ansible runs modules on the control node instead of directly on the devices. These modules then produce specific commands tailored for each device or initiate API requests to automate various tasks.</p>
<p>Automation Execution is idempotent means if you run an Ansible playbook once or multiple times, the end state of the target system will remain the same. This means repeated playbook runs won't unintentionally change systems, making Ansible's automation dependable.</p>
<h2 id="heading-why-use-ansible">Why use Ansible?</h2>
<ol>
<li><p><strong>Open Source</strong>: Being open-source, Ansible benefits from collective expertise, allowing for rapid improvements.</p>
</li>
<li><p><strong>Simplicity</strong>: Ansible's declarative language (YAML) means that even those unfamiliar with programming can understand and write playbooks.</p>
</li>
<li><p><strong>Agentless</strong>: There's no need to install any software on the managed nodes. This reduces overhead and potential attack vectors.</p>
</li>
<li><p><strong>Versatility</strong>: From managing configurations and deploying applications to orchestrating complex workflows, Ansible can handle it all. It can even manage Cloud Infrastructure like AWS, Azure, Google Cloud, VMware, etc.</p>
</li>
<li><p><strong>Community Support</strong>: A large, active community ensures that new modules are continually added, and existing ones are maintained.</p>
</li>
<li><p><strong>Extensibility</strong>: With its modular architecture, it's easy to extend Ansible to support custom or niche requirements. Lots of pre-created modules are present for various use cases. You can write your custom modules using languages like Python, bash, PowerShell, etc., returning JSON.</p>
</li>
</ol>
<h2 id="heading-community-ansible-vs-redhat-ansible-automation-platform">Community Ansible Vs RedHat Ansible Automation Platform</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697993848826/81144417-fb25-45d7-8bbb-32afc1f278e7.webp" alt class="image--center mx-auto" /></p>
<p>Community Ansible is open-source, while the Red Hat Ansible Automation Platform is a commercial offering by Red Hat, which builds on the foundation of Community Ansible.</p>
<p>Community Ansible is perfect for those looking for a free, open-source automation tool with a broad ecosystem.</p>
<p>Red Hat Ansible Automation Platform Provides Professional support, A curated collection of certified modules, Regular updates, better integration with other Redhat products and additional features such as advanced analytics, logging, and integrations making it suitable for enterprises with critical workloads and requirements.</p>
<h2 id="heading-ansible-vs-puppet-vs-chef">Ansible vs Puppet vs Chef</h2>
<p>Comparison of Ansible with other automation tools.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697989176519/d51b111a-eafe-4cfc-94b9-5c8e17265b46.png" alt="Comparison between Ansible Vs Puppet Vs Chef" class="image--center mx-auto" /></p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In the ever-evolving realm of IT, the importance of efficient and scalable management cannot be overlooked. Ansible emerges as a robust solution, offering a blend of simplicity, versatility, and security in its automation capabilities. it's a game-changer in the landscape of IT automation.</p>
]]></content:encoded></item><item><title><![CDATA[Secrets Management with Ansible Vault: A Comprehensive Guide with Examples]]></title><description><![CDATA[Ansible is a powerful automation tool. When automating various tasks, you may need to utilize sensitive information such as passwords, API keys, and SSH keys. Storing this data in plain text can pose security risks. To effectively manage such sensiti...]]></description><link>https://anujdube.com/secrets-management-with-ansible-vault-a-comprehensive-guide-with-examples</link><guid isPermaLink="true">https://anujdube.com/secrets-management-with-ansible-vault-a-comprehensive-guide-with-examples</guid><category><![CDATA[Devops]]></category><category><![CDATA[ansible]]></category><category><![CDATA[Ansible Vault]]></category><category><![CDATA[ansible-playbook]]></category><category><![CDATA[automation]]></category><dc:creator><![CDATA[Anuj Dube]]></dc:creator><pubDate>Sun, 15 Oct 2023 12:19:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1697372106417/0ca5b162-410a-45ec-b943-d9fc3181147c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Ansible is a powerful automation tool. When automating various tasks, you may need to utilize sensitive information such as passwords, API keys, and SSH keys. Storing this data in plain text can pose security risks. To effectively manage such sensitive information, Ansible offers a built-in feature known as Ansible Vault. It has various commands to help in this task. Let's take a look at what Ansible Vault is and how you can use it to make sure your secrets stay secret.</p>
<hr />
<h3 id="heading-what-is-ansible-vault"><strong>What is Ansible Vault?</strong></h3>
<p>Ansible Vault is a feature that helps secure sensitive data within Ansible projects. It allows users to encrypt entire files or individual variables, protecting them with a password. This ensures that even if the codebase is compromised, the sensitive information remains secure and inaccessible to unauthorized users. You can place these vault files in source control or distribute them as they are encrypted.</p>
<h3 id="heading-creating-vault-file">Creating Vault File</h3>
<pre><code class="lang-bash">ansible-vault create variables.yml
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697361381862/1022cbbe-faa6-4bc8-a975-5fd9f090c9d8.png" alt class="image--center mx-auto" /></p>
<p>I have added 3 keys like the above. ( ESC button +:wq for write and escape)</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697361599031/ffe3e600-4fa3-4048-9291-f86093790782.png" alt class="image--center mx-auto" /></p>
<p>If you try to see the file you will see it's encrypted.</p>
<p>The first line of the file denotes that it's encrypted using Ansible Vault and using AES256 for encryption.</p>
<h3 id="heading-viewing-vault-file">Viewing Vault File</h3>
<pre><code class="lang-bash">ansible-vault view variables.yml
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697361860022/031a2445-be3e-47bd-a213-ccd6df5f9231.png" alt class="image--center mx-auto" /></p>
<p>You will be asked for a password enter that and you will see file data.</p>
<h3 id="heading-editing-vault-file">Editing Vault File</h3>
<pre><code class="lang-bash">ansible-vault edit variables.yml
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697361491331/e774029e-c8fb-48b0-9e55-10691410464f.png" alt class="image--center mx-auto" /></p>
<p>You will be asked for a password enter that, you can edit your file.</p>
<h3 id="heading-decrypting-encrypted-files">Decrypting Encrypted Files</h3>
<pre><code class="lang-bash">ansible-vault decrypt variables.yml
</code></pre>
<p>You will be asked for a password to enter that. now you can see your decrypted file by simply opening it. To encrypt it again use the below command.</p>
<pre><code class="lang-bash">ansible-vault encrypt variables.yml
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697362224720/fe2fea31-caac-47dc-8f75-b4000a479bfe.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-changing-password">Changing Password</h3>
<pre><code class="lang-bash">ansible-vault rekey variables.yml
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697370798315/45c2c45b-f52a-4346-9255-375c89758e25.png" alt class="image--center mx-auto" /></p>
<p>You will be asked for an old password. and then a new password to be set. and after a successful password change, you will get output like the above.</p>
<h3 id="heading-using-encrypted-variables-in-playbook">Using Encrypted Variables in Playbook</h3>
<p>Let's say you want to find the location details of the server using its IP. we are going to use <a target="_blank" href="https://ipgeolocation.io/">ipgeolocation</a> API for that.</p>
<p>Create playbook <strong>location.yml</strong></p>
<pre><code class="lang-yaml"><span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Get</span> <span class="hljs-string">IP</span> <span class="hljs-string">Location</span> <span class="hljs-string">Details</span>
  <span class="hljs-attr">hosts:</span> <span class="hljs-string">localhost</span>
  <span class="hljs-attr">connection:</span> <span class="hljs-string">local</span>
  <span class="hljs-attr">gather_facts:</span> <span class="hljs-literal">no</span>
  <span class="hljs-attr">vars_files:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">secrets.yml</span>
  <span class="hljs-attr">tasks:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Install</span> <span class="hljs-string">Requests</span> <span class="hljs-string">Library</span>
      <span class="hljs-attr">pip:</span>
        <span class="hljs-attr">name:</span> <span class="hljs-string">requests</span>
        <span class="hljs-attr">state:</span> <span class="hljs-string">present</span>

    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Get</span> <span class="hljs-string">IP</span> <span class="hljs-string">location</span> <span class="hljs-string">details</span>
      <span class="hljs-attr">uri:</span>
        <span class="hljs-attr">url:</span> <span class="hljs-string">"https://api.ipgeolocation.io/ipgeo?apiKey=<span class="hljs-template-variable">{{ ipgeolocation_api_key }}</span>&amp;ip=<span class="hljs-template-variable">{{ external_ip }}</span>"</span>
        <span class="hljs-attr">method:</span> <span class="hljs-string">GET</span>
        <span class="hljs-attr">return_content:</span> <span class="hljs-literal">yes</span>
      <span class="hljs-attr">register:</span> <span class="hljs-string">location_details</span>

    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Print</span> <span class="hljs-string">location</span> <span class="hljs-string">details</span>
      <span class="hljs-attr">debug:</span>
        <span class="hljs-attr">msg:</span> <span class="hljs-string">"<span class="hljs-template-variable">{{ location_details.content }}</span>"</span>
</code></pre>
<p>now create a new Ansible vault file called <strong>secrets.yml</strong> and add a variable in it like below</p>
<pre><code class="lang-bash">ansible-vault create secrets.yml
</code></pre>
<pre><code class="lang-yaml"><span class="hljs-attr">external_ip:</span> <span class="hljs-string">&lt;ip</span> <span class="hljs-string">address</span> <span class="hljs-string">to</span> <span class="hljs-string">get</span> <span class="hljs-string">data</span> <span class="hljs-string">about&gt;</span>
<span class="hljs-attr">ipgeolocation_api_key:</span> <span class="hljs-string">"&lt;your api key&gt;"</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697366729076/c7ac1261-1e40-43fd-8faa-3a968b65a430.png" alt class="image--center mx-auto" /></p>
<p>You can see that we are using both variables defined in secrets.yml in location.yml by using "{{ variable_name }}" notation. we have also defined variables using "vars_files".</p>
<p>Now Run our Playbook It using the below command</p>
<pre><code class="lang-bash">ansible-playbook location.yml --ask-vault-pass
</code></pre>
<p>You will be asked for a password and then you can see details about the output below</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697366814190/0ba4f927-9bc4-4be9-91c3-3c4e65ed997e.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697366834977/8a244ecf-d1f8-4cbc-bb96-bc023d43ef40.png" alt class="image--center mx-auto" /></p>
<p>In this way, you can use passwords from the vault inside playbooks.</p>
<h3 id="heading-providing-secrets-from-an-external-file">Providing Secrets from an external file</h3>
<p>If you don't want the password to be asked every time you run the playbook. you can provide a password using an external file.</p>
<p>create a file called password.txt and enter your password in it. like below</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697362737723/fa3d921e-ce35-4e81-9f9b-04c5590bf7b8.png" alt class="image--center mx-auto" /></p>
<p>Now Run Playbook using the below command</p>
<pre><code class="lang-bash">ansible-playbook --vault-password-file ./password.txt location.yml
</code></pre>
<p>You can see it worked and it didn't even ask for a password</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697367338833/0dbcbda3-8f90-47e0-aa8f-ae82cf7669a3.png" alt class="image--center mx-auto" /></p>
<p>You can even use a Python executable file to get the vault password like a below</p>
<pre><code class="lang-bash">ansible-playbook --vault-password-file ./password.py location.yml
</code></pre>
<h3 id="heading-using-vault-id-to-create-multiple-vaults">Using vault-id to Create multiple vaults</h3>
<p>Create Two Vaults one for IP address and one for API key. keep passwords for both vaults different.</p>
<p>Creating a File called ipaddress.yml</p>
<pre><code class="lang-bash">ansible-vault create ipaddress.yml --vault-id ip@prompt
</code></pre>
<pre><code class="lang-yaml"><span class="hljs-attr">external_ip:</span> <span class="hljs-number">15.207</span><span class="hljs-number">.85</span><span class="hljs-number">.110</span>
</code></pre>
<p>Create another File called apikey.yml</p>
<pre><code class="lang-bash">ansible-vault create apikey.yml --vault-id api@prompt
</code></pre>
<pre><code class="lang-yaml"><span class="hljs-attr">ipgeolocation_api_key:</span> <span class="hljs-string">"&lt;api key&gt;"</span>
</code></pre>
<p>Now let's edit out the location.yml playbook like below. we are just updating "vars_files" field.</p>
<pre><code class="lang-yaml"><span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Get</span> <span class="hljs-string">IP</span> <span class="hljs-string">Location</span> <span class="hljs-string">Details</span>
  <span class="hljs-attr">hosts:</span> <span class="hljs-string">localhost</span>
  <span class="hljs-attr">connection:</span> <span class="hljs-string">local</span>
  <span class="hljs-attr">gather_facts:</span> <span class="hljs-literal">no</span>
  <span class="hljs-attr">vars_files:</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">ipaddress.yml</span>
      <span class="hljs-bullet">-</span> <span class="hljs-string">apikey.yml</span>
  <span class="hljs-attr">tasks:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Install</span> <span class="hljs-string">Requests</span> <span class="hljs-string">Library</span>
      <span class="hljs-attr">pip:</span>
        <span class="hljs-attr">name:</span> <span class="hljs-string">requests</span>
        <span class="hljs-attr">state:</span> <span class="hljs-string">present</span>

    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Get</span> <span class="hljs-string">IP</span> <span class="hljs-string">location</span> <span class="hljs-string">details</span>
      <span class="hljs-attr">uri:</span>
        <span class="hljs-attr">url:</span> <span class="hljs-string">"https://api.ipgeolocation.io/ipgeo?apiKey=<span class="hljs-template-variable">{{ ipgeolocation_api_key }}</span>&amp;ip=<span class="hljs-template-variable">{{ external_ip }}</span>"</span>
        <span class="hljs-attr">method:</span> <span class="hljs-string">GET</span>
        <span class="hljs-attr">return_content:</span> <span class="hljs-literal">yes</span>
      <span class="hljs-attr">register:</span> <span class="hljs-string">location_details</span>

    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Print</span> <span class="hljs-string">location</span> <span class="hljs-string">details</span>
      <span class="hljs-attr">debug:</span>
        <span class="hljs-attr">msg:</span> <span class="hljs-string">"<span class="hljs-template-variable">{{ location_details.content }}</span>"</span>
</code></pre>
<p>Now For running playbook location.yml, it needs variable values from both files. As both files have different passwords we need to provide two passwords. we can do this using a command like below.</p>
<pre><code class="lang-yaml"><span class="hljs-string">ansible-playbook</span> <span class="hljs-string">location.yml</span> <span class="hljs-string">--vault-id</span> <span class="hljs-string">ip@prompt</span> <span class="hljs-string">--vault-id</span> <span class="hljs-string">api@prompt</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697370492036/27438778-29b5-4e86-be34-421281f979bf.png" alt class="image--center mx-auto" /></p>
<p>You can see that the above Playbook was successful. and it prompted for two passwords.</p>
<p>if you pass only one password it will fail like below</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1697370582620/732e02a7-9b99-4e04-8c25-56e8a60e924f.png" alt class="image--center mx-auto" /></p>
<hr />
<p>In this way by using Ansible Vault, you can securely manage sensitive information, Like database usernames and passwords, API keys and configuration files.</p>
]]></content:encoded></item><item><title><![CDATA[Configuring Ansible For AWS Management]]></title><description><![CDATA[Amazon Web Services (AWS) offers a scalable environment for deploying applications, but as the infrastructure grows, so does the complexity of managing it. Organizations need an easy way to manage this infrastructure. they are using different tools t...]]></description><link>https://anujdube.com/configuring-ansible-for-aws-management</link><guid isPermaLink="true">https://anujdube.com/configuring-ansible-for-aws-management</guid><category><![CDATA[AWS]]></category><category><![CDATA[Devops]]></category><category><![CDATA[ansible]]></category><category><![CDATA[automation]]></category><category><![CDATA[AWS automation]]></category><dc:creator><![CDATA[Anuj Dube]]></dc:creator><pubDate>Sun, 08 Oct 2023 13:18:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1696770763846/e7da66a8-3921-4cb3-8dd1-42e7aa0667ad.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Amazon Web Services (AWS) offers a scalable environment for deploying applications, but as the infrastructure grows, so does the complexity of managing it. Organizations need an easy way to manage this infrastructure. they are using different tools to keep the infrastructure as code. Ansible is such an open-source tool. it can help you to create and manage your infrastructure in different cloud environments.</p>
<p>In this article, we will look into how to create and manage AWS ec2 instances using Ansible.</p>
<hr />
<h2 id="heading-creating-ansible-control-node">Creating Ansible Control Node</h2>
<h3 id="heading-step-1-create-an-ubuntu-ec2-instance-on-aws">Step 1: Create an Ubuntu EC2 Instance on AWS</h3>
<p>After the Creation of the instance SSH into it. we will be using this as a control node to create and manage other AWS resources</p>
<h3 id="heading-step-2-install-ansible">Step 2: Install Ansible</h3>
<p>Update Repository and Upgrade Packages</p>
<pre><code class="lang-bash">sudo apt update
sudo apt upgrade
</code></pre>
<p>Sometimes You will be asked to restart</p>
<pre><code class="lang-bash">sudo reboot
</code></pre>
<p>Install Ansible</p>
<pre><code class="lang-bash">sudo pip install ansible
</code></pre>
<h3 id="heading-step-3-install-amazonaws-ansible-collection">Step 3: Install amazon.aws Ansible Collection</h3>
<p>Install amazon.aws ansible collection</p>
<pre><code class="lang-bash">ansible-galaxy collection install amazon.aws
</code></pre>
<p>amazon.aws Ansible Collection needs boto3 and botocore packages to connect to AWS for creating and managing infrastructure</p>
<p>First Install PIP</p>
<pre><code class="lang-bash">sudo apt install python3-pip
</code></pre>
<p>Install boto3 and botocore packages</p>
<pre><code class="lang-bash">pip install boto3 botocore
</code></pre>
<h3 id="heading-step-4-install-and-configure-aws-cli">Step 4: Install and Configure AWS CLI</h3>
<pre><code class="lang-bash">sudo apt install awscli
</code></pre>
<p>Configure AWS credentials using the AWS CLI</p>
<pre><code class="lang-bash">aws configure
</code></pre>
<p>You will be prompted to enter some details below</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696764712986/fc5a6390-2090-4120-99b7-1f7937ff17f7.png" alt class="image--center mx-auto" /></p>
<p>To Get These Details First go to AWS.</p>
<p>On the Right side, Click on your Profile. In Drop Down Menu You will see an option called "security credentials". Click On it</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696764894472/12f80996-b91c-4275-b31a-fa9692765fbd.png" alt class="image--center mx-auto" /></p>
<p>On this page if you move down You will see an option called "Access Keys".</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696765106386/6e5a4416-7c50-448c-94cf-9db6dd2783da.png" alt class="image--center mx-auto" /></p>
<p>Click on it and select first option "Command Line Interface"</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696765155260/a9e08823-4f49-467a-aaea-047d25f4009b.png" alt class="image--center mx-auto" /></p>
<p>Then Just Click next and create your access key.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696765235778/63958e6c-f4da-4bd2-914b-c4bbcfd78813.png" alt class="image--center mx-auto" /></p>
<p>Now You have "Access Key ID" and "Secret Access Key".</p>
<p>Please do not use keys from images They will not work I will be deleting this user and all his keys😉</p>
<p>To Get the Default Region name click on Drop Down on the left side of the profile. I have taken the region Mumbai so the name will be ap-south-1</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696765744852/b7ac7299-a6e4-4fc5-a13b-e9ff3ecb4698.png" alt class="image--center mx-auto" /></p>
<p>After Entering all the details, We will check if we can connect to AWS or not</p>
<p>Run Below Command It will show information about your EC2 instances</p>
<p>if the below command fails then you must have made some mistake while entering configuration information please try again</p>
<pre><code class="lang-bash">aws ec2 describe-instances
</code></pre>
<p>Now Our Control Node is ready</p>
<h2 id="heading-creating-and-managing-ec2-instances">Creating and Managing EC2 Instances</h2>
<h3 id="heading-example-1-create-a-single-ubuntu-ec2-instance-with-a-public-ip-address">Example 1: Create a Single Ubuntu EC2 Instance with a Public IP Address</h3>
<p>For This, we are going to use the module "ec2_instance"</p>
<p>Create a YAML File called create_ec2.yml</p>
<pre><code class="lang-yaml"><span class="hljs-meta">---</span>
<span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Create</span> <span class="hljs-string">Single</span> <span class="hljs-string">Ubuntu</span> <span class="hljs-string">EC2</span> <span class="hljs-string">Instance</span>
  <span class="hljs-attr">hosts:</span> <span class="hljs-string">localhost</span>
  <span class="hljs-attr">connection:</span> <span class="hljs-string">local</span>
  <span class="hljs-attr">gather_facts:</span> <span class="hljs-literal">no</span>
  <span class="hljs-attr">tasks:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Create</span> <span class="hljs-string">Ubuntu</span> <span class="hljs-string">EC2</span> <span class="hljs-string">instace</span> <span class="hljs-string">with</span> <span class="hljs-string">public</span> <span class="hljs-string">ip</span>
      <span class="hljs-attr">amazon.aws.ec2_instance:</span>
        <span class="hljs-attr">name:</span> <span class="hljs-string">"Created Using Ansible"</span>
        <span class="hljs-attr">key_name:</span> <span class="hljs-string">"newUbuntu"</span>
        <span class="hljs-attr">vpc_subnet_id:</span> <span class="hljs-string">subnet-0bd155c67558454b1</span>
        <span class="hljs-attr">instance_type:</span> <span class="hljs-string">t2.micro</span>
        <span class="hljs-attr">security_group:</span> <span class="hljs-string">sg-076a5ea097f046d8e</span>
        <span class="hljs-attr">network:</span>
          <span class="hljs-attr">assign_public_ip:</span> <span class="hljs-literal">true</span>
        <span class="hljs-attr">image_id:</span> <span class="hljs-string">ami-0f5ee92e2d63afc18</span>
        <span class="hljs-attr">tags:</span>
          <span class="hljs-attr">Environment:</span> <span class="hljs-string">Testing</span>
      <span class="hljs-attr">register:</span> <span class="hljs-string">ec2_node_info</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Display</span> <span class="hljs-string">information</span>
      <span class="hljs-attr">debug:</span>
        <span class="hljs-attr">msg:</span> <span class="hljs-string">"<span class="hljs-template-variable">{{ec2_node_info}}</span>"</span>
</code></pre>
<p>"key_name": SSH Key you will be using to login into the created server, You can use the same key that we are using to log into the control node</p>
<p>You Can use the Same details as we are using in the control node</p>
<p>Image_Id: In Details Tab</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696767771383/0f7d7ab8-3442-4523-8c2e-bc6f73e325ca.png" alt class="image--center mx-auto" /></p>
<p>to create another type of instance you can go to "AMI catalog" and you can get image_id from there.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696768226505/80826478-19e2-44b8-8f32-61ab7cc1b917.png" alt class="image--center mx-auto" /></p>
<p>vpc_subnet_id: In Networking Tab</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696767889194/fe51361c-8949-4309-99c2-993a6ff4438c.png" alt class="image--center mx-auto" /></p>
<p>security_group: In the Security tab</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696767990066/5fc3fcd8-5a7b-494a-a75b-2fc4e06cab60.png" alt class="image--center mx-auto" /></p>
<p>instance_type: In Details Tab</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696768514824/b82dae23-280f-453b-80b9-3e082a634fa2.png" alt class="image--center mx-auto" /></p>
<p>To Get other instance types go to the "Instance Types" tab</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696768458620/09947019-7273-4c8d-ae28-41186085f1d4.png" alt class="image--center mx-auto" /></p>
<p>To Run the playbook use the below command</p>
<pre><code class="lang-yaml"><span class="hljs-string">ansible-playbook</span> <span class="hljs-string">create_ec2.yml</span>
</code></pre>
<p>we are running it in localhost those options are mentioned in yml. so you can ignore warnings.</p>
<p>You will see output like the below as we are printing created instance details</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696768954570/8912b1c5-cc1a-4bff-9753-0d379372f648.png" alt class="image--center mx-auto" /></p>
<p>Now Go To AWS EC2 Console You will see a new instance with the name "Created Using Ansible" will be created.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696769033521/6b104b9b-d9eb-4e77-b9ee-848d78b46b28.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-example-2-get-a-list-of-all-running-instances">Example 2: Get a List of all running Instances</h3>
<p>For This, We are going to "ec2_instance_info"</p>
<p>Create a YAML File called get_all_ec2.yml</p>
<pre><code class="lang-yaml"><span class="hljs-meta">---</span>
<span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Get</span> <span class="hljs-string">All</span> <span class="hljs-string">Running</span> <span class="hljs-string">EC2</span> <span class="hljs-string">instances</span>
  <span class="hljs-attr">hosts:</span> <span class="hljs-string">localhost</span>
  <span class="hljs-attr">connection:</span> <span class="hljs-string">local</span>
  <span class="hljs-attr">gather_facts:</span> <span class="hljs-literal">no</span>
  <span class="hljs-attr">tasks:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Gather</span> <span class="hljs-string">information</span> <span class="hljs-string">about</span> <span class="hljs-string">instances</span> <span class="hljs-string">in</span> <span class="hljs-string">states</span> <span class="hljs-string">"running"</span>
      <span class="hljs-attr">amazon.aws.ec2_instance_info:</span>
        <span class="hljs-attr">filters:</span>
          <span class="hljs-attr">instance-state-name:</span> <span class="hljs-string">"running"</span>
      <span class="hljs-attr">register:</span> <span class="hljs-string">ec2_node_info</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Get</span> <span class="hljs-string">Running</span> <span class="hljs-string">Instances</span> <span class="hljs-string">Count</span>
      <span class="hljs-attr">debug:</span>
        <span class="hljs-attr">msg:</span> <span class="hljs-string">"Total running instances: <span class="hljs-template-variable">{{ ec2_node_info.instances | length }}</span>"</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Display</span> <span class="hljs-string">information</span>
      <span class="hljs-attr">debug:</span>
        <span class="hljs-attr">msg:</span> <span class="hljs-string">"<span class="hljs-template-variable">{{ec2_node_info}}</span>"</span>
</code></pre>
<p>Run Using Command</p>
<pre><code class="lang-yaml"><span class="hljs-string">ansible-playbook</span> <span class="hljs-string">get_all_ec2.yml</span>
</code></pre>
<p>You will see output like below giving all running ec2 instances details</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696769346426/f634fd45-ce24-48c7-b654-304bdc83a052.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-example-3-terminate-every-instance-from-the-current-aws-region">Example 3: Terminate Every Instance From the Current AWS Region</h3>
<p>This will terminate the control node also.</p>
<p>Create a File called terminate_all_ec2.yml</p>
<pre><code class="lang-yaml"><span class="hljs-meta">---</span>
<span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Terminate</span> <span class="hljs-string">Every</span> <span class="hljs-string">Instance</span> <span class="hljs-string">in</span> <span class="hljs-string">Current</span> <span class="hljs-string">AWS</span> <span class="hljs-string">Region</span>
  <span class="hljs-attr">hosts:</span> <span class="hljs-string">localhost</span>
  <span class="hljs-attr">connection:</span> <span class="hljs-string">local</span>
  <span class="hljs-attr">gather_facts:</span> <span class="hljs-literal">no</span>
  <span class="hljs-attr">tasks:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Terminate</span> <span class="hljs-string">every</span> <span class="hljs-string">running</span> <span class="hljs-string">instance</span> <span class="hljs-string">in</span> <span class="hljs-string">a</span> <span class="hljs-string">region.</span> <span class="hljs-string">Use</span> <span class="hljs-string">with</span> <span class="hljs-string">EXTREME</span> <span class="hljs-string">caution.</span>
      <span class="hljs-attr">amazon.aws.ec2_instance:</span>
        <span class="hljs-attr">state:</span> <span class="hljs-string">absent</span>
        <span class="hljs-attr">filters:</span>
          <span class="hljs-attr">instance-state-name:</span> <span class="hljs-string">running</span>
</code></pre>
<p>Now Run this using below command</p>
<pre><code class="lang-yaml"><span class="hljs-string">ansible-playbook</span> <span class="hljs-string">terminate_all_ec2.yml</span>
</code></pre>
<p>You will see That Your Control node is also terminated so you might be disconnected</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696769770374/cb002bbe-239f-4a75-b374-fe3a900a54fc.png" alt class="image--center mx-auto" /></p>
<hr />
<p>You can Manage and control lots of other AWS Resources like S3, VPC, Lambda, RDS etc. using Ansible.</p>
<p>You can learn more about that using the below link</p>
<p><a target="_blank" href="https://docs.ansible.com/ansible/latest/collections/amazon/aws/index.html">AWS Ansible Documentation</a></p>
<p>Happy automating! 🤖</p>
]]></content:encoded></item><item><title><![CDATA[Setting Up a Practical Ansible Lab on AWS: A Step-by-Step Guide]]></title><description><![CDATA[Ansible is a powerful, easy-to-use and easy-to-learn configuration management tool. If you are trying to learn Ansible then the first hurdle for you will be setting up a lab environment to practice Ansible.
In this article, we are going to create a l...]]></description><link>https://anujdube.com/setting-up-a-practical-ansible-lab-on-aws-a-step-by-step-guide</link><guid isPermaLink="true">https://anujdube.com/setting-up-a-practical-ansible-lab-on-aws-a-step-by-step-guide</guid><category><![CDATA[ansible]]></category><category><![CDATA[AWS]]></category><category><![CDATA[ec2]]></category><category><![CDATA[ansible-setup]]></category><dc:creator><![CDATA[Anuj Dube]]></dc:creator><pubDate>Sun, 01 Oct 2023 14:58:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1696171190164/fa4e6de2-b0e8-4772-9fec-e1c6dc9e04cf.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Ansible is a powerful, easy-to-use and easy-to-learn configuration management tool. If you are trying to learn Ansible then the first hurdle for you will be setting up a lab environment to practice Ansible.</p>
<p>In this article, we are going to create a lab environment on AWS. You can use any other cloud platform like Azure, or Google Cloud or you can create vm on Virtual Box. I would suggest using AWS or Azure (here we will use AWS) as they offer 12 months of free trial you can play with lots of different OSs also. not suggesting Google Cloud as they don't offer a Windows server on a free trial.</p>
<hr />
<p>Now Let's get started, We are going to create 3 servers. All of them will be Ubuntu servers. We are going to use one server as the control node and the remaining two as target nodes.</p>
<p>we can use Windows servers as the target node but not as the control node. here for setting up the lab, we are going to use Ubuntu servers only, as using a Windows server as a target has some extra steps. you can learn how to set up a Windows server for Ansible management <a target="_blank" href="https://anujdube.com/setting-up-a-windows-server-for-ansible-management">here</a>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696161048416/dcae42f5-1ca2-461a-a97e-efff942bead5.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-1-get-an-aws-free-tier-account">1. Get an AWS Free Tier Account</h2>
<p>To get this account you might need to provide them with a credit/debit card. No need to worry they will not charge but remember to put a billing alert and close all resources after using them so you don't get any charges.</p>
<h2 id="heading-2-create-ec2-instances">2. Create EC2 Instances</h2>
<p>Search EC2 on the Search Bar and click on that</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696161821700/03da2a22-e4f1-4bd3-8a0c-10d006589023.png" alt class="image--center mx-auto" /></p>
<p>you will see windows like the above. Click on Instances(running)</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696161909893/467c3764-f5ee-416b-9fa7-f857764c4e88.png" alt class="image--center mx-auto" /></p>
<p>now click on the Launch Instances Button at the right-top corner. and enter details below</p>
<p><strong>Name and tags:</strong> Server1</p>
<p><strong>Application and OS Images:</strong> Select Ubuntu do not change anything</p>
<p><strong>Instance type:</strong> Keep Default Free Tier instance type</p>
<p><strong>Key pair:</strong> Click on "Create new key pair" and create a new key it will be downloaded automatically after creation keep it safe</p>
<p><strong>Network settings:</strong> allows SSH, HTTP, HTTPS</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696162757381/4d181c11-9fe4-405a-857f-525342864c40.png" alt class="image--center mx-auto" /></p>
<p>Keep Every other thing Default.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696163080022/1110c16d-4ede-4654-a020-52a306132b92.png" alt class="image--center mx-auto" /></p>
<p>on the right-hand side, you will see the summary. In "Number of instances" enter 3. then click on "Launch instance".</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696163219947/78228416-3349-4e8f-8571-0e0a446c5da5.png" alt class="image--center mx-auto" /></p>
<p>Now change their names as above</p>
<h2 id="heading-3-setting-up-ec2-instances">3. Setting Up EC2 Instances</h2>
<p>I am using Windows So I will be using MobaXtrem as an SSH Client. If you are on Mac or Linux you don't need to install anything SSH Client is pre-installed on those OS.</p>
<p>I have Stored My Key Pair named "newUbuntu.pem" which was generated while creating instances on location "C:\temp\aws".</p>
<p>First, we will go through the steps for Mac/Linux users and then for Windows.</p>
<h3 id="heading-steps-for-maclinux-users">Steps For Mac/Linux Users</h3>
<p>Go to the location where you have stored your key pair and open the terminal there</p>
<p>Now On the AWS console, Select "Client" Server and Click on the Connect button at the top. then Go to SSH Client and copy the example SSH command</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696164123614/ae662d32-d2de-4361-99c8-2ffe7a4b1d3e.png" alt class="image--center mx-auto" /></p>
<p>Paste That command in the terminal and press enter. it will ask for yes/no enter yes.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696164761874/56902403-889f-41e4-a5d0-eb1e0f2b084f.png" alt class="image--center mx-auto" /></p>
<p>Now you are logged in to the control node. Now logout enter "exit"</p>
<p>We are going to copy our private SSH Key into the control node. for that use the below command. do not forget to update the command with your values</p>
<pre><code class="lang-bash"><span class="hljs-comment"># scp -i path/to/your/private/key.pem path/to/your/local/file user@public-dns-name:/path/to/destination/directory</span>
scp -i newUbuntu.pem newUbuntu.pem ubuntu@ec2-3-110-197-196.ap-south-1.compute.amazonaws.com:~/
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696170480911/66612e9a-5af8-436e-9621-62eaea767fd7.png" alt class="image--center mx-auto" /></p>
<p>now again log into the server and you can see your private key is copied like below</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696169948814/2864ac44-8a32-4b9d-89ec-a929b5f4091c.png" alt class="image--center mx-auto" /></p>
<p>Now Type the below command to ensure your key is not publicly viewable</p>
<pre><code class="lang-bash">chmod 400 newUbuntu.pem
</code></pre>
<p>now we will try to see if our control node can SSH into server1 and server2 or not.</p>
<p>Go to AWS Console select server1, click on the connect button, and copy the ssh command like below.</p>
<pre><code class="lang-bash">ssh -i <span class="hljs-string">"newUbuntu.pem"</span> ubuntu@ec2-3-110-197-196.ap-south-1.compute.amazonaws.com
</code></pre>
<p>now paste the command into the terminal of the control node and press enter</p>
<p>it might ask for yes/no. press yes. now you are in server1.</p>
<p>now type "exit" to exit from server1 to the control node.</p>
<p>Copy the SSH command for server2 also and try SSH into it.</p>
<p>You will be able to SSH into server2 also.</p>
<p>now you can directly go to the "4. Installing Ansible" step.</p>
<h3 id="heading-steps-for-windows-users">Steps For Windows Users</h3>
<p>Download MobaXterm From <a target="_blank" href="https://mobaxterm.mobatek.net/download.html">here</a> and Install it.</p>
<p>When MobaXterm is first started click on Settings -&gt; Configuration</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696164368994/1857f1a3-50fb-48cd-9691-10215e1891d3.png" alt class="image--center mx-auto" /></p>
<p>Change Home and Root Directory to the location where the key is stored. in my case it is C:\temp\aws. Click on OK. It will ask for a restart Click on Yes. MobaXStream will restart.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696164480475/73984c7f-9a26-454c-8302-72440c66c34a.png" alt class="image--center mx-auto" /></p>
<p>Now Click On Start Local Terminal</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696164632761/355d0a3b-aa5c-442e-ac89-2c72091f144c.png" alt class="image--center mx-auto" /></p>
<p>When we run "ls" it should show your key in the current directory</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696164679407/8ef31c9a-b63d-45b3-b53d-94d59b2266a0.png" alt class="image--center mx-auto" /></p>
<p>Now On the AWS console, Select "Client" Server and Click on the Connect button at the top. then Go to SSH Client and copy the example SSH command</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696164123614/ae662d32-d2de-4361-99c8-2ffe7a4b1d3e.png" alt class="image--center mx-auto" /></p>
<p>Paste That command in the terminal and press enter. it will ask for yes/no enter yes.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696164761874/56902403-889f-41e4-a5d0-eb1e0f2b084f.png" alt class="image--center mx-auto" /></p>
<p>Now you are logged in to the control node. On the left-hand side, you will see SSH Browser.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696170665032/1bf4b751-f393-4a7c-a2a1-09085fb5605a.png" alt class="image--center mx-auto" /></p>
<p>Upload your private key</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696170715287/3341916d-eb9f-47a1-8eb8-6aa9e080c1fb.png" alt class="image--center mx-auto" /></p>
<p>Now Type the below command to ensure your key is not publicly viewable</p>
<pre><code class="lang-bash">chmod 400 newUbuntu.pem
</code></pre>
<p>now we will try to see if our control node can SSH into server1 and server2 or not.</p>
<p>Go to AWS Console select server1, click on the connect button, and copy the ssh command like below.</p>
<pre><code class="lang-bash">ssh -i <span class="hljs-string">"newUbuntu.pem"</span> ubuntu@ec2-3-110-197-196.ap-south-1.compute.amazonaws.com
</code></pre>
<p>now paste the command into the terminal of the control node and press enter</p>
<p>it might ask for yes/no. press yes. now you are in server1.</p>
<p>now type "exit" to exit from server1 to the control node.</p>
<p>Copy the SSH command for server2 also and try SSH into it.</p>
<p>You will be able to SSH into server2 also.</p>
<p>Windows Users can also use SCP to copy private SSH key to control the server. But Using MobaXterm is much easier.</p>
<p>As Learning Experience you can try SCP also.</p>
<h2 id="heading-4-installing-ansible">4. Installing Ansible</h2>
<p>Update Package list and upgrade Packages</p>
<pre><code class="lang-bash">sudo apt update
sudo apt upgrade
</code></pre>
<p>Sometimes you may be asked to reboot then you can reboot using the below command.</p>
<pre><code class="lang-bash">sudo reboot
</code></pre>
<p>Install Ansible</p>
<pre><code class="lang-bash">sudo apt install ansible
</code></pre>
<p>Now Let's Create a Folder Called "ansiblePractice" and go into that folder</p>
<pre><code class="lang-bash">mkdir ansiblePractice
<span class="hljs-built_in">cd</span> ansiblePractice
</code></pre>
<p>Create a File called "inventory" and enter the public IP address of server1 and server2 in there like below</p>
<pre><code class="lang-bash">nano inventory
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696166874073/adad6db7-cdc8-43b4-a090-6423db29bda8.png" alt class="image--center mx-auto" /></p>
<p>Ctrl + O to Save -&gt; Press Enter -&gt; Ctrl + X to exit.</p>
<p>Now we will execute our first ansible ad-hoc command. Sometimes it can ask for yes/no. press yes.</p>
<pre><code class="lang-bash">ansible all --key-file newUbuntu.pem -i inventory -m ping
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1696167180456/059166db-8761-435a-a342-607ab3fa7aa9.png" alt class="image--center mx-auto" /></p>
<hr />
<p>Now Your Lab Environment Is Ready You can start learning Ansible.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/anujsdtw/status/1702900896705970451">https://twitter.com/anujsdtw/status/1702900896705970451</a></div>
<p> </p>
<p>Happy automating! 🤖</p>
]]></content:encoded></item><item><title><![CDATA[Setting up a Windows Server for Ansible Management]]></title><description><![CDATA[Ansible, a widely used configuration management tool, is not just for Unix-like systems. With the right setup, it can also be used to manage Windows servers. This article will guide you through the process of setting up a Windows server to be control...]]></description><link>https://anujdube.com/setting-up-a-windows-server-for-ansible-management</link><guid isPermaLink="true">https://anujdube.com/setting-up-a-windows-server-for-ansible-management</guid><category><![CDATA[ansible]]></category><category><![CDATA[ansible windows]]></category><category><![CDATA[Devops]]></category><category><![CDATA[automation]]></category><category><![CDATA[ansible-playbook]]></category><dc:creator><![CDATA[Anuj Dube]]></dc:creator><pubDate>Sun, 24 Sep 2023 10:31:53 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1695551333164/3dbef4db-d921-4f6c-a379-121d22b9ac9a.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Ansible, a widely used configuration management tool, is not just for Unix-like systems. With the right setup, it can also be used to manage Windows servers. This article will guide you through the process of setting up a Windows server to be controlled using Ansible.</p>
<p>For this demonstration, we'll be setting up two instances of "Microsoft Windows Server 2022 Base" as child nodes. Additionally, we'll create an Ubuntu instance to serve as our control node.</p>
<p>Ansible Uses SSH for connecting to Linux systems, And for Windows systems it uses Winrm.</p>
<h2 id="heading-steps-to-configure-a-windows-server"><strong>Steps to Configure a Windows Server</strong></h2>
<p>Open Powershell in Administrator mode and run the below command. it will run a script that will do all the necessary configurations. yes, that's it on the Window side.</p>
<pre><code class="lang-powershell"><span class="hljs-built_in">Invoke-WebRequest</span> <span class="hljs-literal">-Uri</span> https://raw.githubusercontent.com/rallabandisrinivas/winrm_ansible/main/README.md <span class="hljs-literal">-UseBasicParsing</span> | <span class="hljs-built_in">Select-Object</span> <span class="hljs-literal">-ExpandProperty</span> Content | <span class="hljs-built_in">Invoke-Expression</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695548596995/d2d5bf96-e994-4ecd-ba74-9f0cd0fa5afc.png" alt class="image--center mx-auto" /></p>
<p>You can refer to the official documentation below if you face any issues</p>
<p><a target="_blank" href="https://docs.ansible.com/ansible/latest/os_guide/windows_setup.html">Ansible Windows Setup Link</a></p>
<h2 id="heading-steps-to-configure-a-ubuntu-server"><strong>Steps to Configure a Ubuntu Server</strong></h2>
<ol>
<li><p>Update Package list and upgrade Packages</p>
<pre><code class="lang-bash"> sudo apt update
 sudo apt upgrade
</code></pre>
<p> Sometimes you may be asked to reboot then you can reboot using the below command.</p>
<pre><code class="lang-bash"> sudo reboot
</code></pre>
</li>
<li><p>Install python3-pip and then install pywinrm package.</p>
<pre><code class="lang-bash"> sudo apt install python3-pip
 pip install pywinrm
</code></pre>
</li>
<li><p>Let's install ansible</p>
<pre><code class="lang-bash"> sudo apt install ansible
</code></pre>
</li>
<li><p>Now create an inventory file and add IP and authentication info about Windows servers in it.</p>
<p> <strong>inventory</strong></p>
<pre><code class="lang-yaml"> [<span class="hljs-string">windows</span>]
 <span class="hljs-string">server1</span> <span class="hljs-string">ansible_host=65.2.122.214</span> <span class="hljs-string">ansible_user=Administrator</span> <span class="hljs-string">ansible_password=3zA)--5TI$4pFng6*=qnAVLudgYtTqRP</span>
 <span class="hljs-string">server2</span> <span class="hljs-string">ansible_host=15.206.194.23</span> <span class="hljs-string">ansible_user=Administrator</span> <span class="hljs-string">ansible_password=3zA)--5TI$4pFng6*=qnAVLudgYtTqRP</span>

 [<span class="hljs-string">windows:vars</span>]
 <span class="hljs-string">ansible_connection=winrm</span>
 <span class="hljs-string">ansible_winrm_server_cert_validation=ignore</span>
</code></pre>
<p> Yes, Storing Passwords in plain text is a security risk we can use ansible-vault. But for the sake of the demo, we are storing it in plain text.</p>
<p> In Production environments, We can Ansible Vault to securely store and use passwords.</p>
<p> To learn more about Ansible Vault you can refer below article</p>
<p> <a target="_blank" href="https://anujdube.com/secrets-management-with-ansible-vault-a-comprehensive-guide-with-examples">Secrets Management with Ansible Vault: A Comprehensive Guide with Examples</a></p>
</li>
<li><p>Now We will be running the below Adhoc command to test the connectivity</p>
<pre><code class="lang-bash"> ansible windows -m win_ping -i inventory
</code></pre>
<p> if you have created instances on the cloud and have not opened Winrm ports you might get the below error.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695547185222/f3b37944-f565-4bdf-bf85-64473ad786d8.png" alt class="image--center mx-auto" /></p>
<p> Open those ports and run the command again</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695547246780/56c0be98-57b0-4fa4-93ff-373eaae3fc36.png" alt class="image--center mx-auto" /></p>
<p> Successful execution will look like the below</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695549971121/1acd5798-6ae6-4252-a8a7-a15d34b744bb.png" alt class="image--center mx-auto" /></p>
</li>
</ol>
<p>Now, with all the Configurations in place, you can fully automate a myriad of tasks on your Windows servers.</p>
<p>Happy automating! 🤖</p>
]]></content:encoded></item><item><title><![CDATA[Ansible Conditionals]]></title><description><![CDATA[In Ansible, conditionals offer control in playbooks, allowing tasks, plays, or even entire roles to be executed or skipped based on certain conditions. Here's an overview of the most used conditionals and their uses:
1. when

The most commonly used c...]]></description><link>https://anujdube.com/ansible-conditionals</link><guid isPermaLink="true">https://anujdube.com/ansible-conditionals</guid><category><![CDATA[ansible]]></category><category><![CDATA[ansible-playbook]]></category><dc:creator><![CDATA[Anuj Dube]]></dc:creator><pubDate>Sun, 17 Sep 2023 04:36:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1696082085436/6b2517c0-3158-4613-be01-0fbac6f32dab.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In Ansible, conditionals offer control in playbooks, allowing tasks, plays, or even entire roles to be executed or skipped based on certain conditions. Here's an overview of the most used conditionals and their uses:</p>
<h2 id="heading-1-when">1. when</h2>
<ul>
<li><p>The most commonly used conditional. It determines if a task or play should be executed.</p>
</li>
<li><p>You have to write an expression that evaluates to a boolean (true/false).</p>
</li>
</ul>
<p>Example:</p>
<p>You want some tasks to be executed only on some specific servers.</p>
<pre><code class="lang-yaml"><span class="hljs-meta">---</span>

<span class="hljs-bullet">-</span> <span class="hljs-attr">hosts:</span> <span class="hljs-string">all</span>
  <span class="hljs-attr">become:</span> <span class="hljs-literal">true</span>
  <span class="hljs-attr">tasks:</span>
  <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">update</span> <span class="hljs-string">repository</span> <span class="hljs-string">index</span> <span class="hljs-string">Ubuntu</span>
    <span class="hljs-attr">apt:</span>
      <span class="hljs-attr">update_cache:</span> <span class="hljs-literal">yes</span>
    <span class="hljs-attr">when:</span> <span class="hljs-string">ansible_distribution</span> <span class="hljs-string">==</span> <span class="hljs-string">"Ubuntu"</span>

  <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">update</span> <span class="hljs-string">repository</span> <span class="hljs-string">index</span> <span class="hljs-string">Centos</span>
    <span class="hljs-attr">yum:</span>
      <span class="hljs-attr">update_cache:</span> <span class="hljs-literal">yes</span>
    <span class="hljs-attr">when:</span> <span class="hljs-string">ansible_distribution</span> <span class="hljs-string">==</span> <span class="hljs-string">"CentOS"</span>
</code></pre>
<p>Here while executing the task. Ansible will first check the when condition. If it's true only then it will execute the main task.</p>
<p>You can see it's skipping if the condition is not true.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694444459657/caa1634a-ef45-486d-aff5-d796877bc97d.png" alt class="image--center mx-auto" /></p>
<p><strong>From where we are getting this "ansible_os_family" variable?</strong></p>
<p>while running every Ansible playbook. By default, Ansible runs the gather_facts task. that task gathers all information about servers. which gives us access to these variables.</p>
<h2 id="heading-2-changedwhen">2. changed_when</h2>
<ul>
<li><p>Modifies the behavior of a task to report a "changed" status.</p>
</li>
<li><p>You have to write an expression that evaluates to a boolean (true/false).</p>
</li>
</ul>
<p>Example:</p>
<p>Updating the repository is a basic task Suppose you don't want to consider that as a change then you can write it like below</p>
<pre><code class="lang-yaml"><span class="hljs-meta">---</span>

<span class="hljs-bullet">-</span> <span class="hljs-attr">hosts:</span> <span class="hljs-string">all</span>
  <span class="hljs-attr">become:</span> <span class="hljs-literal">true</span>
  <span class="hljs-attr">tasks:</span>

  <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">update</span> <span class="hljs-string">repository</span> <span class="hljs-string">index</span>
    <span class="hljs-attr">apt:</span>
      <span class="hljs-attr">update_cache:</span> <span class="hljs-literal">yes</span>
    <span class="hljs-attr">when:</span> <span class="hljs-string">ansible_distribution</span> <span class="hljs-string">==</span> <span class="hljs-string">"Ubuntu"</span>
    <span class="hljs-attr">changed_when:</span> <span class="hljs-literal">false</span>

  <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">update</span> <span class="hljs-string">repository</span> <span class="hljs-string">index</span>
    <span class="hljs-attr">yum:</span>
      <span class="hljs-attr">update_cache:</span> <span class="hljs-literal">yes</span>
    <span class="hljs-attr">when:</span> <span class="hljs-string">ansible_distribution</span> <span class="hljs-string">==</span> <span class="hljs-string">"CentOS"</span>
    <span class="hljs-attr">changed_when:</span> <span class="hljs-literal">false</span>
</code></pre>
<p>It will give you a changed=0</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694442429192/2a25385a-c982-48fb-8a88-870a71cb7836.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-3-failedwhen">3. failed_when</h2>
<ul>
<li>Modifies the behavior of a task to report a "failed" status based on custom conditions.</li>
</ul>
<p>Example: You want to check disk usage and want to mark it as a failure if usage is more than 90%.</p>
<pre><code class="lang-yaml"><span class="hljs-meta">---</span>

<span class="hljs-bullet">-</span> <span class="hljs-attr">hosts:</span> <span class="hljs-string">all</span>
  <span class="hljs-attr">vars:</span>
    <span class="hljs-attr">disk_usage_threshold:</span> <span class="hljs-number">90</span>
  <span class="hljs-attr">tasks:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Check</span> <span class="hljs-string">root</span> <span class="hljs-string">filesystem</span> <span class="hljs-string">disk</span> <span class="hljs-string">usage</span>
      <span class="hljs-attr">command:</span> <span class="hljs-string">df</span> <span class="hljs-string">-h</span> <span class="hljs-string">/</span>
      <span class="hljs-attr">register:</span> <span class="hljs-string">df_output</span>
      <span class="hljs-attr">changed_when:</span> <span class="hljs-literal">false</span>
      <span class="hljs-attr">failed_when:</span> <span class="hljs-string">&gt;
        (ansible_distribution == "CentOS" and (df_output.stdout_lines[-1].split()[4]|replace('%',''))|int &gt; disk_usage_threshold) or
        (ansible_distribution == "Ubuntu" and (df_output.stdout_lines[1].split()[4]|replace('%',''))|int &gt; disk_usage_threshold)</span>
</code></pre>
<p>The output will be like the below</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694443349704/f920d39d-5dbc-40ea-b284-720e9bddc15b.png" alt class="image--center mx-auto" /></p>
<p>as my disks are not filled let me fill the disk of one server.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694444270759/7abfac68-bdc4-493a-a7c5-faba2af99896.png" alt class="image--center mx-auto" /></p>
<p>Now you can see that for one server script has failed showing disk is filled 94%.</p>
<h2 id="heading-4-until">4. until</h2>
<ul>
<li>Used for retrying a task until a certain condition is met or a certain number of retries is reached.</li>
</ul>
<p>Example: Retry a task until a file exists.</p>
<pre><code class="lang-yaml"><span class="hljs-meta">---</span>
<span class="hljs-bullet">-</span> <span class="hljs-attr">hosts:</span> <span class="hljs-string">all</span>
  <span class="hljs-attr">tasks:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Check</span> <span class="hljs-string">if</span> <span class="hljs-string">file</span> <span class="hljs-string">exists</span>
      <span class="hljs-attr">stat:</span>
        <span class="hljs-attr">path:</span> <span class="hljs-string">"/tmp/file.txt"</span>
      <span class="hljs-attr">register:</span> <span class="hljs-string">file_status</span>
      <span class="hljs-attr">until:</span> <span class="hljs-string">file_status.stat.exists</span>
      <span class="hljs-attr">retries:</span> <span class="hljs-number">5</span>
      <span class="hljs-attr">delay:</span> <span class="hljs-number">3</span>
</code></pre>
<p>You can see playbook is trying to check if file exist at that location or not. while it's running i logged into one server and created file. you can see it's showing file found for one server. it kept trying for another server.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694445715462/1c190158-2d07-445d-917d-522d767ed820.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-5-assert">5. assert</h2>
<ul>
<li>Used for failing a play if certain conditions are not met.</li>
</ul>
<p>Example: Fail if the free memory is less than 10 GB.</p>
<pre><code class="lang-yaml"><span class="hljs-meta">---</span>
<span class="hljs-bullet">-</span> <span class="hljs-attr">hosts:</span> <span class="hljs-string">all</span>
  <span class="hljs-attr">tasks:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Get</span> <span class="hljs-string">filesystem</span> <span class="hljs-string">details</span> <span class="hljs-string">for</span> <span class="hljs-string">/</span>
      <span class="hljs-attr">ansible.builtin.setup:</span>
        <span class="hljs-attr">filter:</span> <span class="hljs-string">ansible_mounts</span>

    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Assert</span> <span class="hljs-string">minimum</span> <span class="hljs-string">disk</span> <span class="hljs-string">space</span> <span class="hljs-string">requirements</span>
      <span class="hljs-attr">assert:</span>
        <span class="hljs-attr">that:</span>
          <span class="hljs-bullet">-</span> <span class="hljs-string">item.size_available</span> <span class="hljs-string">&gt;=</span> <span class="hljs-number">10000000000</span>  <span class="hljs-comment"># 10 GB in bytes</span>
        <span class="hljs-attr">fail_msg:</span> <span class="hljs-string">"Not enough disk space on <span class="hljs-template-variable">{{ item.mount }}</span>. At least 10GB required."</span>
        <span class="hljs-attr">success_msg:</span> <span class="hljs-string">"<span class="hljs-template-variable">{{ item.mount }}</span> has sufficient space."</span>
      <span class="hljs-attr">with_items:</span> <span class="hljs-string">"<span class="hljs-template-variable">{{ ansible_mounts }}</span>"</span>
      <span class="hljs-attr">when:</span> <span class="hljs-string">item.mount</span> <span class="hljs-string">==</span> <span class="hljs-string">"/"</span>
</code></pre>
<p>Output</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694532686908/a8a0f46c-373b-4852-8935-7bb419760066.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694532708709/164f9239-d904-41fd-8155-8e0850ad7571.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694532732436/7dc06c1f-82e8-411e-80e3-0229e3535abf.png" alt class="image--center mx-auto" /></p>
<p>You can see in the above image it failed for one server having insufficient space and was successful for another.</p>
<h2 id="heading-6-block-and-rescue">6. block and rescue</h2>
<ul>
<li><p><code>block</code> groups tasks together.</p>
</li>
<li><p><code>rescue</code> defines tasks to be executed if any task in the <code>block</code> fails.</p>
</li>
<li><p>It's like try and catch in javascript, java etc.</p>
</li>
</ul>
<p>Example: Attempt to install a package and handle failures.</p>
<pre><code class="lang-yaml"><span class="hljs-meta">---</span>
<span class="hljs-bullet">-</span> <span class="hljs-attr">hosts:</span> <span class="hljs-string">all</span>
  <span class="hljs-attr">become:</span> <span class="hljs-literal">yes</span>
  <span class="hljs-attr">vars:</span>
    <span class="hljs-attr">package_name:</span> <span class="hljs-string">example_package</span>
  <span class="hljs-attr">tasks:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Attempt</span> <span class="hljs-string">to</span> <span class="hljs-string">install</span> <span class="hljs-string">a</span> <span class="hljs-string">package</span>
      <span class="hljs-attr">block:</span>
        <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Install</span> <span class="hljs-string">the</span> <span class="hljs-string">"<span class="hljs-template-variable">{{ package_name }}</span>"</span>
          <span class="hljs-attr">package:</span>
            <span class="hljs-attr">name:</span> <span class="hljs-string">"<span class="hljs-template-variable">{{ package_name }}</span>"</span>
            <span class="hljs-attr">state:</span> <span class="hljs-string">present</span>
      <span class="hljs-attr">rescue:</span>
        <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Handle</span> <span class="hljs-string">the</span> <span class="hljs-string">failure</span>
          <span class="hljs-attr">debug:</span>
            <span class="hljs-attr">msg:</span> <span class="hljs-string">"Failed to install <span class="hljs-template-variable">{{ package_name }}</span> . Check if the package name is correct or if there's a repo issue."</span>
      <span class="hljs-attr">always:</span>
        <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">This</span> <span class="hljs-string">always</span> <span class="hljs-string">gets</span> <span class="hljs-string">executed</span>
          <span class="hljs-attr">debug:</span>
            <span class="hljs-attr">msg:</span> <span class="hljs-string">"This message will always be displayed, regardless of success or failure in the block above."</span>
</code></pre>
<p>As you can see above script will fail to install a package called example_package as no such package exists. still, we are not shown any failure(failed=0). You can see the task in rescue is executed correctly.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694453046234/303d6d79-2231-4b2b-b378-c301aae705b8.png" alt class="image--center mx-auto" /></p>
<p>if we put package_name=wget. which is actually a real package name. task will succeed. It will look like below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694453165789/1666e167-667d-42a8-b016-71f7de3f5aeb.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-7-conditional-imports-and-includes">7. Conditional imports and includes</h2>
<ul>
<li>Conditionally import playbooks or include tasks/roles based on certain conditions.</li>
</ul>
<p>Example: install web server depending on user input</p>
<p><strong>web_setup.yml</strong></p>
<pre><code class="lang-yaml"><span class="hljs-meta">---</span>
<span class="hljs-bullet">-</span> <span class="hljs-attr">hosts:</span> <span class="hljs-string">all</span>
  <span class="hljs-attr">become:</span> <span class="hljs-literal">true</span>
  <span class="hljs-attr">vars_prompt:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">webserver_type</span>
      <span class="hljs-attr">prompt:</span> <span class="hljs-string">"Which web server do you want to install? (apache/nginx)"</span>
      <span class="hljs-attr">private:</span> <span class="hljs-literal">no</span>

  <span class="hljs-attr">tasks:</span>
    <span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Include</span> <span class="hljs-string">tasks</span> <span class="hljs-string">based</span> <span class="hljs-string">on</span> <span class="hljs-string">web</span> <span class="hljs-string">server</span> <span class="hljs-string">choice</span>
      <span class="hljs-attr">include_tasks:</span> <span class="hljs-string">"install_<span class="hljs-template-variable">{{ webserver_type }}</span>.yml"</span>
      <span class="hljs-attr">when:</span> <span class="hljs-string">webserver_type</span> <span class="hljs-string">in</span> [<span class="hljs-string">'apache'</span>, <span class="hljs-string">'nginx'</span>]
</code></pre>
<p><strong>install_apache.yml</strong></p>
<pre><code class="lang-yaml"><span class="hljs-meta">---</span>
<span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Install</span> <span class="hljs-string">Apache</span>
  <span class="hljs-attr">package:</span>
    <span class="hljs-attr">name:</span> <span class="hljs-string">apache2</span>
    <span class="hljs-attr">state:</span> <span class="hljs-string">present</span>
  <span class="hljs-attr">when:</span> <span class="hljs-string">ansible_distribution</span> <span class="hljs-string">==</span> <span class="hljs-string">"Ubuntu"</span>

<span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Install</span> <span class="hljs-string">httpd</span>
  <span class="hljs-attr">package:</span>
    <span class="hljs-attr">name:</span> <span class="hljs-string">httpd</span> 
    <span class="hljs-attr">state:</span> <span class="hljs-string">present</span>
  <span class="hljs-attr">when:</span> <span class="hljs-string">ansible_distribution</span> <span class="hljs-string">==</span> <span class="hljs-string">"CentOS"</span>
</code></pre>
<p><strong>install_nginx.yml</strong></p>
<pre><code class="lang-yaml"><span class="hljs-meta">---</span>
<span class="hljs-bullet">-</span> <span class="hljs-attr">name:</span> <span class="hljs-string">Install</span> <span class="hljs-string">Nginx</span>
  <span class="hljs-attr">ansible.builtin.package:</span>
    <span class="hljs-attr">name:</span> <span class="hljs-string">nginx</span>
    <span class="hljs-attr">state:</span> <span class="hljs-string">present</span>
</code></pre>
<p>so depending on user input it will select playbook and run it.</p>
<p>for apache as input you can see it ran install_apache.yml</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694532223061/bfb14e81-ff58-4660-a8b8-74dc3666ceaa.png" alt class="image--center mx-auto" /></p>
<p>For nginx as input, you can see it ran install_nginx.yml</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1694532299980/a6b8fd40-464a-419d-90c7-5e850d01f60a.png" alt class="image--center mx-auto" /></p>
<hr />
<p>In conclusion, Ansible's conditionals provide a powerful way to bring logic and decision-making into playbooks, ensuring that infrastructure automation is both flexible and precise. Like any tool, the key is understanding the available options and applying them judiciously.</p>
<p>Happy automating! 🤖</p>
]]></content:encoded></item><item><title><![CDATA[Copying Files From Local To Remote Using PowerShell]]></title><description><![CDATA[Let's say you want to copy files/folders from a local device to one or more remote Windows servers. We have lots of ways to do this but in this article, we will be looking into how to do that using PowerShell. In your local and remote at both places,...]]></description><link>https://anujdube.com/copying-files-from-local-to-remote-using-powershell</link><guid isPermaLink="true">https://anujdube.com/copying-files-from-local-to-remote-using-powershell</guid><category><![CDATA[Powershell]]></category><category><![CDATA[robocopy]]></category><dc:creator><![CDATA[Anuj Dube]]></dc:creator><pubDate>Wed, 16 Aug 2023 14:31:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1692196706990/5c682b58-fa35-4651-9083-1eda0d67e709.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Let's say you want to copy files/folders from a local device to one or more remote Windows servers. We have lots of ways to do this but in this article, we will be looking into how to do that using PowerShell. In your local and remote at both places, you need to enable PowerShell remoting.</p>
<p><strong>Step 1: Check and set the execution policy</strong></p>
<pre><code class="lang-powershell"><span class="hljs-built_in">Get-ExecutionPolicy</span>
</code></pre>
<p>if the exception policy is not <strong>RemoteSigned</strong> set it to RemoteSigned.</p>
<pre><code class="lang-powershell"><span class="hljs-built_in">Set-ExecutionPolicy</span> RemoteSigned
</code></pre>
<p><strong>Step 2: Enable PowerShell remoting</strong></p>
<p>Please keep in mind, When the <strong>SkipNetworkProfileCheck</strong> parameter is specified, it bypasses the check for network profiles during the configuration process. This allows PowerShell remoting to be enabled even if the network profile is not classified as private or domain.</p>
<pre><code class="lang-powershell"><span class="hljs-built_in">Enable-PSremoting</span> <span class="hljs-literal">-SkipNetworkProfileCheck</span>
</code></pre>
<p>Now to the main part</p>
<h2 id="heading-method-1-using-copy-itemhttpslearnmicrosoftcomen-uspowershellmodulemicrosoftpowershellmanagementcopy-itemviewpowershell-73-with-session">Method 1: Using <a target="_blank" href="https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/copy-item?view=powershell-7.3">Copy-Item</a> with session</h2>
<p>The most simple and best way. just use the <strong>ToSession</strong> parameter provided within copy-item.</p>
<pre><code class="lang-powershell"><span class="hljs-variable">$sourcePath</span> = <span class="hljs-string">"C:\temp\files"</span>
<span class="hljs-variable">$destinationPath</span> = <span class="hljs-string">"C:\temp\files"</span>
<span class="hljs-variable">$serverName</span> = <span class="hljs-string">"&lt;server name&gt;"</span>
<span class="hljs-variable">$username</span> = <span class="hljs-string">"&lt;username&gt;"</span>

<span class="hljs-variable">$credentail</span> = <span class="hljs-built_in">Get-Credential</span> <span class="hljs-literal">-Message</span> <span class="hljs-string">"Enter Credentials"</span> <span class="hljs-literal">-UserName</span> <span class="hljs-variable">$username</span>
<span class="hljs-variable">$session</span> = <span class="hljs-built_in">New-PSSession</span> <span class="hljs-literal">-ComputerName</span> <span class="hljs-variable">$serverName</span> <span class="hljs-literal">-Credential</span> <span class="hljs-variable">$credentail</span>

<span class="hljs-built_in">Copy-Item</span> <span class="hljs-literal">-Path</span> <span class="hljs-variable">$sourcePath</span> <span class="hljs-literal">-Destination</span> <span class="hljs-variable">$destinationPath</span> <span class="hljs-literal">-Recurse</span> <span class="hljs-literal">-ToSession</span> <span class="hljs-variable">$session</span>
</code></pre>
<p>in the above script, we created a PowerShell session to that remote Windows server and then we are copying the whole folder from source to destination.</p>
<h2 id="heading-method-2-using-copy-item-with-ps-drive">Method 2: Using Copy-Item with PS Drive</h2>
<p>Here we are creating a ps-drive and then doing the copying part. this method helps to interact with the remote location in a way that resembles working with a local drive.</p>
<pre><code class="lang-powershell"><span class="hljs-variable">$sourcePath</span> = <span class="hljs-string">"C:\temp\files"</span>
<span class="hljs-variable">$destinationPath</span> = <span class="hljs-string">"C:\temp\files"</span>
<span class="hljs-variable">$serverName</span> = <span class="hljs-string">"&lt;server name&gt;"</span>
<span class="hljs-variable">$username</span> = <span class="hljs-string">"&lt;username&gt;"</span>
<span class="hljs-variable">$driveName</span> = <span class="hljs-string">"R"</span>

<span class="hljs-variable">$credentail</span> = <span class="hljs-built_in">Get-Credential</span> <span class="hljs-literal">-Message</span> <span class="hljs-string">"Enter Credentials"</span> <span class="hljs-literal">-UserName</span> <span class="hljs-variable">$username</span>

<span class="hljs-built_in">New-PSDrive</span> <span class="hljs-literal">-Name</span> <span class="hljs-variable">$driveName</span> <span class="hljs-literal">-PSProvider</span> FileSystem <span class="hljs-literal">-Root</span> <span class="hljs-variable">$destinationPath</span> <span class="hljs-literal">-Credential</span> <span class="hljs-variable">$credentail</span>

<span class="hljs-built_in">Copy-Item</span> <span class="hljs-literal">-Path</span> <span class="hljs-variable">$sourcePath</span> <span class="hljs-literal">-Destination</span> <span class="hljs-variable">$driveName:</span>\ <span class="hljs-literal">-Recurse</span>

<span class="hljs-built_in">Remove-PSDrive</span> <span class="hljs-literal">-Name</span> <span class="hljs-variable">$driveName</span>
</code></pre>
<h2 id="heading-method-3-using-robocopyhttpslearnmicrosoftcomen-uswindows-serveradministrationwindows-commandsrobocopy">Method 3: Using <a target="_blank" href="https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/robocopy">Robocopy</a></h2>
<p><strong>Robocopy</strong> (Robust File Copy) is a command-line utility built into Windows that provides advanced options for copying files and directories.</p>
<p>While using robocopy easier way is to create a local drive and then use that for copying files.</p>
<p>keep in mind drive name should be a single character like A, R, X etc. Not names like "newDrive", "test" etc.</p>
<pre><code class="lang-powershell"><span class="hljs-variable">$sourcePath</span> = <span class="hljs-string">"C:\temp\files"</span>
<span class="hljs-variable">$destinationPath</span> = <span class="hljs-string">"C:\temp\files"</span>
<span class="hljs-variable">$serverName</span> = <span class="hljs-string">"&lt;server name&gt;"</span>
<span class="hljs-variable">$username</span> = <span class="hljs-string">"&lt;username&gt;"</span>
<span class="hljs-variable">$driveName</span> = <span class="hljs-string">"R"</span>

<span class="hljs-variable">$credentail</span> = <span class="hljs-built_in">Get-Credential</span> <span class="hljs-literal">-Message</span> <span class="hljs-string">"Enter Credentials"</span> <span class="hljs-literal">-UserName</span> <span class="hljs-variable">$username</span>

robocopy <span class="hljs-variable">$sourcePath</span> <span class="hljs-variable">$driveName:</span>\  /E /Z /COPYALL /<span class="hljs-built_in">R</span>:<span class="hljs-number">3</span> /W:<span class="hljs-number">1</span>

<span class="hljs-built_in">Remove-PSDrive</span> <span class="hljs-literal">-Name</span> <span class="hljs-variable">$driveName</span>
</code></pre>
<p>Meaning of copy options we have passed</p>
<p><strong>/E:</strong> copies subdirectories, including empty ones.</p>
<p><strong>/Z:</strong> enables restartable mode.</p>
<p><strong>/COPYALL:</strong> copies all file information.</p>
<p><strong>/R:3:</strong> specifies 3 retries on failed copies.</p>
<p><strong>/W:1:</strong> sets the wait time between retries to 1 second.</p>
<hr />
]]></content:encoded></item></channel></rss>