Tuesday, November 10, 2020

EKS - Alpaca market data on Grafana and PostgreSQL

Following a number of experimentations with Prometheus and Grafana for the purposes of collecting and viewing logs off internal systems, I decided to put together a proof of concept for something more visually fun.

The objective is to subscribe to a market data feed and display historic prices in the form of a graph. Needed for this are:

1. Market data - Alpaca offers a free data API. This requires an active trading account but no cash deposit is necessary. The data is supplied by 3rd party vendors which would be a factor if we were building strategies, but for display purposes this would be perfectly sufficient

2. Visualization - the choices are numerous, from Python libraries like Matplotlib and Plotly to dashboards by Kibana, but the aim is to demonstrate the Grafana's ease of use

3. Data store - PostgreSQL is integrated into Grafana and would work as  sufficient data store

4. Host - using a Kubernetes cluster on Amazon Elastic Kubernetes Service (AWS EKS) would help decouple services into individual components as well as serve as effective hosting option

IMPLEMENTATION

Those in need of a refresh on the Kubernetes concepts, please see this article.

EKS CLUSTER

The prerequisites for this are: an account with AWS, AWS command line, kubectl and eksctl. A cluster can be initiated using the below yaml: eksctl create cluster -f cluster.yaml. 

Note that we are intentionally using a single node group on t2.medium EC2 instance. This is to save on hosting fees. We are not yet concerned with resilience as this is a demo exercise - thus only a single instance to host all services. The size is of concern as well - t2.medium offers greater number of private IPs than micro and nano as thus more suitable to host a multi-service cluster.

kind: ClusterConfig
 
metadata:
  name: marketeye-cluster
  region: us-east-2
 
nodeGroups:
  - name: ng-1
    instanceType: t2.medium
    desiredCapacity: 1

PosgreSQL NODE

We firstly create a postrges-conf.yaml with ConfigMap to expose the database credentials. These will become available as environment variables on other pods.

apiVersion: v1
kind: ConfigMap
metadata:
  name: postgres-config
  labels:
    app: postgres
data:
  POSTGRES_DB: postgresdb
  POSTGRES_USER: postgresadmin
  POSTGRES_PASSWORD: admin123

Define a volume in postrges-vol.yaml - persistent storage outside of the pod that helps preserve the data in case of the database pod loss. The two kinds below stand for: PersistentVolumeClaim – a dedicated resource that represents a request for storage of specific size (i.e. WHAT we want). PersistentVolume – represents the actual storage in the cluster (i.e. HOW we want it implemented); can specify path and size as well.

kind: PersistentVolume
apiVersion: v1
metadata:
  name: postgres-pv-volume
  labels:
    type: local
    app: postgres
spec:
  storageClassName: manual
  capacity:
    storage: 1G
  accessModes:
    - ReadWriteMany
  hostPath:
    path: "/mnt/data"
---
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: postgres-pv-claim
  labels:
    app: postgres
spec:
  storageClassName: manual
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 1G

Add a postrges-svc.yaml defining the Service - a networking abstract that exposes an application running on a pod. The type of ClusterIP indicates that the service is to be available to requests originating within the cluster only.

kind: Service
metadata:
  name: postgres
  labels:
    app: postgres
spec:
  type: ClusterIP
  ports:
   - port: 5432
     name: postgres-serv
  selector:
   app: postgres

Add a postrges-deployment.yaml defining a Deployment - the mechanism of deploying pods that provides auto scaling and resource availability. image below maps to the depo containing the latest PostgreSQL image. postgres-config maps to the config defined previously. Note the Service needed to be defined and applied prior to Deployment if these are loaded via distinct yaml files with a "kubectl apply -f" per each file.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: postgres
spec:
  selector:
    matchLabels:
      app: postgres
  replicas: 1
  template:
    metadata:
      labels:
        app: postgres
    spec:
      containers:
        - name: postgres
          image: postgres:latest
          imagePullPolicy: "IfNotPresent"
          ports:
            - containerPort: 5432
          envFrom:
            - configMapRef:
                name: postgres-config
          env:
            - name: POSTGRES_HOST
              value: postgres-service
            - name: POSTGRES_PORT
              value: "5432"
          volumeMounts:
            - mountPath: /var/lib/postgresql/data
              name: postgredb
      volumes:
        - name: postgredb
          persistentVolumeClaim:
            claimName: postgres-pv-claim

GRAFANA

Grafana source code is open for all to explore. The Docker-friendly installation instructions are available here. The below grafana.yaml was derived from this very worthy post. As with Postgres above, there is a Service for connectivity and a Deployment for pod management.

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: grafana
  name: grafana-deployment
  namespace: default
spec:
  replicas: 1
  selector:
    matchLabels:
      component: grafana
  template:
    metadata:
      labels:
        component: grafana
    spec:
      volumes:
      - name: grafana-claim
        persistentVolumeClaim:
          claimName: grafana-claim
      containers:
      - name: grafana
        image: grafana/grafana:5.0.0
        imagePullPolicy: IfNotPresent
        ports:
        - containerPort: 3000
        resources:
          limits:
            cpu: 500m
            memory: 2500Mi
          requests:
            cpu: 100m
            memory: 100Mi
        volumeMounts:
        - mountPath: /var/lib/grafana
          name: grafana-claim
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  creationTimestamp: null
  labels:
    component: grafana
  name: grafana-claim
  namespace: default
spec:
  accessModes:
  - ReadWriteOnce
  resources:
    requests:
      storage: 1Gi
---
apiVersion: v1
kind: Service
metadata:
  name: grafana-ip-service
  namespace: default
spec:
  type: LoadBalancer
  selector:
    component: grafana
  ports:
  - port: 3000
    targetPort: 3000

ALPACA API

Since we are deploying on Kubernetes, we need a custom container with the following:
- Code to interrogate the API and write data into the Postgres DB
- OS and all dependencies needed for the code to run
- Secret containing API credentials

Alpaca offer various technologies for API interaction: C#, Go, Javascript, Python. A number of Python examples are available AlpacaHQ Git repo. Streaming live price updates are available via Websockets as described here.

The below Dockerfile describes the container: 

FROM python:3.7.9
RUN apt-get update
COPY requirements.txt
RUN pip install -r /requirements.txt
 
RUN useradd --create-home alpaca
WORKDIR /home/alpaca
USER alpaca
 
COPY alpaca-bot.py .
COPY alpaca_db.py .
 
ENTRYPOINT [ "python3", "alpaca-bot.py" ]

alpaca-bot.py and alpaca_db.py are the code files residing in the local directory. requirements.txt contains references to the below libraries that need to be installed on the pod:

alpaca-trade-api
psycopg2-binary

A secrets.yaml with API credentials obtained from Alpaca needs to be applied before the container is deployed:

apiVersion: v1
kind: Secret
metadata:
  name: api-secret
data:
  api_key_id: <.....>
  api_secret_key: <.....>
  api_base_url: <.....>

Define the database class in alpaca_db.py:

import psycopg2
from psycopg2 import Error
 
class PostgresDB():
    def __init__(self, db, user, pwd, host, port):
        self.conn = psycopg2.connect(database=db, user=user, password=pwd, host=host, port=port)
        self.conn.autocommit = True
        self.cur = self.conn.cursor()
 
    def execute(self, statement):
        try:
            self.cur.execute(statement)
        except (Exception, Error) as error:
            print("Error while connecting to PostgreSQL:", error)
 
    def fetch(self, statement):
        try:
            self.cur.execute(statement)
            rows = self.cur.fetchall()
            for row in rows:
                print(row)
        except (Exception, Error) as error:
            print("Error while connecting to PostgreSQL:", error)
 
    def close(self):
        self.cur.close()
        self.conn.close()

Add the Alpaca stream subscription code in alpaca_bot.py - in part based on the post here. 

import alpaca_trade_api as tradeapi
import threading
from alpaca_trade_api import StreamConn
import datetime
import os
import asyncio
import alpaca_db
 
# Get environment variables
key_id = os.getenv('APCA_API_KEY_ID')
secret_key = os.environ.get('APCA_API_SECRET_KEY')
base_url =  os.environ.get('APCA_API_BASE_URL')
data_stream = 'alpacadatav1'
ws_url = 'wss://data.alpaca.markets'
 
database = os.environ['POSTGRES_DB']
dbUser = os.environ['POSTGRES_USER']
dbPwd = os.environ['POSTGRES_PASSWORD']
dbHost = os.environ['POSTGRES_SERVICE_HOST']
dbPort = os.environ['POSTGRES_SERVICE_PORT']
 
script_start = datetime.datetime.now()
symbol = ['MSFT']
 
# Initialise and connect to the database
dbInstance = alpaca_db.PostgresDB(database, dbUser, dbPwd, dbHost, dbPort)
 
# Connect to the Alpaca API
connApi = tradeapi.stream2.StreamConn(
    key_id, secret_key, base_url=base_url, data_url=ws_url, data_stream=data_stream
)
 
# Extend the connection interval as needed
async def handle_signal(channel, symbol, value):
    if (datetime.datetime.now() - script_start).seconds > 30:
        print('Closing connection for ' + str(symbol))
        await connApi.unsubscribe([r'^T.' + str(symbol), r'^AM.' + str(symbol)])
        dbInstance.close()
    else:
        print(str(channel) + '.' + str(symbol))
        print(str(value))
        print(' ')
 
# T stands for a trade event
@connApi.on(r'^T.*$', symbol)
async def on_trade(connApi, channel, trade):
    symbol = str(trade.symbol)
    price = float(trade.price)
    print('-- T Hit --')
    timeNow = datetime.datetime.now()
    command = "INSERT INTO TRADE_AUDIT(ID, SYMBOL, TRADE_PRICE) VALUES ('%s', '%s', %s);" % (timeNow, symbol, price)
    dbInstance.execute(command)
    await handle_signal(channel, symbol, price)
 
 
async def kickoff_trades():
    await connApi.subscribe("T.('%s')" % (symbol))
 
 
if __name__ == '__main__':
    dbInstance.execute('CREATE TABLE TRADE_AUDIT(\
            ID          TEXT  NOT NULL,\
            SYMBOL      TEXT  NOT NULL,\
            TRADE_PRICE FLOAT NOT NULL,\
            PRIMARY KEY( ID ));')
    loop = asyncio.new_event_loop()
    loop.create_task(kickoff_trades())
    loop.run()

The image containing all of the above can be build and pushed up to the custom Docker hub repo (<.....>) using the commands below:

sudo docker login --username=<.....> --password <.....>
sudo docker build -f Dockerfile -t alpaca-app:latest .
sudo docker tag <.build id produced in the step above.> <.....>/alpaca-app:latest
sudo docker push <.....>/alpaca-app

And, finally, the last piece to tie it all together - alpaca-app.yaml - the yaml to deploy the custom Alpaca app. This pulls in the application image from the custom Docker hub repo (fill in the name in place of <.....>). It also maps in the database config (configMapRef) and the Alpaca credentials (env).

apiVersion: apps/v1
kind: Deployment
metadata:
  name: alpaca
  labels:
    app: alpaca-app
spec:
  replicas: 1
  selector:
    matchLabels:
      app: alpaca-app
  template:
    metadata:
      labels:
        app: alpaca-app
    spec:
      containers:
      - name: alpaca-app
        image: <.....>/alpaca-app
        command: ["sleep", "123456"]
        envFrom:
          - configMapRef:
              name: postgres-config
        env:
        - name: APCA_API_KEY_ID
          valueFrom:
            secretKeyRef:
              name: api-secret
              key: api_key_id
        - name: APCA_API_SECRET_KEY
          valueFrom:
            secretKeyRef:
              name: api-secret
              key: api_secret_key
        - name: APCA_API_BASE_URL
          valueFrom:
            secretKeyRef:
              name: api-secret
              key: api_base_url
      nodeSelector:
        beta.kubernetes.io/os: linux


DEPLOY IT ALL !

kubectl apply -f secrets.yaml
kubectl apply -f postrges-conf.yaml
kubectl apply -f postrges-vol.yaml
kubectl apply -f postrges-svc.yaml
kubectl apply -f postrges-deployment.yaml
kubectl apply -f grafana.yaml
kubectl apply -f alpaca-app.yaml

Once applied, do kubectl get all to see all components deployed or kubectl get scv to only see the services. See EXTERNAL-IP and PORT(S) column values in the grafane-ip-service row below - that is the URL and the port of the load balancer service residing on top of Grafana. In addition, CLUSTER-IP value of postgres service is the internal in-cluster IP of the database insatnce.


Log into Grafana using the above URL and "admin/admin" credential. Make sure to change the admin password if needed. Define a Data Source using PostgresSQL as Type, the above service IP as Host and database login credentials as defined in postrges-conf.yaml.


Create a new Dashboard selecting the data source defined above and a simple SQL statement to pull data in. 


Wednesday, November 4, 2020

GCP to AWS - multi-provider file copy

 
I was recently asked to look into the effort involved in implementing an outbound file copy interface between an on-premise proprietary application and public cloud storage.
       A number of items needed clarification: nature of connectivity between the on-premise and the cloud, security and encryption requirements, expected frequency of transfers, the anticipated file size, etc. 
 
While the questions were pending, a quick POC was performed f
or illustrative purposes. Terraform was used to:
       -         deploy a RHEL compute instance on Google Private Cloud
        o   run latest OS updates
        o   obtain and install AWS Command Line binaries
        o   supply credentials needed to connect to a specific AWS account
        o   install pip, python 3.6 and boto3
-         deploy a python script to transfer files onto S3
-         create a new custom S3 bucket on AWS
-         run the script on the GCP instance to pick up contents of a file from /var/log and transfer in into the specified S3 bucket

providers.tf

provider "aws" {
  region = var.aws-region
  access_key = file("../Credentials/AWS/access_key.txt")
  secret_key = file("../Credentials/AWS/secret_key.txt")
}

provider "google" {
  credentials = file("../Credentials/GCP/redhat-295420-769720b20d99.json")
  project     = "redhat-295420"
  region      = var.gcp-region
}

gcpInstance.tf

# Terraform plugin for creating random ids
resource "random_id" "instance_id" {
 byte_length = 8
}

# A single Compute Engine instance
resource "google_compute_instance" "default" {
 name         = "rhel-vm-${random_id.instance_id.hex}"
 machine_type = "f1-micro"
 zone         = "us-west1-a"
 boot_disk {
    initialize_params {
      image = "rhel-7-v20201112"
    }
 }

# Make sure rhel is installed on all new instances for later steps
metadata_startup_script = "yum update"
 network_interface {
   network = "default"
   access_config {
     // Include this section to give the VM an external ip address
   }
 }

 # install prerequisites
 provisioner "file" {
   source      = "bootstrap.sh"
   destination = "/tmp/bootstrap.sh"
 }

 # copy over python script that performs S3 transfer
 provisioner "file" {
   source      = "upload_file.py"
   destination = "/tmp/upload_file.py"
 }

 # copy over the AWS credenials file
 provisioner "file" {
   source      = "credentials"
   destination = "/tmp/credentials"
 }

 # initiate the transfer script
 # remove exta characters that might have been added by Windows editor
 provisioner "remote-exec" {
   inline = [
     "chmod +x /tmp/upload_file.py",
     "tr -d '\r' < /tmp/bootstrap.sh > /tmp/scriptClean.sh",
     "chmod +x /tmp/scriptClean.sh",
     "sh /tmp/scriptClean.sh ${var.log_file_name} ${var.bucket_name}",
   ]
 }

 connection {
   type = "ssh"
   user = "${var.gcp_user_name}"
   private_key = file("../Credentials/GCP/legacy_key")
   host = google_compute_instance.default.network_interface.0.access_config.0.nat_ip
 }
}

# Create a public IP address for our google compute instance to utilize
resource "google_compute_address" "static" {
  name = "vm-public-address"
}

# A variable for extracting the external IP address of the instance
output "ip" {
 value = google_compute_instance.default.network_interface.0.access_config.0.nat_ip
}

awsS3.tf

resource "aws_s3_bucket" "import_file_store" {
  bucket = var.bucket_name
  acl    = "private"
  tags = {
    Name        = "Source"
    Environment = "GCP"
  }
}

upload_file.py

import logging
import boto3
import sys
from botocore.exceptions import ClientError

def upload_file(file_name, bucket, object_name=None):
    """Upload a file to an S3 bucket
    :param file_name: File to upload
    :param bucket: Bucket to upload to
    :param object_name: S3 object name. If not specified then file_name is used
    :return: True if file was uploaded, else False
    """
    # If S3 object_name was not specified, use file_name
    if object_name is None:
        object_name = file_name
    # Upload the file
    s3_client = boto3.client('s3')
    try:
        response = s3_client.upload_file(file_name, bucket, object_name)
    except ClientError as e:
        logging.error(e)
        return False
    return True

def main():

    file_path_name = sys.argv[1]
    bucket         = sys.argv[2]
    object_name    = file_path_name.split('/')[-1]

    if file_path_name != "" and bucket != "":
       upload_file(file_path_name, bucket, object_name)

main()

bootstrap.sh

#!/bin/bash
mkdir $HOME/.aws
mv /tmp/credentials $HOME/.aws/.
export PATH="$HOME/.local/bin:$PATH"
sudo yum -y install python3
curl -O "https://bootstrap.pypa.io/get-pip.py"
python3 get-pip.py --user
sudo yum -y install unzip
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
unzip awscliv2.zip
sudo ./aws/install
pip install boto3
sudo cat /var/log/$1>/tmp/$1
python3 /tmp/upload_file.py "/tmp/$1" "$2"


      The upload script was based on the AWS boto3 example: https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-uploading-files.html

A more comprehensive transfer example featuring multi-part upload, a callback routine and more is available here: https://docs.aws.amazon.com/code-samples/latest/catalog/code-catalog-python-example_code-s3.html

Tuesday, November 3, 2020

Terraform - AWS provisioning


KEY CONCEPTS:

-        Configuration management – install and manage software on existing servers: Ansible, Chef, Puppet

-        Infrastructure Orchestration – provision servers and other infrastructure components: Terraform, AWS CloudFormation


TERRAFORM

-        free, works w multiple platforms: https://www.terraform.io/docs/providers/index.html

-        single binary - https://www.terraform.io/downloads.html. On Windows – add path to the .exe to system PATH variable (Control Panel, etc.)

-        Terraform on AWS: https://registry.terraform.io/providers/hashicorp/aws/latest/docs

-     Example of an EC2 instance config: https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/instance

      To test this out, create a sample.tf as below:

# Configure the AWS Provider
provider "aws" {
  region  = "us-east-1"
  access_key = "my-access-key "
  secret_key = "my-secret-key "
}
resource "aws_instance" “my_awesome_ec2” {
  ami           = "ami-096fda3c22c1c990a"
  instance_type = "t2.micro"
}

-        “provider” defines what API you are running against

-        “resource” is specific to a provider

-        “terraform init” downloads the necessary plugins for the given provider

-        To run, execute the following on the same folder as the above .tf:

terraform init
terraform plan
terraform apply
OR
terraform apply -auto-approve

-        NOTE: if numerous resources are being created and there is a cap on API calls, can use “terraform plan -refresh=false” to limit an API refresh call on every single resource when changing only a subset OR “terraform plan -refresh=false -target=<resource_name>” to change a specific resource only

-        To clean up and remove all created resources run “terraform destroy”

       To remove a specific resource:

-        terraform destroy -target aws_instance.my_awesome_ec2

-        OR comment out a specific resource that is no longer needed and re-run “terraform plan” / “apply”


Format / validate

-        https://www.terraform.io/docs/commands/fmt.html

-        Run “terraform fmt” to format the .tf file removing extra indentation, etc.

-        Run “terraform validate” to check if confoguration supplied in the file is valid


State file

-        Terraform saves it’s “current view” of the deployed infrastructure in terraform.tfstate

-        Uses this file to diff against updates in the user’s .tf

-        If changes are made to the infra manually – terraform will pick up and highlight the differences

-        .tf = desired state of infra, terraform.tfstate = current stare of infra

-        Run “terraform refresh” to reconcile and update the state file

-        “terraform show” provides a more user-friendly read of the state file

-        NOTE: only items explicitly defined in .tf (desired state) get flagged as outstanding if manually changed in the background (ex: manually switch a Sec Group on EC2 w/out siting it in .tf)


Plugin version

-        There is a terraform plugin running on the infra provider side for the client tor interact with

-        It is possible to specify a version of the plugin desired; can specify a range >=, etc.

-        By default, the latest version is used if none is specified

-        Can work with 3rd party infra providers – requires download of a 3rd party plugin (wget <source>)

provider "aws" {
  region  = "us-east-1"
  access_key = "my-access-key "
  secret_key = "my-secret-key "
  version      = “2.7”
}


Attribute reference and output values

-        https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/eip

-        Can expose attributes of a newly created resource

o   print on-screen for reference after “terraform apply”

o   use those as input for resources created subsequently

-        Output values are visible in “  "outputs": {},” section in the state file

output "instance_ip_addr" {
  value = aws_instance.server.private_ip
}

 

Association of an ID with an instance or a network interface

-        https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/eip_association

resource "aws_eip_association" "eip_assoc" {
  instance_id   = aws_instance.web.id
  allocation_id = aws_eip.example.id
}


Variables

-        https://www.terraform.io/docs/configuration/variables.html

variable "instancetype" {
  default = "t2.micro"
}
 
resource "aws_instance" "example" {
  instance_type = var.instancetype
}

-        Can specify a variable value on command line at launch:

o   terraform plan -var="instancetype=t2.small"

-        if no default is set (i.e. variable "image_id" {}), terraform will prompt for value at launch

-        BEST PRACTICE

o   define variables and default values in variables.tf

o   move out variable name/value pairs and default overrides into terraform.tfvars

§  instancetype="t2.large"

o   can optionally save variables into a custom-ly name file

§  terraform plan -var-file="custom.tfvars"

-        Can specify a variable value on command line at launch:

variable "instancetype" {
  type = "string"
}


-        Can store variables as lists 

variable "instancetype" {
  type = "list"
  default = ["m5.large", “m5.xlarge”, “t2.medium”]
}


Count

-        Speed up creation of multiple resource by using list of variables and count

-        Can apply conditional expressions: “condition ? true : false”


variable "elb_names" {
  type = list
  default = ["dev-loadbalancer", "stage-loadbalanacer","prod-loadbalancer"]
}
 
resource "aws_iam_user" "lb" {
  name = var.elb_names[count.index]
  count = 3
  path = "/system/"
}
 
variable "istest" {}
 
resource "aws_instance" "prod" {
   ami = "ami-082b5a644766e0e6f"
   instance_type = "t2.large"
   count = var.istest == false ? 1 : 0
}


Functions

-        https://www.terraform.io/docs/configuration/functions.html

-        A finite list of built-in functions is available – as documented above

-        Can run “terraform console” to test out function code


Data sources

-        https://www.terraform.io/docs/configuration/data-sources.html

-        Can filter and extract data from the provider and use in configuration:


data "aws_ami" "app_ami" {
  most_recent = true
  owners = ["amazon"]
 
  filter {
    name   = "name"
    values = ["amzn2-ami-hvm*"]
  }
}
 
resource "aws_instance" "instance-1" {
    ami = data.aws_ami.app_ami.id
   instance_type = "t2.micro"
}


Debugging

-        https://www.terraform.io/docs/internals/debugging.html

-         Set environment variable TF_LOG to any value to enable detailed logging

- Set to TRACE (most verbose), DEBUG, INFO, WARN or ERROR to change the verbosity

- TF_LOG_PATH sends the log output to be appended to a specific file: 

        o   set TF_LOG_PATH=./terraform.log

- Can use “terraform output <name>” to view variable values


Dynamic blocks

- Can dynamically construct repeating blocks:


variable "sg_ports" {
  type        = list(number)
  description = "list of ingress ports"
  default     = [8200, 8201,8300, 9200, 9500]
}
 
resource "aws_security_group" "dynamicsg" {
  name        = "dynamic-sg"
  description = "Ingress for Vault"
 
  dynamic "ingress" {
    for_each = var.sg_ports
    iterator = port
    content {
      from_port   = port.value
      to_port     = port.value
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    }
  }
}

- Can introduce “iterator” – name of the element to be set. If iterator is omitted – element name is derived from the name of the dynamic block itself (“ingress” above)


Taint

- “terraform taint <ex: aws_security_group.allow_all>” can be used to manually mark a resource as tainted and thus in need of being destroyed and recreated on next apply. 

- the command marks a resource as “tainted” in the .tfstate file

- careful to check the dependencies – ex: recreating an EC2 might change its IP


Splat

- [*] style expressions to represent the running and increasing total


Plan to graph or file

- “terraform graph > graph.dot” helps convert resource definition ns into a grap. Can us graphwiz tool for visual representation: 

        o   yum install graphwiz

        o   cat graph.dot | dot -Tsvg > graph.svg

        o   open svg (on frnt end) using graphwiz

- “terraform plan -out=demoplan” saves plan into a binary file. Can subsequently do “terraform apply demofile” to load directly from the file


Provisioners

- https://www.terraform.io/docs/provisioners/index.html

- The local-exec provisioner invokes a local executable after a resource is created. Ex: run an Ansilble playbook


resource "aws_instance" "web" {
  # ...
 
  provisioner "local-exec" {
    command = "echo ${aws_instance.web.private_ip} >> private_ips.txt"
  }
}

- Can add “when = destroy” to make it an destroy-time provisioner


- The remote-exec provisioner invokes a script on a remote resource after it is created


resource "aws_instance" "web" {
  # ...
 
  provisioner "remote-exec" {
    inline = [
      "puppet apply",
      "consul join ${aws_instance.web.private_ip}",
    ]
  }

- To ensure the remote provisioner can connect to the created resource, define a connection inside the provisioner block

- https://www.terraform.io/docs/provisioners/connection.html


  connection {
    type     = "ssh"
    user     = "root"
    password = "${var.root_password}"
    host     = "${var.host}"
  }

- Can tweak the connection to load a key from a local file

- Can set “on failure” to "continue" or "fail" to specify what should happen of the provisioner fails


Modules

- https://www.terraform.io/docs/configuration/modules.html

- A module is a container for multiple resources that are used together. DRY – do not repeat yourself. Ex: separate out an EC2 definition use it across multiple projects


module "ec2module" {
  source = "../../modules/ec2"
}


- Need to do “terraform init” when a new module is added

- Verified provider modules are available at the terraform registry: 

- https://registry.terraform.io/browse/modules

- https://github.com/terraform-aws-modules

- Can pull in modules directly from the terraform registry


module "consul" {
  source  = "hashicorp/consul/aws"
  version = "0.0.5"
 
  servers = 3
}

- Can pull from Git: source  = "git::https://mystuff.com/stuff.git?ref=1.2.0"

- Can do git::ssh


Workspace

- https://www.terraform.io/docs/cloud/workspaces/index.html

- A way of organizing infrastructure. Ex: dev/uat/prod

- “terraform workspace”


resource "aws_instance" "myec2" {
   ami = "ami-082b5a644766e0e6f"
   instance_type = lookup(var.instance_type,terraform.workspace)
}
 
variable "instance_type" {
  type = "map"
 
  default = {
    default = "t2.nano"
    dev     = "t2.micro"
    prd     = "t2.large"
  }
}

- The above will do the instance type lookup based on the name of the current workspace


Backends

- https://www.terraform.io/docs/backends/index.html

- If storing code in github or like, bet proactive is to avoid storing .tfstate, variables etc. in a public repo to avoid exposing secrets. This can be worked around with .gitignore: 

        o   https://www.terraform.io/docs/backends/types/index.html

- Nonpublic storage options exist:

        o   https://www.terraform.io/docs/backends/types/index.html

- Need to be careful as automatic state locking of files at backend is not available with all backends   Example: s3 allows file overwrites, need to implement locking manually using dynamoDb:


terraform {
  backend "s3" {
    bucket = "<remote-backend_bucket_name>"
    key    = "myproject.tfstate"
    region = "us-east-1"
    access_key = "<access_key>"
    secret_key = "<secret_key>"
    dynamodb_table = "<state_lock_tabel_name>"
  }
}

State

- https://www.terraform.io/docs/state/index.html

- Manipulate the content of .tfstate directly - helps avoid destroying/recreating resources, etc.

        o   terraform state list

        o   terraform state pull

- useful for team collaboration


Import

- https://www.terraform.io/docs/import/index.html

- https://learn.hashicorp.com/tutorials/terraform/state-import

- Can import configuration of an existing resource created outside of terraform

- Writes into the state file only

- Need to manually define the resource first to be able map it out uniquely 


Alias / Profile

- By default, terraform operates in one region per provider

- Can add alias to provider definition to introduce additional regions / availability zones


provider "aws" {
  region     =  "us-west-1"
}
 
provider "aws" {
  alias      =  "awsEast"
  region     =  " us-east-1"
  profile    =  "account2"
}
 
resource "aws_eip" "myeipEast" {
  vpc = "true"
  provider = "aws.awsEast"
}

- Can add a profile setting to the resource definition as well as to the credentials file if need to operate on separate provider accounts 


Alias / Profile

- Can integrate with AWS STS to assume a pre-define role

- https://support.hashicorp.com/hc/en-us/articles/360041289933-Using-AWS-AssumeRole-with-the-AWS-Terraform-Provider