Templatefile and Bash script - bash

I need to be able to run bash script as userdata for launchtemplate and this is how I try to do it :
resource "aws_launch_template" "ec2_launch_template" {
name = "ec2_launch_template"
image_id = data.aws_ami.latest_airbus_ami.id
instance_type = var.instance_type[terraform.workspace]
iam_instance_profile {
name = aws_iam_instance_profile.ec2_profile.name
}
vpc_security_group_ids = [data.aws_security_group.default-sg.id, aws_security_group.allow-local.id] # the second parameter should be according to the user
monitoring {
enabled = true
}
block_device_mappings {
device_name = "/dev/sda1"
ebs {
volume_size = 30
encrypted = true
volume_type = "standard"
}
}
tags = {
Name = "${var.app_name}-${terraform.workspace}-ec2-launch-template"
}
#user_data = base64encode(file("${path.module}/${terraform.workspace}-script.sh")) # change the base encoder as well
user_data = base64encode(templatefile("${path.module}/script.sh", {app_name = var.app_name, env = terraform.workspace, high_threshold = var.high_threshold, low_threshold = var.low_threshold})) # change the base encoder as well
}
as you can see, I pass parameters as map in the "templatefile" function, I managed to retrieve them doing this :
#!/bin/bash -xe
# Activate logs for everything
exec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1
# Retrieve variables from Terraform
app_name = ${app_name}
environment = ${env}
max_memory_perc= ${high_threshold}
min_memory_perc= ${low_threshold}
instance_id=$(wget -q -O - http://169.254.169.254/latest/meta-data/instance-id)
ami_id=$(wget -q -O - http://169.254.169.254/latest/meta-data/ami-id)
instance_type=$(wget -q -O - http://169.254.169.254/latest/meta-data/instance-type)
scale_up_name=$${app_name}"-"$${environment}"-scale-up"
scale_down_name=$${app_name}"-"$${environment}"-scale-down"
Then, when I look at launchtemplate in AWS console, I can see that the values used in parameters are filled in :
app_name = test-app
environment = prod
max_memory_perc= 80
min_memory_perc= 40
the problem that I have is, when I run that, I get this error :
+ app_name = test-app
/var/lib/cloud/instances/scripts/part-001: line 7: app_name: command not found
I assume there is a problem with interpretation or something like that but cannot put the finger on it
any ideas ?
Thanks

As they said, it was a problem with spaces, it's fixed now
thanks

Related

Terraform failing to render with invalid character

I have a terraform script that deploys a linux VM into azure, snippet below
data "template_file" "setup_script" {
template = file("myscript.sh")
}
resource "azurerm_linux_virtual_machine" "myterraformvm" {
name = var.vmname
location = var.zone
resource_group_name = azurerm_resource_group.myresourcegroup.name
network_interface_ids = [azurerm_network_interface.myterraformnic.id]
size = "Standard_DS1_v2"
os_disk {
name = "myOsDisk"
caching = "ReadWrite"
storage_account_type = "Premium_LRS"
}
source_image_reference {
publisher = "Canonical"
offer = "UbuntuServer"
sku = "16.04-LTS"
version = "latest"
}
computer_name = var.vmname
admin_username = "myusername"
disable_password_authentication = true
custom_data = base64encode(data.template_file.setup_script.rendered)
tags = {
environment = var.envname
}
}
On boot I want to run the script myscript.sh which derives from template_file. It looks like this
#!/bin/bash
REMOTEHOST=8.8.8.8
REMOTEPORT=(22 80 443)
TIMEOUT=1
for i in "${REMOTEPORT[#]}"; do
if nc -w 1 -z 8.8.8.8 $i; then
echo "I was able to connect via $i" >> /tmp/output.txt
else
echo "Connection failed on $i. Exit code from Netcat was ($?)." >> /tmp/output.txt
fi
done
When i run terraform apply it get the following error
fatal: [localhost]: FAILED! => changed=false
msg: |-
Terraform plan could not be created
STDOUT:
STDERR:
Error: failed to render : <template_file>:6,24-25: Invalid character; This character is not used within the language., and 1 other diagnostic(s)
on main.tf line 134, in data "template_file" "setup_script":
134: data "template_file" "setup_script" {
The bash script works fine if i run it locally and works in the terraform deployment if I remove the for loop/'#' character and just do a static run. Is there a way to loop over an array in a bash file and deploy it on azurerm_linux_virtual_machine?

Nomad job using exec fails when running any bash command

I have tried everything and I just can’t get an exec type job to run. I tried it on 3 different clusters and it fails on all.
The job prunes docker containers and just runs docker system prune -a.
This is the config section:
driver = "exec"
config {
command = "bash"
args = ["-c",
" docker system prune -a "]
}
No logs and containers are not pruned:
job "docker-cleanup" {
type = "system"
constraint {
attribute = "${attr.kernel.name}"
operator = "="
value = "linux"
}
datacenters = ["dc1"]
group "docker-cleanup" {
restart {
interval = "24h"
attempts = 0
mode = "fail"
}
task "docker-system-prune" {
driver = "exec"
config {
command = "bash"
args = ["-c",
" docker system prune -a "]
}
resources {
cpu = 100
memory = 50
network {
mbits = 1
}
}
}
}
}
What am I doing wrong?
I would suggest you provide the output to make it easier to analyze.
One thing you can try, is to add the full path to the bash executable.
driver = "exec"
config {
command = "/bin/bash"
args = ["-c",
" docker system prune -a "]
}
Further you are missing the "--force" parameter on system prune, without it - docker system prune asks for confirmation.
docker system prune --all --force
As I know all args should be provided separately:
driver = "exec"
config {
command = "/bin/bash"
args = [
"-c", "docker", "system", "prune", -a "
]
}

Why does terraform aws code fail to render?

Terraform version = 0.12
resource "aws_instance" "bespin-ec2-web" {
ami = "ami-0bea7fd38fabe821a"
instance_type = "t2.micro"
vpc_security_group_ids = [aws_security_group.bespin-sg.id]
subnet_id = aws_subnet.bespin-subnet-public-a.id
associate_public_ip_address = true
tags = {
Name = "bespin-ec2-web-a"
}
user_data = data.template_file.user_data.rendered
}
data "template_file" "user_data" {
template = file("${path.module}/userdata.sh")
}
userdata.sh file
#!/bin/bash
USERS="bespin"
GROUP="bespin"
for i in $USERS; do
/usr/sbin/adduser ${i};
/bin/echo ${i}:${i}1! | chpasswd;
done
cp -a /etc/ssh/sshd_config /etc/ssh/sshd_config_old
sed -i 's/PasswordAuthentication no/#PasswordAuthentication no/' /etc/ssh/sshd_config
sed -i 's/#PasswordAuthentication yes/PasswordAuthentication yes/' /etc/ssh/sshd_config
systemctl restart sshd
terraform plan result
Error: failed to render : <template_file>:5,24-25: Unknown variable; There is no variable named "i"., and 2 other di
agnostic(s)
on instance.tf line 13, in data "template_file" "user_data":
13: data "template_file" "user_data" {
Why am I getting an error?
The template argument in the template_file data source is processed as Terraform template syntax.
In this syntax, using ${...} has a special meaning, that the ... part will be injected by some var that is passed into the template.
Bash also allows this syntax, for getting the values of variables as you're intending to use it.
To reconcile this, you'll need to escape the $ character so that the terraform template compiler will leave it be, which you can do by doubling up the character: $${i} in all cases.
https://www.terraform.io/docs/configuration/expressions.html#string-templates

Issue using Terraform EC2 Userdata

I am deploying a bunch of EC2 instances that require a mount called /data, this is a seperate disk that I am attaching using volume attach in AWS.
Now when I did the following manually it works fine, so the script I use works however when adding it via userdata I am seeing issues and the mkfs command is not happening.
If you see my terraform config:
resource "aws_instance" "riak" {
count = 5
ami = "${var.aws_ami}"
vpc_security_group_ids = ["${aws_security_group.bastion01_sg.id}","${aws_security_group.riak_sg.id}","${aws_security_group.outbound_access_sg.id}"]
subnet_id = "${element(module.vpc.database_subnets, 0)}"
instance_type = "m4.xlarge"
tags {
Name = "x_riak_${count.index}"
Role = "riak"
}
root_block_device {
volume_size = 20
}
user_data = "${file("datapartition.sh")}"
}
resource "aws_volume_attachment" "riak_data" {
count = 5
device_name = "/dev/sdh"
volume_id = "${element(aws_ebs_volume.riak_data.*.id, count.index)}"
instance_id = "${element(aws_instance.riak.*.id, count.index)}"
}
And then the partition script is as follows:
#!/bin/bash
if [ ! -d /data ];
then mkdir /data
fi
/sbin/mkfs -t ext4 /dev/xvdh;
while [ -e /dev/xvdh ] ; do sleep 1 ; done
mount /dev/xvdh /data
echo "/dev/xvdh /data ext4 defaults 0 2" >> /etc/fstab
Now when I do this via terraform the mkfs doesn't appear to happen and I see no obvious errors in the syslog. If I copy the script manually and just bash script.sh the mount is created and works as expected.
Has anyone got any suggestions here?
Edit: It's wort noting adding this in AWS gui under userdata also works fine.
You could try with remote_exec instead of user_data.
User_data relates on cloud-init which can act differently depending on images of your cloud provider.
And also i'm not sure it's a good idea to exec a script that would wait for some time before executing in the cloud-init section => this may lead to VM considering launch has failed because of a timeout (depending on your cloud provider).
Remote_exec may be better here because you will be able to wait until your /dev/xvdh is attached
See here
resource "aws_instance" "web" {
# ...
provisioner "file" {
source = "script.sh"
destination = "/tmp/script.sh"
}
provisioner "remote-exec" {
inline = [
"chmod +x /tmp/script.sh",
"/tmp/script.sh args",
]
}
}

replace code block in terraform file

I am running a build on my Jenkins server and I am looking to dynamically populate the git_commit field with the commit number from the current build. The file has multiple functions in it and I want to use sed to match core-lambda-function1 name of the module and update the git_commit field with the commit number from the current build. Any help is appreciated. Thanks.
module "core-lambda-function1" {
source = "./lambda"
name = "core-lambda-function"
runtime = "nodejs6.10"
role = "${aws_iam_role.iam_role_for_lambda.arn}"
filename = "../Archive.zip"
source_code_hash = "${base64sha256(file("../Archive.zip"))}"
source_dir = "../"
git_commit = ""
}
module "core-lambda-function2" {
source = "./lambda"
name = "core-lambda-function"
runtime = "nodejs6.10"
role = "${aws_iam_role.iam_role_for_lambda.arn}"
filename = "../Archive.zip"
source_code_hash = "${base64sha256(file("../Archive.zip"))}"
source_dir = "../"
git_commit = ""
}
this is what i currently have.
#!/bin/bash
set -e
while read p; do
NAME=$p
GIT_COMMIT=`git rev-parse HEAD`
echo $NAME | grep `xargs` main.tf -A 7 | sed -ri '7s/git_commit = ""/git_commit\ = \"'$GIT_COMMIT'"/g'
done < build_name
Why not Input Variables in Terraform?
variable "git_commit" {}
module "core-lambda-function1" {
source = "./lambda"
name = "core-lambda-function"
runtime = "nodejs6.10"
role = "${aws_iam_role.iam_role_for_lambda.arn}"
filename = "../Archive.zip"
source_code_hash = "${base64sha256(file("../Archive.zip"))}"
source_dir = "../"
git_commit = "${var.git_commit}" #### Use variable here.
}
So in your wrapper script, you can update to:
#!/bin/bash
set -e
GIT_COMMIT=$(git rev-parse HEAD)
terraform plan -var 'git_commit=${GIT_COMMIT}' ...

Resources