5 # Copyright:: 2023, OpenStreetMap Foundation
7 # Licensed under the Apache License, Version 2.0 (the "License");
8 # you may not use this file except in compliance with the License.
9 # You may obtain a copy of the License at
11 # https://www.apache.org/licenses/LICENSE-2.0
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS,
15 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 # See the License for the specific language governing permissions and
17 # limitations under the License.
20 cache_dir = Chef::Config[:file_cache_path]
22 # Determine architecture of system for the AWS CLI download
29 awscli_version_suffix = if node[:awscli][:version] == "latest"
30 "" # latest version does not have a suffix
32 "-#{node[:awscli][:version]}"
35 awscli_zip = "awscliv2#{awscli_version_suffix}.zip"
37 # Ensure unpack directory is removed
38 directory "#{cache_dir}/awscli" do
43 # Remove any existing AWS CLI zip files, unless it's the one we're downloading
44 Dir.glob("#{cache_dir}/awscliv2*.zip").each do |zip|
45 next if zip == "#{cache_dir}/#{awscli_zip}"
53 # Download the AWS CLI zip file
54 remote_file "#{cache_dir}/#{awscli_zip}" do
55 source "https://awscli.amazonaws.com/awscli-exe-linux-#{awscli_arch}#{awscli_version_suffix}.zip"
63 # Extract the AWS CLI zip file
64 archive_file "#{cache_dir}/#{awscli_zip}" do
65 path "#{cache_dir}/#{awscli_zip}"
66 destination "#{cache_dir}/awscli"
69 subscribes :extract, "remote_file[#{cache_dir}/#{awscli_zip}]", :immediately
72 # Find the version of the AWS CLI we just downloaded
73 # Example version string: aws-cli/2.12.6 Python/3.11.4 Linux/5.15.49-linuxkit-pr exe/aarch64.ubuntu.22 prompt/off
74 # Install CLI to path: /opt/awscli/v2/current/bin/aws
75 ruby_block "install-awscli" do
78 awscli_version_string = shell_out("#{cache_dir}/awscli/dist/aws", "--version")
79 awscli_version = awscli_version_string.stdout.split(" ").first.split("/").last
81 install_dir = "/opt/awscli/v2/#{awscli_version}"
83 FileUtils.mkdir_p("#{install_dir}/bin/", :mode => 0755)
84 FileUtils.mv("#{cache_dir}/awscli/dist", "#{install_dir}/dist", :force => true)
85 FileUtils.ln_sf("#{install_dir}/dist/aws", "#{install_dir}/bin/aws")
86 FileUtils.ln_sf("#{install_dir}/dist/aws_completer", "#{install_dir}/bin/aws_completer")
88 FileUtils.rm_f("/opt/awscli/v2/current")
89 FileUtils.ln_sf(install_dir, "/opt/awscli/v2/current")
91 # Retain the last 5 versions, including the current one
92 versions = Dir.glob("/opt/awscli/v2/*").select { |dir| File.directory?(dir) && dir != "/opt/awscli/v2/current" }
93 versions.sort_by! { |dir| File.mtime(dir) }.reverse!
94 versions_to_delete = versions[5..] || []
96 versions_to_delete.each do |dir|
101 subscribes :run, "archive_file[#{cache_dir}/#{awscli_zip}]", :immediately