Network settings for Terraform aws_launch_template? - terraform

Terraform v0.12.x
I'm trying to create an AWS launch template using of course the aws_launch_template resource, and trying to relate to what the AWS console gives me when I try to create a launch template there. In the AWS console, I see the "Network settings" option seen in screen shot.
However, but I don't see a corresponding setting for the Terraform resource? Is that correct? I think I need to set it because when I try to create a spot fleet request, using Terraform's aws_spot_fleet_request resource, and using the launch template created by Terraform, it defaults to the "EC2-Classic" setting, which doesn't work for me. I get this error
Error: Error requesting spot fleet: InvalidSpotFleetRequestConfig: Invalid: (InstanceType: r5a.xlarge with Os: Linux/UNIX and EC2-Classic)
How can I fix this?

Ah, in the aws_spot_request resource, add an overrides that specifies a subnet id, which will of course put the instances in a VPC
resource "aws_spot_fleet_request" "jenkins_build_fleet" {
...
launch_template_config {
launch_template_specification {
id = module.launch_template.id
version = module.launch_template.version
}
overrides {
subnet_id = "subnet-12345abcde"
}
}
}

Related

Azure - Create Function App hostkey with Terraform azapi/bicep/powershell

I'm working on automating the rotation of my azure function app's host key, which is used to maintain a more secure connection between my API Management and my function apps. The issue is that I can not figure out how to accomplish this based on the lack of clear documentation. I found a document for how to create a key for a specific function within the function app, but not for the host level. I've tried using the web ui resource manager to figure out what the proper values are, but host seems to have no values available by GET request to help me see what the formatting needs to be. In fact, I can't find any reference to my function app's host keys anywhere in the resource manager UI. (Of course I can in the portal).
I don't care if it's powershell, bicep, ARM, terraform azapi, whatever, I'd just like to find a way to accomplish the creation of a new hostkey so that I can control it's rotation with terraform. Does anyone know how to accomplish this?
Right now my attempt looks like
resource "azapi_resource" "function_host_key" {
type = "Microsoft.Web/sites/host/functionkeys#2018-11-01"
name = "${azurerm_windows_function_app.api_function.name}-host-key"
parent_id = "${azurerm_windows_function_app.api_function.id}/host"
body = jsonencode({
properties = {
name = "test-key-terraform"
value = "asdfasdfasdfasdfasdfasdfasdf"
}
})
}
I also tried
resource "azapi_resource" "function_host_key" {
type = "Microsoft.Web/sites#2018-11-01"
name = "${azurerm_windows_function_app.api_function.name}-host-key"
parent_id = "${azurerm_windows_function_app.api_function.id}/functionsAppKeys"
location = var.region
}
since it said the body was invalid, but this also throws an error due to there being no body. I'm wondering if this just isn't possible.
I also just tried
resource "azapi_resource" "function_host_key" {
type = "Microsoft.Web/host/functionkeys#2018-11-01"
name = "${azurerm_windows_function_app.api_function.name}-host-key"
parent_id = "${azurerm_windows_function_app.api_function.id}/host"
location = var.region
}
and the result said that it was expecting
parent_id of `parent_id is invalid`: expect ID of `Microsoft.Web/host`
so I'm not sure what that parent_id should be.
I found an example through a bash/powershell script using the azure rest API, but I get a 403 error when I attempt to do it, I can only assume because my function app is secured, but I'm not sure a good way to determine that.
There must be a way to create a key programmatically...
UPDATE
I believe that this has been purposely made impossible now to do with terraform and I need to, as grose and backwards as it may be, use a CLI command in my pipeline. I understand you can do this, but it is (ofc my opinion) that if I am using terraform, I have terraform manage something, not have random CLI commands outside of terraform doing things that TF should be able to manage.
I created a key using az functionapp keys set and that worked, and the output explicitly stated that the type of resource which was created was Microsoft.Web/sites/host/functionKeys, so I went to the Azure Resource Explorer to see what versions were available for this type, since it clearly exists.. and found that nope, azure does not have it listed.
What confuses me is that I see this being done w/ ARM templates and I believe that my code matches theirs, just I'm using AZAPI.. and I get a not found error. Giving up for now

Deploying and configuring Postgres server in Azure with Terraform

I'm deploying Azure Postgres Flexible Server with Terraform as described in GitHub. The configuration works as expected, no issues there. The only divination from that GitHub template is that I want to configure pgBouncer for Postgres which is now supported natively. I don't see a way how I can create this configuration (i.e., enable this feature).
I've done some research and discovered the configuration feature is not quite available (at least according to the open ticket in GitHub here). At the same time, one of the published replies suggests using azurerm_postgresql_flexible_server_configuration and this resource type is available in Terraform indeed. However, Microsoft documentation states that to enable and configure pgBouncer I need to introduce 7 parameters. I thought that to make the code tidier, I can use a list and foreach loop, like this:
locals {
pg_config = {
"pgbouncer.default_pool_size" : "50",
"pgBouncer.max_client_conn" : "5000",
"pgBouncer.pool_mode" : "TRANSACTION"
etc...
}
}
resource "azurerm_postgresql_flexible_server_configuration" "postgres_fs_config" {
for_each = local.pg_config
name = each.key
value = each.value
server_id = azurerm_postgresql_flexible_server.postgres-fs.id
}
Is this the best way to configure Postgres (without involving CDK)? Did I miss something?
Ok, I verified this approach and it works like a charm. Will stick to it for now.

How to prevent the instance getting deleted when creating new instance in terraform in a single code?

I have tried creating an instance using terraform by getting values either windows ami or linux ami using parameters in jenkins pipeline.
The loophole is :-
When I choose windows instance ,it creates instance in AWS, next time I choose linux ,windows gets deleted and newly Linux is created.
Expected Output
The old instance should not get deleted when creating the new one
I have tried using the following codes:-
provider "aws"{
region="us-east-1"
}
resource "aws_instance" "my-instance" {
ami = lookup(var.ami,var.name)
instance_type = "t2.micro"
count=1
key_name = "nits"
tags = {
Name = var.name
}
}
variable "ami" {
default = {
"Linux" = "ami-08e4e35cccc6189f4"
"Windows" = "ami-0d43d465e2051057f"
}
}
variable "name" {
default ="Linux"
}
pipeline{
agent any
tools{
terraform 'terra'
}
parameters{
choice(name:'ami', choices: ['Linux','Windows'])
choice(name:'Actions', choices:['apply','destroy'])
}
stages{
stage('Git checkout'){
steps{
//
}
}
stage('Terraform Init'){
steps{
sh label: '', script:'terraform init'
}
}
stage('Terraform apply'){
steps{
sh label:'',script:'terraform ${Actions} -var name="${ami}" --auto-approve'
}
}
}
}
If I can try with modules, kindly suggest me the ways.
The Terraform language is declarative, meaning what you described using your terraform configuration is the intended goal rather than the steps to reach that goal. No matter how many times you run the pipeline terraform will make sure that only one resource get provisioned (because in your configuration you have only placed one aws_instance) and then maintain the infrastructure information in terraform.tf state file
For your expected output there are quite a few ways:
Add a stage in the pipeline before the terraform commands which will add a example.tf file with the content :
resource "aws_instance" "my-other-instance" {
/......
}
Make sure to add example.tf in the same directory as the previous tf files.
So every time you run the pipeline a new instance will be created without others getting deleted.
But here you need to adjust the variables so that every new instance gets different ami and name.
Add a stage in the pipeline before the terraform commands which deletes the terraform.tf state file so that terrform forgets the infrastructure it built the previous time and then init and apply.
That's not how Terraform works. You are trying to use Terraform as a scripting language, but it is not a scripting language. Terraform templates are not scripts, they are a declarative template to specify what infrastructure you want to exist, which you then pass to Terraform, which does what it needs to do in order to make that infrastructure exist. If you run it again with changes, then you are telling it: "I want you to change what currently exists, to match this new template".
If you want both resources to exist, then you have to declare them both separately in Terraform.
If you want to build some sort of interactive pipeline that creates EC2 instances on demand, then you may want to build that with a scripting language like Python + Boto3, instead of Terraform.

terraform lifecycle prevent destroy

I am working with Terraform V11 and AWS provider; I am looking for a way to prevent destroying few resources during the destroy phase. So I used the following approach.
lifecycle {
prevent_destroy = true
}
When I run a "terraform plan" I get the following error.
the plan would destroy this resource, but it currently has
lifecycle.preven_destroy set to true. to avoid this error and continue with the plan.
either disable or adjust the scope.
All that I am looking for is a way to avoid destroying one of the resources and its dependencies during the destroy command.
AFAIK This feature is not yet supported
You need to remove that resource from state file and then reimport it
terraform plan | grep <resource> | grep id
terraform state rm <resource>
terraform destroy
terraform import <resource> <ID>
The easiest way to do this would be to comment out all of the the resources that you want to destroy and then do a terraform apply.
I've found the most practical way to manage this is through a combination of variables that allow the resource in question to be conditionally created or not on via the use of count, alongside having all other resources depend on the associated Data Source instead of the conditionally created resource.
A good example of this is a Route 53 Hosted Zone which can be a pain to destroy and recreate if you manage your domain outside of AWS and need to update your nameservers, waiting for DNS propagation each time you spin it up.
1. By specifying some variable
variable "should_create_r53_hosted_zone" {
type = bool
description = "Determines whether or not a new hosted zone should be created on apply."
}
2. you can use it alongside count on the resource to conditionally create it.
resource "aws_route53_zone" "new" {
count = var.should_create_r53_hosted_zone ? 1 : 0
name = "my.domain.com"
}
3. Then, by following up with a call to the associated Data Source
data "aws_route53_zone" "existing" {
name = "my.domain.com"
depends_on = [
aws_route53_zone.new
]
}
4. you can give all other resources consistent access to the resource's attributes regardless of whether or not your flag has been set.
resource "aws_route53_record" "rds_reader_endpoint" {
zone_id = data.aws_route53_zone.existing.zone_id
# ...
}
This approach is only slightly better than commenting / uncommenting resources during apply, but at least gives some consistent, documented way of working around it.

How to use multiple Terraform Providers sequentially

How can I get Terraform 0.10.1 to support two different providers without having to run 'terraform init' every time for each provider?
I am trying to use Terraform to
1) Provision an API server with the 'DigitalOcean' provider
2) Subsequently use the 'Docker' provider to spin up my containers
Any suggestions? Do I need to write an orchestrating script that wraps Terraform?
Terraform's current design struggles with creating "multi-layer" architectures in a single configuration, due to the need to pass dynamic settings from one provider to another:
resource "digitalocean_droplet" "example" {
# (settings for a machine running docker)
}
provider "docker" {
host = "tcp://${digitalocean_droplet.example.ipv4_address_private}:2376/"
}
As you saw in the documentation, passing dynamic values into provider configuration doesn't fully work. It does actually partially work if you use it with care, so one way to get this done is to use a config like the above and then solve the "chicken-and-egg" problem by forcing Terraform to create the droplet first:
$ terraform plan -out=tfplan -target=digitalocean_droplet.example
The above will create a plan that only deals with the droplet and any of its dependencies, ignoring the docker resources. Once the Docker droplet is up and running, you can then re-run Terraform as normal to complete the setup, which should then work as expected because the Droplet's ipv4_address_private attribute will then be known. As long as the droplet is never replaced, Terraform can be used as normal after this.
Using -target is fiddly, and so the current recommendation is to split such systems up into multiple configurations, with one for each conceptual "layer". This does, however, require initializing two separate working directories, which you indicated in your question that you didn't want to do. This -target trick allows you to get it done within a single configuration, at the expense of an unconventional workflow to get it initially bootstrapped.
Maybe you can use a provider instance within your resources/module to set up various resources with various providers.
https://www.terraform.io/docs/configuration/providers.html#multiple-provider-instances
The doc talks about multiple instances of same provider but I believe the same should be doable with distinct providers as well.
A little bit late...
Well, got the same Problem. My workaround is to create modules.
First you need a module for your docker Provider with an ip variable:
# File: ./docker/main.tf
variable "ip" {}
provider "docker" {
host = "tcp://${var.ip}:2375/"
}
resource "docker_container" "www" {
provider = "docker"
name = "www"
}
Next one is to load that modul in your root configuration:
# File: .main.tf
module "docker01" {
source = "./docker"
ip = "192.169.10.12"
}
module "docker02" {
source = "./docker"
ip = "192.169.10.12"
}
True, you will create on every node the same container, but in my case that's what i wanted. I currently haven't found a way to configure the hosts with an individual configuration. Maybe nested modules, but that didn't work in the first tries.

Resources