How Do You Write a Terraform Module in AWS?

Problem scenario
You want to write a Terraform module in AWS. What do you do?

Solution
You will use the keyword "module" in a .tf file, and you will use either "terraform init" or "terraform get" to install the module. The directions below were adapted from https://www.howtoforge.com/how-to-create-a-terraform-module/.

Prerequisite
You need to have Terraform installed; if you need assistance, see this posting.

Procedures

  1. On the Linux server with Terraform, go to a directory where you can place some .tf files. The user's home directory may be acceptable.
  2. Create a file called main.tf with this as the content:
provider "aws" {
region = var.region
access_key = var.access_key
secret_key = var.secret_key
}
module "contint_s3_bucket" {
source = "./submod"
bucket_name = var.bucket_name
tags = {
Terraform = "true"
Environment = "dev"
}
}
  1. Create a file called variables.tf with this as the content:
variable "access_key" {
description = "Insert an access key here"
}
variable "secret_key" {
description = "Put the secret access key that corresponds to the Access Key above"
}
variable "region" {
description = "AWS has different regions, i.e., us-west-2, us-east-1. Insert one here"
}
variable "bucket_name" {
description = "This is a Required field. Enter a name that will be unique in S3"
type = string
default = "test-bucket-contint-delete"
}
  1. Create a file called terraform.tfvars with this as the content:
region = "us-west-1"
access_key = "123somestring"
secret_key = "ZYX987/variousletters"
  1. Create a directory for the modules called submod: mkdir submod
  2. Change directories to be in this new directory named submod.
  3. Create a file called main.tf with this as the content (this was taken from https://www.howtoforge.com/how-to-create-a-terraform-module/):
resource "aws_s3_bucket" "s3_bucket" {
bucket = var.bucket_name
acl = "public-read"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": "", "Action": [ "s3:GetObject" ], "Resource": [ "arn:aws:s3:::${var.bucket_name}/"
]
}
]
}
EOF
website {
index_document = "index.html"
error_document = "error.html"
}
tags = var.tags
}
  1. Create a file called variables.tf with this as the content:
variable "bucket_name" {
description = "Each s3 bucket must have a unique name (among every bucket regardless of what region it is in)."
type = string
}
variable "tags" {
description = "A bucket can have tags; that is what this variable does."
type = map(string)
default = {}
}

How Do You Troubleshoot the yum Repository “Errors during downloading metadata for repository”?

Problem scenario
You try to use a yum command on RHEL 8.2. But you get this error:

Docker Repository 0.0 B/s | 0 B 00:00 Errors during downloading metadata for repository 'foobar': - Curl error (6): Couldn't resolve host name for https://yum.dockerproject.org/repo/main/centos/7/repodata/repomd.xml [Could not resolve host: yum.dockerproject.org] Error: Failed to download metadata for repo 'foobar': Cannot download repomd.xml: Cannot download repodata/repomd.xml: All mirrors were tried

What should you do?

Solution
Run this command but replace "foobar": sudo yum-config-manager --disable foobar

How Do You Troubleshoot the InsufficientFreeAddressSpaceInVpc Error?

Problem scenario
You run an AWS CLI command. But you get this message:

An error occurred (InsufficientFreeAddressSpaceInVpc) when calling the CreateDefaultSubnet operation: The VPC 'vpc-123abcd' does not have enough free address space to allocate an additional /20 subnet.

How do you troubleshoot this AWS CLI error?

Solution
Go to the VPC section of AWS. Find the VPC in the error and click on it. Go to "Edit CIDRs" and add a CIDR to allocate more IP addresses.

How Do You Troubleshoot the kubectl ‘version “extensions/v1beta1″‘ Error Message?

Problem scenario
You run a kubectl command, but you get this problem: 'error: unable to recognize "foobar.yaml": no matches for kind "Deployment" in version "extensions/v1beta1"'

What should you do?

Solution
Change your yaml file so the apiVersion setting/value works. To learn more about the acceptable values, see this posting.

How Do You Replace a Pattern with a String in Bash?

Problem scenario
You have a .txt file. You know Linux can support substitutions of strings with some type of expression. You want to use Bash to replace every occurrence in the file with a string. What should you do?

Solution
Let's assume the file you have is called coolfile.txt. Run these two commands to replace "foo" with "bar" every time "foo" is found in the file named coolfile.txt:

oldfile=$(cat coolfile.txt)
echo "${oldfile//'foo'/bar}" > newfile.txt
# The resulting file newfile.txt will have "bar" instead of "foo"

How Do You Escape or Break from a Method in Python?

Problem scenario
You want to quit a function, or return out of it, when a certain condition is met. How do you do this?

Solution
This program illustrates how it is done. You will want to run the program twice, once by leaving the "5" as it is, and a second time by changing the "5" to "6".

def cool(x):
  if x == 5:
    return "There was equivalence"
  else:
    y = x
  print("This statement is printing as an illustration")
  return "The comparison was NOT equivalent"

var1 = cool(5)
print(var1)

How Do You Troubleshoot a C Program That Prints a Warning Message like “expects argument of type ‘int’, but argument 2 has type ‘char *’ [-Wformat=]”?

Problem scenario
You compile a C program (with gcc foobar.cc) but you get an error message like this:

basicprog.c:5:13: warning: format '%d' expects argument of type 'int', but argument 2 has type 'char *' [-Wformat=]
printf ("y is a %d\n",y);

What do you do to not get this error?

Solution
While the code compiles, the executable may not run.  A compilation error can be benign.  For this case, string characters need a special syntax to be printed out.  

Here is a line that will produce this error (with a variable named "y"):

   printf ("y is a %d\n", y);

Here is a similar but corrected line that will be error free:

  printf ("y is a %s\n",y);

The "%d" is appropriate for printing integer variables.  For string variables, use "%s" syntax.


For learning about the C programming language, you may want to purchase a book below:

0131103628C Programming Language, 2nd Edition by Pearson
1718501048Effective C: An Introduction to Professional C Programming by No Starch Press
1789349915Learn C Programming: A beginner's guide to learning C programming the easy and disciplined way by Packt Publishing
1789343623Extreme C: Taking you to the limit in Concurrency, OOP, and the most advanced capabilities of C by Packt Publishing
0393979504C Programming: A Modern Approach, 2nd Edition by W. W. Norton & Compan

How Do You Use Terraform and Kubernetes in a Simple Way (as a Proof of Concept)?

Problem scenario
You want to use Terraform and Kubernetes (in EKS). How do you do this in a simple way to test it out?

Solution
Prerequisite

This assumes you have deployed EKS. If you need assistance, see this posting.
This assumes you have installed Terraform. If you need assistance, see this posting.

Procedures

  1. This first step is optional. Log into the AWS Management Console, and go here. Take a screenshot.
  2. Go to the back-end server with Terraform. Run these commands:
git clone https://github.com/hashicorp/learn-terraform-provision-eks-cluster
cd learn-terraform-provision-eks-cluster/
terraform init
terraform plan  # This command is optional
terraform apply

# It may take 20 minutes.  This step "module.eks.aws_eks_cluster.this[0]: Still creating... " may take 15 minutes by itself.  Be patient.
  1. This step is optional. Go back to the web UI and refresh the web page to view the new VPC changes.
  2. Go back to the command prompt and run this command to rollback the changes: terraform destroy

How Do You Fix the AWS CLI Error “Following required service principals [eks.amazonaws.com] were not found in the trust relationships”?

Problem scenario
You run an AWS CLI command, but you get this error:

An error occurred (InvalidParameterException) when calling the CreateNodegroup operation: Following required service principals [eks.amazonaws.com] were not found in the trust relationships of clusterRole arn:aws:iam::12345678910:role/foobar

How do you fix this?

Solution
Draft a command like this (but replace "12345677810:role/foobar" with the equivalent string in the error, and replace foobar.amazonaws.com with the service principal in the error):

aws iam list-roles --query 'Roles[?Arn==arn:aws:iam::12345678910:role/foobar]' | grep foobar.amazonaws.com

If the above command returns nothing, try the command again without the "| grep foobar.amazonaws.com". If your Role was configured correctly, you may need to open a ticket with AWS Support. If nothing is returned from the command above with the "grep", you need to modify the role. Go to the AWS Management Console, go to IAM -> Roles. Click on the role, go to "Trust Relationships" and "Edit Trust Relationship." Modify it like this:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "foo.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    },
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "bar.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}