in AWS, is user_data executed before cloud-init? - cloud-init

I use terraform to create an EC2 instance, and I use user_data to place a file in /var/lib/cloud/scripts/per-once. This is not executed - my question now is: is cloud-init run before user_data?
===EDIT===
A longer reply to Dude0001's very helpful answer:
I have tried the following, now - this is my user_data:
#!/bin/bash
cat >/var/lib/cloud/scripts/per-once/install_mysql <<!
#cloud-config
package_update: true
packages:
- mysql-server
!
cat >>/root/.bashrc <<!
set -o vi
unalias -a
alias ll='ls -lp'
!
cat >>/home/admin/.bashrc <<!
set -o vi
unalias -a
alias ll='ls -lp'
!
cat /root/.vimrc <<!
set t_ti= t_te=
set compatible
set expandtab ts=2 sw=2 ai
!
cat >/home/admin/.vimrc <<!
set t_ti= t_te=
set compatible
set expandtab ts=2 sw=2 ai
!
This creates all the files, as expected (I'm really old-fashioned and don't like most of vim's new features). I tried to reboot after the instance was created: no mysqld. I changed the permissions, chmod 755 /var/lib/cloud/scripts/per-once/install_mysql, and rebooted: no result either (the reason I changed permissions is that it appears from the python code that cloud-init looks for executables only).
===EDIT===
Some explanations to my user_data above:
This construction may mystify some, since it isn't too common:
cat >/some/path/to/a/file <<!
...
!
cat is a command that simply read from the standard input and writes to the standard output without change - it is often used with redirection < and >. In the construction above, I direct any output to a file /some/path/to/a/file. The other part, involving <<! and ! is known as a here document, something that has its origin in the JCL language used on mainframes, I suspect, but it is really useful. What is means is read the following lines until the end-marker (here: !, but it could be any string). So, all in all, it says create a file with the following content: ....
The first file, /var/lib/cloud/scripts/per-once/install_mysql, contains:
#cloud-config
package_update: true
packages:
- mysql-server
My hope is that this should tell cloud-init to update the package repository and install mysql-server - this doesn't happen.
The next 4 files are just some setup in the root and admin users' environments; basically, I create a .vimrc and add a few lines to .bashrc to ensure that certain things are set up to my liking.
The files are all created, but the one with #cloud-config doesn't seem to get touched at all. I have done a few experiments yesterday, by placing this file in different directories under /var/lib/cloud/scripts/, but it looks a lot as if these files aren't in place for when cloud-init reads the directories. Reading through cloud-init's source code, it looks as if it runs through 10 stages - user_data is fetched in stage 5, and it should be read in stage 7. I can also see that it seems to require the execute permission bit to be set; however this is what is in the log after a reboot:
2019-10-02 08:06:52,884 - handlers.py[DEBUG]: start: modules-final/config-scripts-per-boot: running config-scripts-per-boot with frequency always
2019-10-02 08:06:52,884 - helpers.py[DEBUG]: Running config-scripts-per-boot using lock (<cloudinit.helpers.DummyLock object at 0x7f677362acc0>)
2019-10-02 08:06:52,885 - util.py[DEBUG]: Running command ['/var/lib/cloud/scripts/per-boot/install_mysql'] with allowed return codes [0] (shell=False, capture=False)
2019-10-02 08:06:52,887 - util.py[WARNING]: Failed running /var/lib/cloud/scripts/per-boot/install_mysql [-]
2019-10-02 08:06:52,887 - util.py[DEBUG]: Failed running /var/lib/cloud/scripts/per-boot/install_mysql [-]
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/cloudinit/util.py", line 1992, in subp
env=env, shell=shell)
File "/usr/lib/python3.7/subprocess.py", line 775, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.7/subprocess.py", line 1522, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
OSError: [Errno 8] Exec format error: b'/var/lib/cloud/scripts/per-boot/install_mysql'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/cloudinit/util.py", line 835, in runparts
subp(prefix + [exe_path], capture=False)
File "/usr/lib/python3/dist-packages/cloudinit/util.py", line 2000, in subp
stderr="-" if decode else b"-")
cloudinit.util.ProcessExecutionError: Exec format error. Missing #! in script?
Command: ['/var/lib/cloud/scripts/per-boot/install_mysql']
Exit code: -
Reason: [Errno 8] Exec format error: b'/var/lib/cloud/scripts/per-boot/install_mysql'
Stdout: -
Stderr: -
2019-10-02 08:06:52,897 - cc_scripts_per_boot.py[WARNING]: Failed to run module scripts-per-boot (per-boot in /var/lib/cloud/scripts/per-boot)
2019-10-02 08:06:52,898 - handlers.py[DEBUG]: finish: modules-final/config-scripts-per-boot: FAIL: running config-scripts-per-boot with frequency always
2019-10-02 08:06:52,898 - util.py[WARNING]: Running module scripts-per-boot (<module 'cloudinit.config.cc_scripts_per_boot' from '/usr/lib/python3/dist-packages/cloudinit/config/cc_scripts_per_boot.py'>) failed
2019-10-02 08:06:52,898 - util.py[DEBUG]: Running module scripts-per-boot (<module 'cloudinit.config.cc_scripts_per_boot' from '/usr/lib/python3/dist-packages/cloudinit/config/cc_scripts_per_boot.py'>) failed
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/cloudinit/stages.py", line 800, in _run_modules
freq=freq)
File "/usr/lib/python3/dist-packages/cloudinit/cloud.py", line 54, in run
return self._runners.run(name, functor, args, freq, clear_on_fail)
File "/usr/lib/python3/dist-packages/cloudinit/helpers.py", line 187, in run
results = functor(*args)
File "/usr/lib/python3/dist-packages/cloudinit/config/cc_scripts_per_boot.py", line 41, in handle
util.runparts(runparts_path)
File "/usr/lib/python3/dist-packages/cloudinit/util.py", line 842, in runparts
% (len(failed), len(attempted)))
RuntimeError: Runparts: 1 failures in 1 attempted commands
So, it definitely doesn't like the format of the file - it wants to see a #!... or perhaps a binary executable.
I will try out Dude0001's suggestions in more detail now.
===EDIT===
In the end, what does work is using the multipart/mixed format, as suggested by Dude0001:
Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0
--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"
#cloud-config
package_update: yes
package_upgrade: all
packages:
- mariadb-server
- apt-file
--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"
#!/bin/bash
cat >>/root/.bashrc <<!
set -o vi
unalias -a
alias ll='ls -lp'
!
cat >>/home/admin/.bashrc <<!
set -o vi
unalias -a
alias ll='ls -lp'
!
cat /root/.vimrc <<!
set t_ti= t_te=
set compatible
set expandtab ts=2 sw=2 ai
!
cat >/home/admin/.vimrc <<!
set t_ti= t_te=
set compatible
set expandtab ts=2 sw=2 ai
!
--//
Just specifying #cloud-config doesn't seem to work, but this way does. For me, at least. In the present moment.

Short answer:
A user_data value set to a shell script will cause the given shell script to be ran during in the final stage of cloud-init (and I believe after the cloud-init directives in the one-time folder you reference).
If you want to use a custom cloud-init directive and a shell script both in EC2 user_data property you need to use the multipart/mixed mime format https://aws.amazon.com/premiumsupport/knowledge-center/execute-user-data-ec2/
Long answer:
The user_data can hold raw data to be read through the EC2 meta data, a script or a cloud-init directive. Additionally, you can set it up as a multipart/mixed mime type and provide each of these.
If user_data is raw data, it can be fetched with a curl command inside the EC2 instance. It is up to the calling command to interpret the data, it can be whatever the user chooses.
[ec2-user ~]$ curl http://169.254.169.254/latest/user-data
If user_data is a script (e.g. #!/bin/bash in the first line), it is ran as a step in cloud-init in the final stage of cloud-init https://cloudinit.readthedocs.io/en/latest/topics/boot.html#final.
If user_data is a cloud-init directive (e.g. #cloud-config in the first line), it is ran as the specified cloud-init directive.
From https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html#user-data-cloud-init
"To pass cloud-init directives to an instance with user_data... enter your cloud-init directive text in the user_data text."
Like so
#cloud-config
repo_update: true
repo_upgrade: all
packages:
- httpd
- mariadb-server
runcmd:
- [ sh, -c, "amazon-linux-extras install -y lamp-mariadb10.2-php7.2 php7.2" ]
- systemctl start httpd
- sudo systemctl enable httpd
- [ sh, -c, "usermod -a -G apache ec2-user" ]
- [ sh, -c, "chown -R ec2-user:apache /var/www" ]
- chmod 2775 /var/www
- [ find, /var/www, -type, d, -exec, chmod, 2775, {}, \; ]
- [ find, /var/www, -type, f, -exec, chmod, 0664, {}, \; ]
- [ sh, -c, 'echo "<?php phpinfo(); ?>" > /var/www/html/phpinfo.php' ]
The multipart/mixed mime format is described here https://aws.amazon.com/premiumsupport/knowledge-center/execute-user-data-ec2/, with the example
Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0
--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"
#cloud-config
cloud_final_modules:
- [scripts-user, always]
--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"
#!/bin/bash
/bin/echo "Hello World" >> /tmp/testfile.txt
--//

Related

Create tar into stdout on Ubunutu 16

tar cannot write to standard output on Ubuntu 16:
prod ~ $ cat /etc/os-release | grep -i version
VERSION="16.04.2 LTS (Xenial Xerus)"
VERSION_ID="16.04"
VERSION_CODENAME=xenial
prod ~ $ tar -cf - tmp
tar: Refusing to write archive contents to terminal (missing -f option?)
tar: Error is not recoverable: exiting now
Let's try on CentOS7:
[root#drft068 ~]# tar -cf - /tmp
tar: Removing leading `/' from member names
tar: /tmp/mongodb-27018.sock: socket ignored
tar: /tmp/mongodb-27017.sock: socket ignored
tmp/00017770000000000000000000000000131574472010
What do I do wrong?
To have a proper SO answer here, I condensed #Kamajii and #Cyrus comments to the questions (please consider doing that yourselves ...).
tar notices that stdout will end up on a terminal. Besides the output is binary and thus not really readable for humans it is also a security risk.
As soon as you redirect stdout of the tar process, it will work. One example given involves cat, which doesnt care if you give it a binary blob. Thus
tar -cf - tmp | cat
will display the binary stuff. Otherwise tar -cf - tmp > mytmp.tar is probably closer than what you want to use (although for this example a tar -cf mytmp.tar tmp would have been the typical call).

sed in script creating corrupt .tar.gz file

I am installing a program which has a file "drown.bin" (Bourne shell script text executable).
When I execute this file as part of the process, it gives error
gzip: stdin: unexpected end of file
tar: Child returned status 1
tar: Error exit delayed from previous errors
Below are file contents (pasted only Bash portion, rest is machine language)
dir_tmp=/tmp/.$(date +"%y%m%d%H%M%S")
mkdir /$dir_tmp >/dev/null
sed -n -e '1,/^exit 0$/!p' $0 > "${dir_tmp}/.make-3000.tar.gz" 2>/dev/null
cd $dir_tmp >/dev/null
tar xvfz .make*.tar.gz >/dev/null
./.make
rm -rf $dir_tmp >/dev/null
exit 0
Can someone please advise what goes wrong in "sed" command to create a corrupted .tar.gz file. I already tried 3 systems with different CentOS versions.
It's not the sed command that fails, but the tar command.
This is a "self-extracting" tar file. The script that sits in front attempts to unpack the rest of the file, starting after the line exit 0. Likely the rest of the file is somehow corrupt.
If you downloaded it, try that again. If you copied it from somewhere else (especially FTP) make sure you used binary mode.
If that didn't work, what you could try to do:
copy the script-file to a file with extension .tgz, e.g. cp drown.bin mycopy.tgz
edit the copy, removing all script lines up to and including the exit 0 line. The file now should be a pure tar.gz file.
on the command line, do a tar tzvf mycopy.tgz to see the contents. Try tar xzvf mycopy.tgz to actually unpack. This likely will fail with just the same error you got first, but at least now you can see the extracted content, at least the part that didn't fail.

procmail not piping e-mail content to a file

I have a postfix server and procmail installed and working.
The problem is when I try to output the content of an e-mail to a file.
I have the following script:
/var/log/user1/fooscript.sh
#!/bin/bash
echo "Trying to get e-mail" > success.txt
echo $1 >> success.txt
/var/log/user1/.procmailrc
VERBOSE=off
PMDIR=$HOME/.procmail
LOGFILE=$PMDIR/procmail.log
INCLUDERC=$PMDIR/rc.filters
/var/log/user1/.procmail/rc.filters
:0
* ^From:(.*\<)?(test#gmail\.com)\>
| /var/log/user1/fooscript.sh
After sending an e-mail, /var/log/user1/.procmail/rc.filters
contains:
From test#gmail.com Thu Jul 18 05:08:13 2013
Folder: /var/log/user1/fooscript.sh 513
but the success file only shows:
Trying to get e-mail
(empty line)
I've chmod 777 all files and directories, so don't think its a permissions issue.
Any help would be greatly appreciated.
Your script gets the message via standard input (STDIN). Try:
#!/bin/bash
echo "Trying to get e-mail" > success.txt
# append data read from STDIN to success.txt file
cat >> success.txt
BTW for more complicated scripts use custom lock to avoid running two scripts in parallel:
:0 w :fooscript.lock
* ^From:(.*\<)?(test#gmail\.com)\>
| /var/log/user1/fooscript.sh

sed+text on a specific line after an IP

I have the following line in my proftpd log (line 78 to be precise)
Deny from 1.2.3.4
I also have a script which rolls through my logs for people using brute force attacks and then stores their IP (ready for a black listing). What i'm struggling with is inserting (presume with sed) at the end of that specific line - this is what I've got so far:
sed "77i3.4.5.6" /opt/etc/proftpd.conf >> /opt/etc/proftpd.conf
Now one would presume this would work perfectly, however it actually does the following (lines 77 through 78):
3.4.5.6
Deny from 1.2.3.4
I suspect this is due to my dated version of sed, are there any other ways of acheiving the same thing? Also the >> causes the config to be duplicated at the end of the fole (again i'm sure this is a limitation of my version of sed). This is running a homebrew linux kernel on my nas. Sed options below:
root#NAS:~# sed BusyBox v1.7.0
(2009-04-29 19:12:57 JST) multi-call
binary
Usage: sed [-efinr] pattern [files...]
Options:
-e script Add the script to the commands to be executed
-f scriptfile Add script-file contents to the
commands to be executed
-i Edit files in-place
-n Suppress automatic printing of pattern space
-r Use extended regular expression syntax
If no -e or -f is given, the first
non-option argument is taken as the
sed script to interpret. All remaining
arguments are names of input files; if
no input files are specified, then the
standard input is read. Source files
will not be modified unless -i option
is given.
Cheers for your help guys.
This has nothing to do with the version of sed; this is just plain old Doing It Wrong.
sed -i '77s/$/,3.4.5.6/' /opt/etc/proftpd.conf

How to send special characters via mail from a shell script?

I have a script that runs on cron that outputs some text which we send to the 'mail' program. The general line is like this:
./command.sh | mail -s "My Subject" destination#address.com -- -F "Sender Name" -f sender#address.com
The problem is that the text generated by the script has some special characters - é, ã, ç - since it is not in english. When the e-mail is received, each character is replaced by ??.
Now I understand that this is most likely due to the encoding that is not set correctly. What is the easiest way to fix this?
My /usr/bin/mail is symlinked to /etc/alternatives/mail which is also symlinked to /usr/bin/bsd-mailx
I had to specify myself the encoding in the mail header. (The -S is not supported here.)
cat myutf8-file | mail -a "Content-Type: text/plain; charset=UTF-8" -s "My Subject" me#mail.com
You're right in assuming this is a charset issue. You need to set the appropriate environment variables to the beginning of your crontab.
Something like this should work:
LANG=en_US.UTF-8
LC_CTYPE=en_US.UTF-8
Optionally use LC_ALL in place of LC_CTYPE.
Reference: http://opengroup.org/onlinepubs/007908799/xbd/envvar.html
Edit: The reason it displays fine when you run it in your shell is probably because the above env vars are set in your shell.
To verify, execute 'locale' in your shell, then compare to the output of a cronjob that runs the same command.
Re-Edit: Ok, so it's not an env var problem.
I am assuming you're using mailx, as it is the most common nowdays. It's manpage says:
The character set for outgoing
messages is not necessarily the same
as the one used on the terminal. If an
outgoing text message contains
characters not representable in
US-ASCII, the character set being used
must be declared within its header.
Permissible values can be declared
using the sendcharsets variable,
So, try and add the following arguments when calling mail:
-S sendcharsets=utf-8,iso-8859-1
Just to give additional information to KumZ answer:
if you need to specify more headers with the -a switch, feel free to add them up, like this (note the polyusage of -a).
echo /path/to/file | mail -s "Some subject" recipient#theirdomain.com -a "From: Human Name <noreply#mydomain.com>" -a "Content-Type: text/plain; charset=UTF-8"
i've written a bash function to send an email to recipients. The function send utf-8 encoded mails and work with utf-8 chars in subject and content by doing a base64 encode.
To send a plain text email:
send_email "plain" "from#domain.com" "subject" "contents" "to#domain.com" "to2#domain.com" "to3#domain.com" ...
To send a HTML email:
send_email "html" "from#domain.com" "subject" "contents" "to#domain.com" "to2#domain.com" "to3#domain.com" ...
Here is the function code.
# Send a email to recipients.
#
# #param string $content_type Email content mime type: 'html' or 'plain'.
# #param string $from_address Sender email.
# #param string $subject Email subject.
# #param string $contents Email contents.
# #param array $recipients Email recipients.
function send_email() {
[[ ${#} -lt 5 ]] && exit 1
local content_type="${1}"
local from_address="${2}"
local subject="${3}"
local contents="${4}"
# Remove all args but recipients.
shift 4
local encoded_contents="$(base64 <<< "${contents}")"
local encoded_subject="=?utf-8?B?$(base64 --wrap=0 <<< "${subject}")?="
for recipient in ${#}; do
if [[ -n "${recipient}" ]]; then
sendmail -f "${from_address}" "${recipient}" \
<<< "Subject: ${encoded_subject}
MIME-Version: 1.0
From: ${from_address}
To: ${recipient}
Content-Type: text/${content_type}; charset=\"utf-8\"
Content-Transfer-Encoding: base64
Content-Disposition: inline
${encoded_contents}"
fi
done
return 0
} # send_message()
You may use sendmail command directly without mail wrapper/helper.
It would allow you to generate all headers required for "raw" UTF-8 body
(UTF-8 is mentioned in asker's comments),
WARNING-1:
Non 7bit/ASCII characters in headers (e.g. Subject:,From:,To:) require special encoding
WARNING-2:
sendmail may break long lines (>990 bytes).
SENDER_ADDR=sender#address.com
SENDER_NAME="Sender Name"
RECIPIENT_ADDR=destination#address.com
(
# BEGIN of mail generation chain of commands
# "HERE" document with all headers and headers-body separator
cat << END
Subject: My Subject
From: $SENDER_NAME <$SENDER_ADDR>
To: $RECIPIENT_ADDR
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
END
# custom script to generate email body
./command.sh
# END of mail generation chain of commands
) | /usr/sbin/sendmail -i -f$SENDER_ADDR -F"$SENDER_NAME" $RECIPIENT_ADDR
rfc2045 - (5) (Soft Line Breaks) The Quoted-Printable encoding REQUIRES that encoded lines be no more than 76 characters long. For bash shell script code:
#!/bin/bash
subject_encoder(){
echo -n "$1" | xxd -ps -c3 |awk -Wposix 'BEGIN{
BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
printf " =?UTF-8?B?"; bli=8
}
function encodeblock (strin){
b1=sprintf("%d","0x" substr(strin,1,2))
b2=sprintf("%d","0x" substr(strin,3,2))
b3=sprintf("%d","0x" substr(strin,5,2))
o=substr(BASE64,b1/4 + 1,1) substr(BASE64,(b1%4)*16 + b2/16 + 1,1)
len=length(strin)
if(len>1) o=o substr(BASE64,(b2%16)*4 + b3/64 + 1,1); else o=o"="
if(len>2) o=o substr(BASE64,b3%64 +1 ,1); else o=o"="
return o
}{
bs=encodeblock($0)
bl=length(bs)
if((bl+bli)>64){
printf "?=\n =?UTF-8?B?"
bli=bl
}
printf bs
bli+=bl
}END{
printf "?=\n"
}'
}
SUBJECT="Relatório de utilização"
SUBJECT=`subject_encoder "${SUBJECT}"`
echo '<html>test</html>'| mail -a "Subject:${SUBJECT}" -a "MIME-Version: 1.0" -a "Content-Type: text/html; charset=UTF-8" you#domain.net
This is probably not a command line issue, but a character set problem. Usually when sending E-Mails, the character set will be iso-8859-1. Most likely the text you are putting into the process is not iso-8859-1 encoded. Check out what the encoding is of whatever data source you are getting the text from.
Obligatory "good reading" link: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)
Re your update: In that case, if you enter the special characters manually, your terminal may be using UTF-8 encoding. You should be able to convert the file's character set using iconv for example. The alternative would be to tell mail to use UTF-8 encoding, but IIRC that is not entirely trivial.
use the option -o message-charset="utf-8", like that:
sendemail -f your_email -t destination_email -o message-charset="utf-8" -u "Subject" -m "Message" -s smtp-mail.outlook.com:587 -xu your_mail -xp your_password
I'm a bit late but none of the previous solutions worked for me.
Locating mail command (CentOS)
# locate mail | grep -v www | grep -v yum | grep -v share
# ls -l /bin/mail
lrwxrwxrwx. 1 root root 22 jul 21 2016 /bin/mail -> /etc/alternatives/mail
# ls -l /etc/alternatives/mail
lrwxrwxrwx. 1 root root 10 jul 21 2016 /etc/alternatives/mail -> /bin/mailx
# ls -l /bin/mailx
-rwxr-xr-x. 1 root root 390744 dic 16 2014 /bin/mailx
So mail command is in fact mailx. This helped with the search that finally took me to this answer at Unix&Linux Stackexchange that states:
Mailx expects input text to be in Unix format, with lines separated by newline (^J, \n) characters only. Non-Unix text files that use carriage return (^M, \r) characters in addition will be treated as binary data; to send such files as text, strip these characters e. g. by tr -d '\015'
From man page and:
If there are other control characters in the file they will result on mailx treating the data as binary and will then attach it instead of using it as the body. The following will strip all special characters and place the contents of the file into the message body
So the solution is using tr command to remove those special characters. Something like this:
./command.sh \
| tr -cd "[:print:]\n" \
| mail -s "My Subject" destination#address.com -- -F "Sender Name" -f sender#address.com
I've used this solution with my command
grep -v "pattern" $file \
| grep -v "another pattern" \
| ... several greps more ... \
| tr -cd "[:print:]\n" \
| mail -s "$subject" -a $file -r '$sender' $destination_email